Page 1 (index.php)
<?php for($i=0;$i<2;$i++) { ?>
<select id="name[<?php echo $i;?>]">
<option value="John">John</option>
<option value="Alice">Alice</option>
</select>
<input type="text" id="name-id">
<input type="text" id="location">
<?php } ?>
</table>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="js/function.js"></script>
Page 2 (function.js)
for (i=0;i<2;i++){
$('select#name['+i+']').on('change',function()
{ alert(1); } ); }
The Code is not working after i add in the array.. Someone please help me..
4 Answers 4
You have to escape the [] in the id, but rather do that, you'd better not introduce [] in id, the [] should be used in name attribute in common usage.
html:
<select id="name_<?php echo $i;?>" name="name[]">
js:
$('select#name_'+i).on('change',function() { //...
Or you could add a class and use class selector instead of id selector.
Comments
You need to escape the [] in id
for (var i = 0; i < 2; i++) {
$('#name\\[' + i + '\\]').on('change', function () {
alert(1);
});
}
also since id should be unique in a page there is no need for the element selector select
But I would recommend adding a class to select the similar select elements instead of using id
<select id="name[<?php echo $i;?>]" class="name">
<option value="John">John</option>
<option value="Alice">Alice</option>
</select>
then
$('select.name').on('change', function () {
alert(1);
});
2 Comments
name[i]= $('select#name\\[' + i + '\\]').val(); - you need to use \` not `You need to escape [ AND ] with \\ in front.
$('#name\\[' + i + '\\]').on('change', function () {
alert(1);
});
Comments
I think that is a bad idea to make identifiers look like an array. Maybe you can use 'data' attribute?
I edited your code a little:
HTML
<?php for($i=0;$i<2;$i++) { ?>
<select id="name" data-index="[<?php echo $i;?>]">
<option value="John">John</option>
<option value="Alice">Alice</option>
</select>
<input type="text" id="name-id">
<input type="text" id="location">
<?php } ?>
JS
$('body').on('change',"select#name", function () {
alert($(this).data("index"));
});
<input name="some_name[]" >