1

I have slightly modified the code here https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_getelementsbyname_loop

From:

<!DOCTYPE html>
<html>
<body>

Cats:  <input name="animal" type="checkbox" value="Cats">
Dogs:  <input name="animal" type="checkbox" value="Dogs">

<p>Click the button to check all checkboxes that have a name attribute with the value "animal".</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementsByName("animal");
    var i;
    for (i = 0; i < x.length; i++) {
        if (x[i].type == "checkbox") {
            x[i].checked = true;
        }
    }
}
</script>

</body>
</html>

To: i.e. I want to change the value of value's attribute.

  for (i = 0; i < x.length; i++) {
    if (x[i].type == "checkbox") {
        x[i].setAttribute("value", "camels");
    }
}

It didn't change nothing, but What wrong am I doing?

Edit: Requirement is to change the property in DOM not HTML.

enter image description here

2
  • You can shorten it to x[i].value = "camels";. BTW, setAttribute should work too, did you change anything else by any chance? Commented Nov 28, 2018 at 21:36
  • you are right, it worked for me, but setAttribute didnt. Commented Nov 29, 2018 at 8:08

2 Answers 2

4

Looks to be doing what is expected. The value attribute changes to camels for every single checkbox.

If what you're trying to do is change the TEXT beside the checkbox, you'll need to wrap it in its own element (likely a p) and change the text to be camel. Changing the value will only change the actual data value which that checkbox corresponds to.

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

1 Comment

When I do webElement.getAtrribute("value"); it will be some value. Same value I want to change using Javascriptexecutor, but what it is doing is change value in HTML. I have added picture for better understanding.
2

I think it is doing what you want, you just can't see it. You are changing the value of the input, not the actual text "Dogs:", so what you end up with is:

Cats:  <input name="animal" type="checkbox" value="camels">
Dogs:  <input name="animal" type="checkbox" value="camels">

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.