tanya
tanya

Reputation: 2985

javascript - name or id of element

Is this.form.sel2 similar to document.getElementById('sel2')?

My select tag is as follows:

<select size=5 id="sub_player_ids" name="sub[player_ids][]">

And when I am putting the name of the tag, i.e, sub[player_ids][] in my javascript code, am getting a syntax error. I am trying to find a workaround so that instead of using the name of the element, i want to use the id.

However using document.getElementById('sub_player_ids') is not working.

Thanks for any suggestion provided.

Please see my javascript code below:

      <input type="button" value="--&gt;"
       onclick="moveOptions(this.form.sel1, this.form.sel2);" /><br />
      <input type="button" value="&lt;--"
       onclick="moveOptions(this.form.sel2, this.form.sel1);" />

Upvotes: 0

Views: 1212

Answers (5)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

The id of your element is sub_player_ids, not sel2. So document.getElementById("sub_player_ids") would work.

You may also find that this.form["sub[player_ids][]"] would work. Using the quoted form lets you use things that you can't use in the literal form.

Something to beware of is that IE7 and earlier have a broken version of getElementById that will find things that use the given string as a name, rather than as an id, even if something later on the page actually uses it as an id. (Yes, really; more here.) Some libraries will work around that for you (jQuery does, for instance). And actually, speaking of libraries, a good library really can help work around all sorts of browser inconsistencies and provide a lot of handy utility functionality, letting you concentrate on your actual business problems. You might consider looking at jQuery, Prototype, YUI, Closure, or any of several others.

Upvotes: 3

Matt Ball
Matt Ball

Reputation: 359826

You can use bracket notation instead:

this.form['sub[player_ids][]']

...or getElementById(), with the right ID:

document.getElementById('sub_player_ids')

Upvotes: 2

niksvp
niksvp

Reputation: 5563

verify that your options contains id, it would only be containing name with sel2

Upvotes: 1

benjamunky
benjamunky

Reputation: 260

You have the wrong id

document.getElementById('sub_player_ids')

Upvotes: 1

Ry-
Ry-

Reputation: 224921

Use document.getElementById('sub_player_ids') to get that element.

Upvotes: 1

Related Questions