Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jackie Jen
Jackie Jen
2,723 Points

how to pass or set the attribute of checked in radio button using javascript

i'm having and html radio button tag. i wish to use javascript to set the attribute of radio button. how to do that?

 <input type="radio" name="rating" id="rating" value="1" />

javascript

document.getElementById('rating').setAttribute("checked", "checked")

But it couldn't work.

1 Answer

You're just missing the semicolon at the end of your JavaScript. Also, for accessibility, you might want to wrap a label tag around your input element like so:

<label for="rating"><input type="radio" name="rating" id="rating" value="1">some rating text</label>
Jackie Jen
Jackie Jen
2,723 Points

Hi imouto,

i just want use javascript to set attribute checked to the radio button. I don't want to put checked in the radio button tag for the 1st time.

Hi Jackie,

That was my mistake. I had copied and pasted my HTML AFTER the JavaScript code had been executed. Your original HTML code should work with your JavaScript code if you just add the semicolon at the end. I've corrected the HTML in my answer.

Jackie Jen
Jackie Jen
2,723 Points

Thanks Imouto,