1

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);

rob.m
  • 9,843
  • 19
  • 73
  • 162
  • Possible duplicate of [Set the default value in dropdownlist using jQuery](https://stackoverflow.com/questions/4781420/set-the-default-value-in-dropdownlist-using-jquery) – Sunil Kanzar Nov 07 '18 at 01:00

2 Answers2

1

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

jQuery('#argomenti').append('<option value="" selected="selected">'+newdata+'</option>');
Poul Bak
  • 10,450
  • 5
  • 32
  • 57
1

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');
David Thomas
  • 249,100
  • 51
  • 377
  • 410