0

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]
0

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I have no access to html code (public website). Here is also XPath for this radio : //*[@id="frmSubmit"]/table/tbody/tr[4]/td/p[2]/table/tbody/tr/td[1]/input[3]
How will your javascript be executed then? Is the content in an iframe?
1

"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.

2 Comments

document.getElementsByName("printTemplate")[2].checked = true; << working !! thank you !!
@maniootek Remember to tick my answer if it helped you :) thank you
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.