views:

93

answers:

4

I have the following code:

<select>
<option value="blablabla">Test</option>
<!-- ... -->
</select>

But I want to know if I can set the "value" attribute of the option tag, as a reference to an object (in javascript).

+1  A: 

Your question is a bit unclear. You can set the value of an item according to the value of the selected option:

<select id="mySelect">
  <option value="goose">Goose</option>
  <option value="gander">Gander</option>
</select>

var myObj = {a:"",b:true};
document.getElementById("mySelect").onchange = function() {
  myObj.a = this.value;
  alert(myObj.a);
}
Jonathan Sampson
But I want to set as an object, not a string.
M28
What do you mean? Tell us what you want to do, ultimately, and we'll tell you how.
Jonathan Sampson
An object can be defined as: {aaa:"lololo",cats:false}
M28
There, M28. Now it's an object.
Jonathan Sampson
Did it work? 10chars
M28
Yes, it works. I just gave it a local test.
Jonathan Sampson
M28, Voce poder falar em portuguese tambem. Touvez e mais dificil pra explicar sua idea em ingles. Eu acho que meu exemplo esta certo, e vai funcionar correto.
Jonathan Sampson
Não era assim que eu queria, eu quero armazenar o objeto no value, mas agora o outro cara deu uma ideia
M28
Eu nao entendo, voce que fazer isso? `<option value'myObj.a' />`? Voce nao poder colocar um objecto no value. Voce poder colocar uma attribute de o objecto, mais nao o objecto.
Jonathan Sampson
+1  A: 

The "value" attribute could be a number that you can use later in javascript to reference a object in an array.

rodrigoap
+1  A: 

As is so often the case, the answer is MAYBE.

The only way I can think of to do this off the top of my head, would be to have an array of objects, and have the indexes of the array to be the values found in the drop down list.

Of course, depending on the context of what you're trying to do, that may or may not be useful. For example, say you want a DIV to appear/disappear based on the selection. In that case, you wouldn't need the array, as you could just put the control's name into the VALUE field and perform a look up on it.

Stephen Wrighton
+1  A: 

The option value must be a "string" (that string can be a number).

What you want to do is a bit unusual but can be done (but I think there are better ways to achieve what you want to do)... You could serialize your object and set it in the value but that would be odd.

You could also index these references in an array and then set it's index in the value of the option...

AlexV