maniootek
maniootek

Reputation: 419

How to check/tick radio input in javascript

I have this HTML code:

<input type="radio" name="printTemplate" value="5" checked="checked">
<input type="radio" name="printTemplate" value="2">

how can I make value "2" checked (ticked) in javascript? I have no access to change html code, it is public website. Here is XPath to this radio with value "2"

//*[@id="frmSubmit"]/table/tbody/tr[4]/td/p[2]/table/tbody/tr/td[1]/input[3]

Upvotes: 0

Views: 661

Answers (3)

dsgriffin
dsgriffin

Reputation: 68566

"I have no access to change html code"

In that case, you could use JavaScript:

document.getElementsByName('printTemplate')[0].checked = true;

[0] selects the first element with that name, [1] the second and so on. If necessary (maybe you want to target multiple elements), you can loop through the the element list.


In reply to question edit:

"How can I make value "2" checked (ticked)?"

If there are one or more elements with with the name printTemplate that has value=2 and you want to target them, you could use:

var x = document.getElementsByName('printTemplate');
for(var i = 0; i < x.length; i++) {
    if(x[i].value == 2) x[i].checked = true;
}

jsFiddle.

Upvotes: 1

epascarello
epascarello

Reputation: 207501

From the docs for input at MDN

radio: A radio button. You must use the value attribute to define the value submitted by this item. Use the checked attribute to indicate whether this item is selected by default. Radio buttons that have the same value for the name attribute are in the same "radio button group"; only one radio button in a group can be selected at one time.

So what the doc says, you want to use the attribute checked.

<input type="radio" name="printTemplate" value="2" checked="checked" />

Now to do it with JavaScript code, you would set the checked attribute

//if you add an id
document.getElementById("foo").checked = true;

//if you only go by name
document.getElementById("frmSubmit").printTemplate[1].checked = true;

Upvotes: 0

compid
compid

Reputation: 1323

You would add the checked attribute.

<input type="radio" name="printTemplate" value="2" checked>

With jQuery, you can easily target the radio buttons by value too

$("input[name=printTemplate][value=2]").prop("checked", true);

Upvotes: 2

Related Questions