Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<option> value not being set

I have data returned by an ajax call, I am creating an option(dropdown select) element for each returned row of data, I need to make one of them default selected based on text. But value does not get assigned to the one I made "selected". Below is my code:

$.each(JSON.parse(r.d), function (key, value) {
  if (value == 'Username') {
    $('#ddlcriteria1')
      .append($('<option selected="selected">', { value: key })
        .text(value));
  }
  else {
    $('#ddlcriteria1')
      .append($('<option>', { value: key })
        .text(value));
  }
});

I am adding an option element for each returned row, and making the default selected one as "Username". When I look at the DOM after this has been added. I see this:

  <option value="1">First Name</option>
  <option value="2">Last Name</option>
  <option selected="selected">Username</option>
  <option value="4">Email</option>
  <option value="8">Department</option>
  <option value="9">Status</option>
  <option value="10">Position</option>
  <option value="11">Role</option>
  <option value="12">User Group</option>
  <option value="13">Course Code</option>
  <option value="15">Enrollment Location</option>
  <option value="16">Organization</option>

The option element with "Username" text does not have a value assigned, any idea why this is happening?

like image 367
Phani Avatar asked Jun 15 '26 08:06

Phani


2 Answers

Set the selected attribute in the object as well, like this:

$('<option>', { value: key, selected: true })
like image 74
Matt Cain Avatar answered Jun 17 '26 20:06

Matt Cain


Make it good:

var optionElement = $('<option/>').attr({
                                     "selected":"selected", 
                                     "value": key
                                   });
$('#ddlcriteria1')
  .append(optionElement)
    .text(value));

With your code you are overriding the last properties

like image 26
Marcos Pérez Gude Avatar answered Jun 17 '26 21:06

Marcos Pérez Gude