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> 
1
  • 1
    $('AccommodationType-2') is looking for DOM elements of type <AccomodationType-2>, you probably meant $('#AccommodationType-2') (ID selector) or $('.AccommodationType-2') (class selector). Commented Sep 19, 2012 at 12:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for mentioning jQuery version regarding prop which was only added in jQuery 1.6. Here is also the links to the docs: api.jquery.com/prop and api.jquery.com/attr
You should use ('checked', 'checked') and not ('checked', true)
@deifwud: That doesn't matter. The attr() method converts (checked, true) to checked="checked" in HTML.
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/

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.