skymario84 skymario84 - 3 months ago 12
jQuery Question

jQuery chosen returning invalid selected data

I have Chosen select box in my code

<select id="days" multiple>
<option value="1" selected>Mon</option>
<option value="2" selected>Tue</option>
<option value="3" selected>Wed</option>
<option value="4" selected>Thu</option>
<option value="5">Fri</option>
<option value="6">Sat</option>
<option value="7">Sun</option>
</select>


Now, I need to get all selected values with javascript and send them to php processor. I've tried with

var dani = $('#days').val();


and

var dani = $('#days').chosen().val();


But the strange thing is that only first time I get the correct values separated by comma, every other time it returns full array (1,2,3,4,5,6,7)

Is there a more precise way of doing that?

Also must say, select box is in bootstrap modal window.

Answer

Try this :

$(document).ready(function(){

    $("#days option:selected").each(function(){

        alert ($(this).val());
    })
})

<html>
    <title>This is test</title>
    
    <head>
    </head>
    <body>
        
        <select id="days" multiple>
         <option value="1" selected>Mon</option>
         <option value="2" selected>Tue</option>
         <option value="3" selected>Wed</option>
         <option value="4" selected>Thu</option>
         <option value="5">Fri</option>
         <option value="6">Sat</option>
         <option value="7">Sun</option>
    </select>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
        $(document).ready(function(){

            $("#days option:selected").each(function(){

                alert ($(this).val());
            })
        })
        </script>
    </body>
</html>

If want all Selected Values in one alert :

<html>
    <title>This is test</title>
    
    <head>
    </head>
    <body>
        
        <select id="days" multiple>
         <option value="1" selected>Mon</option>
         <option value="2" selected>Tue</option>
         <option value="3" selected>Wed</option>
         <option value="4" selected>Thu</option>
         <option value="5">Fri</option>
         <option value="6">Sat</option>
         <option value="7">Sun</option>
    </select>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
        $(document).ready(function(){
            
            var values = "You Selected Values : ";
            var num = "";

            $("#days option:selected").each(function(){
        
                num +=$(this).val() +" ";
                
                
            })
            
            alert(values + num);
        })
        </script>
    </body>
</html>

Comments