简体   繁体   中英

Why can't I use - in field names?

Basically I'm just trying to clear a text field, which has never been a problem for me. However, this is NOT working:

<html>
<body>

<form name="form">

<input type="text" name="input-field" value="Value" />

<input type="button" name="clear" value="Clear field" onclick="document.form.input-field.value = ''"; />

</form>

</body>
</html>

But if I rename "input-field" to "inputfield" and onclick to onclick="document.form.inputfield.value = ''"; ... Then it works fine.

However... Removing the "-" from the field name, is not an option in my case (long explanation).

So, how do I clear a text field, containing a "-"???

Because it's not a valid JavaScript identifier. However, you can use the following instead:

document.form['input-field'].value

It's for the same reason you can't declare a variable using var my-var . On the other hand, if you have an object , such as form with several keys, you can access its properties as if it was an associative array:

var form = {
  "input-field": 20,
  otherKey: 30
};
form.input-field; // Error
form.otherKey; // OK
form['input-field']; // OK

References:

- is not a valid character in an identifier because, for example

document.form.input-field;

is interpreted as

document.form.input - field;

Of course you can remedy the problem by using the square bracket notation:

document.form["input-field"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM