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

1

Good evening.

I'm 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 because of the brackets.

The result of the radio 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 in 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 does not have the brackets link . What should I change in the code to work correctly?

    
asked by anonymous 14.05.2016 / 04:26

1 answer

1

You were almost there. You can not mix the period to access the property and at the same time the brackets. That is objeto.[propriedade] is invalid syntax. The period is over.

You should use 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: link

    
14.05.2016 / 06:22