0

I have a html select like:

<select id="airports-sel">
      <option data-group="1" value="1">Madrid–Barajas</option>
      <option data-group="1" value="2">Torrejón de Ardoz Airport</option>
      <option data-group="2" value="3">Milan-Malpensa</option>
      <option data-group="2" value="4">Milan-Linate</option>
</select>

I need to add a new airport to this select using jQuery, I try to use the following code but it's not working:

$('#airports-sel').append($('<option>', {
      value: 5,
      text: Paris-Orly Airport,
      data-group: 3
}));

This works without "data-group" but it's very important to me to have the data-group set on every option, can you please provide an example of how can I do this?

0

3 Answers 3

2

Your code has a couple of problems:

  1. You don't use strings correctly; strings must be enclosed in quotes.
  2. You use a hyphen-separated key in your object which must also be enclosed in quotes, or you'll get a syntax error.

Code:

$('#airports-sel').append($('<option>', {
      value: 5,
      text: "Paris-Orly Airport",
      "data-group": 3
}));
Sign up to request clarification or add additional context in comments.

2 Comments

Why down voted this answer? This is correct one and it's not a duplicate as mentioned in comment.
@Alex, if it solves your problem then you should accept the answer.
0

Hope it helps!

     $("#airports-sel").append("<option data-group=3 value='>Paris-Orly Airport</option>");

Comments

0

You can add option by simply writing following code in jquery.

$("#airports-sel").append("<option data-group='3' value='5'>Paris-Orly Airport</option>");

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.