Select something that contains brackets in the name in a Javascript function

Asked

Viewed 69 times

1

Good night.

I am trying to use this javascript code to display the "value" of a "radio" in a form:

document.userForm.onclick = function(){
    var radVal = document.userForm.[rads].value;
    result.innerHTML = 'You selected: '+radVal;
}

But in name="..." I have brackets, in this example: name="[rads]", and the javascript code is not working due to the brackets.

The radio output selected in the form will be displayed in this code:

<form id="mainForm" name="mainForm">
    <input type="radio" name="[rads]" value="1" />
    <input type="radio" name="[rads]" value="2" />
    <input type="radio" name="[rads]" value="3" />
    <input type="radio" name="[rads]" value="4" />
</form>
<span id="result"></span>

I’ve tried changing javascript to these ways:

var radVal = document.userForm.\\[rads\\].value;
var radVal = document.userForm.['[rads]'].value;

But none of them worked. Here we can see that the code works as long as it doesn’t have the brackets https://jsfiddle.net/Josh_Shields/23kg3tf4/1/. What should I change in the code to work properly?

1 answer

1


You were almost there. You can’t mix the dot to access the property and at the same time the brackets. That is to say objeto.[propriedade] is invalid syntax. O dot is the most.

You should wear it like this:

document.mainForm.onclick = function(){
    var radVal = document.mainForm['[rads]'].value;
    result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
    <input type="radio" name="[rads]" value="1" />
    <input type="radio" name="[rads]" value="2" />
    <input type="radio" name="[rads]" value="3" />
    <input type="radio" name="[rads]" value="4" />
</form>
<span id="result"></span>

jsFiddle: https://jsfiddle.net/97kz9ak0/

  • 1

    Thank you Sergio, it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.