d_unknown
d_unknown

Reputation: 875

How to set the data-attribute of a button to whatever value set in an input [type=text]?

I have a modal and inside my modal is an input[type]. And I want to set default value and that default value is from a data-attribute of a button..

Here is my code:

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

and this:

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);
});

I can set the data-attribute of the button but the problem is if I change the value in the input textfield. The data-attribute doesn't change. How am I going to fix?

Upvotes: 2

Views: 7959

Answers (2)

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

How about using blur

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

});

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use jQuery change() event handler

$('#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>

or use keypress() event

$('#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>

Upvotes: 3

Related Questions