Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: add extra attribute after new Option()

Tags:

I have a piece of code that dynamically adds options to a select field depending on some other criteria. It looks somewhat like this:

if (chosen == "a_value") {   selbox.options[selbox.options.length] = new Option('text_1','value_1');   selbox.options[selbox.options.length] = new Option('text_2','value_2');   selbox.options[selbox.options.length] = new Option('text_3','value_3'); } 

What I need is to add an extra attribute to that new option that contains a specific value. In this case the attribute will be called "discount" and the value will be an integer. Later on I'll read the attribute values and process them based on the value in the Option field.

So an option will look like this, once the script is ready;

<option value="value_1" discount="integer">text_1</option> 

Makes sense?

Now how can I do this without the use of JS frameworks. It's just this small part of code that I need, so a framework would be overkill for this project.

Cheers! :-)

like image 703
Léon Avatar asked Mar 31 '11 11:03

Léon


People also ask

Can option tag have data attribute?

An <option> element can have any number of data-* attributes, each with their own name.

What is the use of setAttribute in JavaScript?

setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.

How to edit attribute JavaScript?

Another way to change or create an attribute is to use a method like element. setAttribute("attribute", "value") or element. createAttribute("attribute", "value"). Use setAttribute to change an attribute that has been defined before.


1 Answers

you can do something like

  var o1 = new Option("key","value"); selbox.options[selbox.options.length] = o1; o1.setAttribute("key","value");  
like image 156
sushil bharwani Avatar answered Oct 09 '22 09:10

sushil bharwani