ISSUE:
I had the following hidden input in some part of my page –
<input id="selectedOption" type="hidden" value="">
This hidden input was added to hold the ‘city name’, which was going to be populated in hidden input on some button click event.
For populating the value I wrote the following jQuery script:
$('#btnBloreCity').click(function(){
// alert($('#btnBloreCity').attr('value'));
$('#selectedOption').val($('#btnBloreCity').attr('value'));
});
The code seemed to be fine & was also executing without any error. But still value was not getting populated to “selectedOption” hidden input.
I re-verified the id of hidden input with the one used in the jQuery selector. But found it matching.
REASON:
After an hour of investigation, I found that one more hidden input field with same id was present before this hidden input. That’s the reason why on button click the value was not being populated to the hidden input.
jQuery Id Selector’s Behaviour:
When we use Id selector of jQuery $(‘#Id’) for finding element with specified Id & If two elements with same id are present in the DOM, then the selector returns you the first one.
Explaination:
(1) Add following two hidden inputs in your page inside body.
<input id="selectedOption" type="hidden" value="Mumbai"> <input id="selectedOption" type="hidden" value="Bangalore">
(2) Add following script within head tag of your page.
<script type="text/javascript">
$(document).ready(function(){
alert('Selected City: '+$('#selectedOption').val());
});
</script>
(3) View Page in browser.
So when the page is loaded, an alert pops up saying ‘Selected City: Mumbai’
Hope you got the basic point…
“Page should not have elements with duplicate IDs“
