Sachin Kainth
Sachin Kainth

Reputation: 46740

How do I check a checkbox with JQuery

I have tried everything and nothing works. I have this checkbox

<input type="checkbox" onchange="WriteFormSelections('SearchForm', 'AccommodationType', 'AccommodationTypeSelections', 'All', 'AccommodationType-0', false, '_', true);" value="Hotel" name="AccommodationType_Hotel" id="AccommodationType-2">Hotel

And I want to check it when the page loads. I have tried lots of things. One of the things I can't work out is, am I supposed to use the id or the name of the checkbox to check it?

Here's my current code. I have tried to use prop as suggested by this post but that doesn't work either.

<script type="text/javascript">
   $('AccommodationType-2').attr('checked', true);
</script>

Upvotes: 0

Views: 808

Answers (3)

csharpnumpty
csharpnumpty

Reputation: 3723

You are missing a # in front of your selector.

$('AccommodationType-2').attr('checked', true);

becomes

$('#AccommodationType-2').attr('checked', true);

...depending on the version of jQuery you're using I'd recommend looking at .prop() too, which is to be used for property access on objects.

Additionally, as the other answerers have rightly pointed out - you do need to wait for the DOM to be ready by wrapping a document.ready() around your checkbox-checking line.

Upvotes: 9

GajendraSinghParihar
GajendraSinghParihar

Reputation: 9131

You have To use jQuery Id Selector (also always try to encapsulate jquery code in the document ready wrapper)

Correct Code :

$(function(){

$('#AccommodationType-2').attr('checked', true);

});

using $("AccommodationType-2") tells jQuery to search for the tag as <AccommodationType-2>

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

You were missing the # in your selector. Also, you it's a good idea to wrap the code inside a document ready call to ensure the dom is loaded before it is run:

$(document).ready(function() {
    $('#AccommodationType-2').prop('checked', true);
});

Example - http://jsfiddle.net/infernalbadger/vMTvs/

Upvotes: 1

Related Questions