Photonic
Photonic

Reputation: 1421

dynamic input on change jquery

I have a dynamic input field which is being generated like this

var field = '<tr><td><input type="text" name="program_id" data-id="'+val['program_id']+'" value="'+val['program_id']+'">'+programBtn+'</td></tr>';
$('#transaction').append(field);
$('#transaction').on('change', 'input',function() {
    console.log('hi');
});

And i have a button that when i click, it will input data into that input field using

$('.button').on('click', function() {
    var text = $(this).data('text');
    var id = $(this).data('id');
    $('#transaction').find('input:'+id).val(text);
});

Ok if i click the button it will fill in those values but console.log('hi') isnt firing. But if i type in the text box and then i leave focus it, i can see console.log('hi') is firing. Note that code here is just an example.

My Jquery version is 3.2.1

Upvotes: 1

Views: 6938

Answers (2)

Saravanan I
Saravanan I

Reputation: 1229

You need to trigger change function as soon as you change the input value since change fn will be triggered only when the user changes the value manually and losses the focus. you can trigger that using .trigger('change') or change()

var field = '<tr><td><input type="text" name="program_id" data-id="11" value="test"></td></tr>';
$('#transaction').append(field);
$('#transaction').on('change','input',function() {
    console.log('hi');
});
$('button').on('click', function() {
    var text = $(this).data('text');
    var id = $(this).data('id');
    $('#transaction').find('input[data-id="'+ id +'"]').val(text).change();
    //$('#transaction').find('input[data-id="'+ id +'"]').val(text).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="transaction">Transaction: </div>
<button data-text="Some Text" data-id="11">Click</button>

Upvotes: 4

Chay22
Chay22

Reputation: 2894

I think you're finding input element that has data-id with value equal to data-id on the clicked button. If that so, you might use

$('#transaction').find('input[data-id="+ id +"]')

And from previous topic. onchange only fires when the user types into the input and then the input loses focus. So, you need to trigger the event manually.

$('.button').on('click', function() {
    var text = $(this).data('text');
    var id = $(this).data('id');
    $('#transaction').find('input[data-id="+ id +"]').val(text).change(); // trigger change event
});

Upvotes: 0

Related Questions