1

I have the following:

HTML

<select class="dropDownList" id="PersonFunction">
    <option value="">Choose</option>
    <option value="1">Vice President</option>
    <option value="2">Director</option>
    <option value="3">Secretary</option>
    <option value="4">Clerk</option>
</select>​

JS

$("#PersonFunction").change(function () {    
    $("option", this).eq($(this).val()).attr('selected', 'selected');
});​

So after the index change i set the selected attribute and it works but after the user changes the index again i set yet another selected attribute on different value and i don't want that.

<select class="dropDownList" id="PersonFunction">
    <option value="">Choose</option>
    <option value="1" selected="selected">Vice President</option>
    <option value="2" selected="selected">Director</option>
    <option value="3">Secretary</option>
    <option value="4">Clerk</option>
</select>

How can i first remove selected attribute if one exists then add one?

JsFiddle here: http://jsfiddle.net/mgrcic/HCrS2/

4

3 に答える 3

11
$('#PersonFunction').on('change', function() {
  $('option:selected', this).attr('selected',true).siblings().removeAttr('selected');
});

DEMO

于 2012-04-18T08:42:33.243 に答える
4

There is no need to update the selected attribute programmatically as the browser will automatically know which element is selected. The selected attribute is only intended to set a default option on page load.

To get the current selected option, just use the following:

var selectedValue = $("#PersonFunction option:selected").val(); 

Example Fiddle


Update

If for whatever reason you do want to set a selected attribute (as form what I can understand you are creating another form dynamically), try this:

$("#PersonFunction").change(function () {   
    $("option", $(this)).removeAttr("selected");
    $("option:selected", $(this)).attr("selected", true);
});​
于 2012-04-18T08:26:34.770 に答える
-1

This will alert you the text thats selected. change .text() to .val() if you want it to pick up the option values instead

$("#PersonFunction").change(function () {
    var selected = $("option:selected").text();
    alert(selected);
});
于 2012-04-18T08:30:29.870 に答える