【问题标题】:How to set the data-attribute of a button to whatever value set in an input [type=text]?如何将按钮的数据属性设置为输入 [type=text] 中设置的任何值?
【发布时间】:2015-03-22 14:11:27
【问题描述】:

我有一个模态,我的模态内部是一个输入[类型]。我想设置默认值,该默认值来自按钮的数据属性..

这是我的代码:

 <input type="text" class="form-control" name="ID" id="ID" placeholder="Enter ID number"/>
                <button id="confirmation" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirm">Submit</button>

还有这个:

document.getElementById("ID").onmouseover = function() {
    var id=document.getElementById("ID").value;

    $('#confirmation').attr('data-id' , id); 

    return false;
};

$('#confirm').on('show.bs.modal', function (event)  {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var id = button.data('id') // Extract info from data-* attributes
    var modal = $(this)
    modal.find('.modal-body #IDN').val(id);
});

我可以设置button 的数据属性,但问题是如果我更改输入文本字段中的值。数据属性不会改变。我将如何修复?

【问题讨论】:

    标签: javascript jquery html bootstrap-modal custom-data-attribute


    【解决方案1】:

    使用 jQuery change() 事件处理程序

    $('#ID').change(function() {
      $('#confirmation').data('id', this.value);
      console.log($('#confirmation').data('id'));
    }).change();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="text" class="form-control" name="ID" id="ID" placeholder="Enter ID number" />
    <button id="confirmation" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirm">Submit</button>

    或使用keypress()事件

    $('#ID').keypress(function() {
      $('#confirmation').data('id', this.value);
      console.log($('#confirmation').data('id'));
    }).change();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="text" class="form-control" name="ID" id="ID" placeholder="Enter ID number" />
    <button id="confirmation" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirm">Submit</button>

    【讨论】:

    • 这确实有效,但它不会将 data-id 值更改为当前输入的值.. 它会将 data-id 设置为文本字段中输入的先前值.. :(
    • 如果您想在每次按键时更新,请使用第二种方法
    • 感谢您的时间和回答 :) 我改用模糊,因为当我尝试按键时,最后输入的字符不包括在内..
    【解决方案2】:

    用blur怎么样

    $('#ID').blur(function() {
      $('#confirmation').data('id', this.value);
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2010-11-28
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多