1

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
  • You want what now? Perhaps an example of what you're trying to do would be in order? Commented Jan 4, 2010 at 19:19

4 Answers 4

1

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...

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

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);
}

6 Comments

But I want to set as an object, not a string.
What do you mean? Tell us what you want to do, ultimately, and we'll tell you how.
There, M28. Now it's an object.
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.
Não era assim que eu queria, eu quero armazenar o objeto no value, mas agora o outro cara deu uma ideia
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.