YVS1102 YVS1102 - 2 months ago 13
Javascript Question

Alert multiple column using javascript

I'm trying to

alert fields
. Here is my html

<table width="100%" id="example1" class="table table-bordered table-striped">
<tr>
<td> Nip </td>
<td> Nama Lengkap </td>
</tr>
<tr id='ke0'>

<td> <input class="form-control nipnya" type="text" name="nip[]" /> </td>

<td> <input class="form-control namanya" type="text" name="namalengkap[]" /> </td>
</tr>
<tr id='ke1'>

</tr>
</table>
<div>
<a id="add_row" class="btn btn-success pull-left">Tambah Baris Baru</a> &nbsp;&nbsp;&nbsp;
<a id="delete_row" class="pull-left btn btn-danger">Hapus Baris</a>
</div>


and i have this jquery

$(document).ready(function() {
$("#rmnya").change(function() {
$('#td11').html($("#rmnya").val());
});
var i = 1;
$("#add_row").click(function() {
$('#ke' + i).html('<td><input class="form-control nipnya" type="text" name="nip[]" /> </td>' +
'<td> <input class="form-control namanya" type="text" name="namalengkap[]" />' +
'</td>');
$('#example1').append('<tr id="ke' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#ke" + (i - 1)).html('');
i--;
}
});
});


As you can see from my script. There is only one Row
<tr></tr>
. I can alert it if it only one row. But when click
Tambah Baris Baru
there is another row showing up. I can't alert it. Here is my other javascript

$(".nipnya").change(function(){
$('.nipnya').each(function(i, obj) {
alert($('.nipnya').val());
});
});


So, can you tell me how to alert
after onchange
in every field that showing up dynamically.

Here is my fiddle https://jsfiddle.net/spc5884w/

Sorry for my bad english.

Answer

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.

General Syntax

$(staticParentElement).on('event','selector',callback_function)

Example

$('table').on('click', ".nipnya", function(){
    alert($(this).val());
});

DEMO