Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append option in select and add data attribute to option

I have select name slc_pc and i want to append option by jquery code.

I try these script. But it's not working.

$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true).attr("abc",brand,"123",model));
like image 537
The Rock Avatar asked Oct 21 '25 08:10

The Rock


2 Answers

There are some mistakes in your code. First of all, to set multiple attributes, you need to pass them as an object. Second, the property name and value for the data attributes are incorrect. brand & model should be property and abc & 123 should be their values respectively.

new Option will create an option element which does not have attr method on it. You may use jQuery to create a new element.

Here's the correct way

$('select[name="slc_pc"]')
  .append($('<option />')  // Create new <option> element
    .val('Hello')            // Set value as "Hello"
    .text('Hello')           // Set textContent as "Hello"
    .prop('selected', true)  // Mark it selected
    .data({                  // Set multiple data-* attributes
      brand: 'abc',
      model: '123'
    })
  );
like image 168
Tushar Avatar answered Oct 22 '25 22:10

Tushar


If you add an ID "slc-pc" to your select element, it's like this in it's basic form:

$('#slc_pc').append($("<option></option>").attr({"value": key, "abc": brand, "123": model }).text(value)); 
like image 40
Emil Kidi Avatar answered Oct 22 '25 20:10

Emil Kidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!