Can you please take a look at following code and let me know why i am not able to get the ID of selected radios by using the this.id
?
<div id="pay" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="mode" id="option1"> Cash
</label>
<label class="btn btn-primary">
<input type="radio" name="mode" id="option2"> Cheque
</label>
</div>
<script>
$("#pay input:radio").on('click',function(){
alert(this.id);
});
</script>
Thanks
If that posted code is, in fact, the entirety of your jQuery you've simply forgotten to use the document ready handler:
$(document).ready(function(){
// your code should be in here
});
Or you could ensure that your <script>
is placed before the closing </body>
tag, both of which approaches ensure the content of the page is loaded and present in the page before you try binding event-handlers.
Make sure your jQuery code is executed once the DOM is ready:
$(document).ready(function () {
// All your function calls, self-invoked functions, etc
// Also you define your event handlers here
});
From the docs about the .ready( handler )
:
Specify a function to execute when the DOM is fully loaded
Then you need to transform this
into a jQuery object to access its methods, eg .attr()
like so: $(this)
Since jQuery version 1.7 you may use event delegation by using the .on()
function.
Again the docs :
Attach an event handler function for one or more events to the selected elements.
<script>
$(document).ready(function () {
$(document).on('click', '#pay input:radio', function() {
// Instead of using alert(), use the console for debugging
window.console.log($(this).attr('id'));
});
});
</script>
Try to use
$(this).attr("id")
instead of this.id
this will work;
$(function(){
$(document).on('click', '#pay input:radio', function(){
alert($(this).prop('id'))
});
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.