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));
如果将ID“ slc-pc”添加到select元素,则基本形式类似于以下形式:
$('#slc_pc').append($("<option></option>").attr({"value": key, "abc": brand, "123": model }).text(value));
try this one
you have add )
after (new Option("Hello", "Hello", true, true)
that and remove )
from last
$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true)).attr("abc", "brand", "123", "model");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name='slc_pc'> <option>select</option> </select>
$(function(){ var brand = 'test'; var model = '123'; var brand1 = 'abc'; var model1 = '456'; $(".slc_pc").append("<option value='hello' data-brand='" +brand+ "' data-model='" +model+ "'>hello</option><option value='hello1' data-brand='" +brand1+ "' data-model='" +model1+ "'>hello1</option>"); }) $(document).on("change",".slc_pc", function(){ var option = $("option:selected", this); alert("value : "+ $(this).val() + ", brand : "+$(option).data('brand') + ", model : " + $(option).data('model')); })
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <select class='slc_pc' name='slc_pc'> <option value=''>--select--</option> </select>
it can be done by something like this.
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'
})
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.