0
votes

I'm facing an issue in selecting the dropdown first value after selecting it for the first time. When the dropdown options slidedown to select, the first value would be selected by default,bcoz of which I'm not able to select the first value. I'm using JQuery mobile framework and I'm writing custom JS to change the dropdown. I need to handle this dropdown only using custom JS and cannot make the dropdown work with this custom logic due to some other issue with my project.

Here first value im referring as 'US' from dropdown

The solution for this issue would be really appreciated. Thanks in advance.

HTML:

<select id="drpDwn">
    <option value="" disabled="disabled">select</option>
    <option value="US">US</option>
    <option value="AU">AU</option>
    <option value="NZ">NZ</option>
</select>

JS:

$(document).on('change', '#drpDwn', function () {
var index = $(this)[0].selectedIndex;
$(this).attr('selectedIndex', index);
$(this).find('option').removeAttr('selected');
$(this).find('option').eq(index).attr('selected', 'selected');
$(this).siblings('span').html($(this).find('option').eq(index).text());
});

http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css

1
I don't understand the question, you want to retain which option was selected previously? Or, once an option is selected, you want it do be disabled? - Jeramiah Harland
@JeramiahHarland.... FIrst ill be able to select US from the dropdown, but when i change to other value like NZ or AU, If i want to select back the first value like US, It does not get selected - Manju

1 Answers

0
votes

Check out this JSFiddle

The difference maker was modifying:

$(this).find('option').removeAttr('selected');

Into:

$(this).find('option:not(:selected)').removeAttr('selected');

When 'change' was triggered, the selected attribute is added to the new option, so you were stripping it away from everything even the new selection. That's why the option never changed.

Using :not(:selected) came in handy then since it will only strip away the attribute from things that weren't the current selected option.