David
David

Reputation: 41

How to access form input value in javascript with special characters in input name?

I have a form for which I cannot change the input value field names. One such field is in the HTML as follows:

<body>
<form id="f" method="get" action="/code/submit.php">
<input type="text" name="var[list]" id="ixv[list]" value="">
<button type="button" title="Save" onclick="check();">
</form>
</body>

Now in my javascript, I want to access that input value. I tried this, and of course it doesn't work since [] looks like an array in JS.

function check() {
var x=var[list].value;
alert(x);
}

The problem is that the variable name has [] in it. How can I get that input field value in javascript?

Upvotes: 1

Views: 965

Answers (3)

BYTE RIDER
BYTE RIDER

Reputation: 169

Try it like this:

var x = document.getElementsByName("var[list]")[0].value;

Upvotes: 1

rab
rab

Reputation: 4144

In modern browser, use querySelectorAll

document.querySelectorAll('[name="var[list]"]')[0].value 

or if you know id try getElementById

document.getElementById('ixv[list]').value 

or getElementsByName

document.getElementsByName('var[list]')[0] .value 

Above three will returns same result

Upvotes: 0

coma
coma

Reputation: 16659

this works:

http://jsfiddle.net/mqv82/1/

<input type="text" name="var[list]" id="ixv[list]" value="foo">

alert(document.getElementById('ixv[list]').value);

Upvotes: 2

Related Questions