How to make an <option> selected when inserted with append?

2417 views jquery
2

I am adding a <option> with ajax and append it on success:

    success: function(data) {
      var newdata = data.replace(/['"]+/g, '');
      jQuery('#argomenti').append('<option value="">'+newdata+'</option>');
    }

But how would I make it so that it is the selected as I will have many other tags and values in that ?

Something like $('#argomenti').val(newdata).prop('selected', true);

answered question

2 Answers

5

You simply set the 'selected' attribute, like this:

jQuery('#argomenti').append('<option value="" selected="selected">'+newdata+'</option>');

posted this
6

I’d suggest:

// creating the element, passing an object of
// properties, and values, to set to that object:
$('<option>', {
  'selected': true,
  'text': newdata})
// appending the created element to its parent element:
.appendTo('#argomenti');

posted this

Have an answer?

JD

Please login first before posting an answer.