简体   繁体   中英

JQuery Mobile Change Attribute Each Option on Multiple Select Using JavaScript

I'm new with this JQuery Mobile thing. And the first problem i met in this is i can't set "selected" attr on multiple select option to "false" / unselected in JQuery mobile using Javascript.

A documentation i found told me to refreshing a select so i can manipulate it via javascript here in the bottom of it's page: http://jquerymobile.com/demos/1.0a4.1/docs/forms/forms-selects.html

I've done it. But i don't know if i did it wrong or what. Here is my code :

<script type="text/javascript">
function SelectAll(){
    var select=document.getElementById('sfruit');
    if (select.options[1].selected == true){
        alert('All Selected');

        for (x in select.options){
            if(x > 1){
                if (select.options[x].selected == true){
                    alert(select.options[x].value+' selected');

                    RefreshSelect();
                    select.options[x].selected == false;
                }else{
                    alert(select.options[x].value+' unselected');
                }
            }
        }
    }
}

function RefreshSelect(){   
    var myselect = $("select#sfruit");
    myselect[0].selectedIndex = 5;
    myselect.selectmenu("refresh");
}
</script>

<select onChange="SelectAll()" data-native-menu="false" id="sfruit" name="sfruit" multiple>
    <option>Select Fruit</option>
    <option value="all" selected>All</option>
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="grape">Grape</option>
    <option value="melon">Melon</option>
</select>

What i actually want is when i select "All" option, other option that have been selected become unselected. I'll attaching the image if u all still doesn't understand what i mean, later, it's already late here.

Thanks guys. And please help me. .. :)

I think this is what you want

$(window).load(function(){
    $("select#sfruit").change(function () {
        $("select#sfruit option:selected").each(function (obj) {  
            if($(this).index()==1){
               alert('All Selected');
               $("select#sfruit option:selected").removeAttr("selected");
               $("select#sfruit option:eq(1)").attr("selected","");
            }
        });
    });
});

<select data-native-menu="false"  id="sfruit" name="sfruit" multiple>
    <option>Select Fruit</option>
    <option value="all" selected>All</option>
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="grape">Grape</option>
    <option value="melon">Melon</option>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM