如何将按钮的数据属性设置为输入[type = text]中设置的任何值?

时间:2015-03-22 05:27:56

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

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

这是我的代码:

 <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的数据属性,但问题是我是否更改了输入文本字段中的值。数据属性不会改变。我该怎么办?

2 个答案:

答案 0 :(得分:3)

使用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>

答案 1 :(得分:1)

如何使用blur

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

});