0

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>
Community
  • 1
  • 1
Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • 1
    `$('AccommodationType-2')` is looking for DOM elements of type ``, you probably meant `$('#AccommodationType-2')` (ID selector) or `$('.AccommodationType-2')` (class selector). – jbabey Sep 19 '12 at 12:47

3 Answers3

9

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.

SpaceBison
  • 3,704
  • 1
  • 30
  • 44
  • 2
    +1 for mentioning jQuery version regarding `prop` which was only added in jQuery 1.6. Here is also the links to the docs: http://api.jquery.com/prop/ and http://api.jquery.com/attr/ – Nope Sep 19 '12 at 12:52
  • You should use `('checked', 'checked')` and not `('checked', true)` – billyonecan Sep 19 '12 at 12:53
  • @deifwud: That doesn't matter. The `attr()` method converts `(checked, true)` to `checked="checked"` in HTML. – Nope Sep 19 '12 at 12:58
1

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/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
1

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>

devnull69
  • 16,402
  • 8
  • 50
  • 61
GajendraSinghParihar
  • 9,051
  • 11
  • 36
  • 64