0

I have a select list that's generated by the Javascript code of my app

<select name="addToContexts" id="addToContexts">
 <option selected>private</option>    
 <option>public</option>
 <option>shared</option> 
</select>

What I need to do is that when the user performs a certain action the selected parameter shifts to another option, so that the result would be something like:

<select name="addToContexts" id="addToContexts">
 <option>private</option>    
 <option selected>public</option>
 <option>shared</option> 
</select>

Do you know if there's a way to do it without regenerating the whole options list simply using jQuery to get the select element by ID and to change the selected option?

Thank you!

Aerodynamika
  • 7,883
  • 16
  • 78
  • 137
  • What's the "certain action" that the user performs? – j08691 Dec 10 '14 at 15:33
  • They double click on an element on my page, which then puts that element into the textarea field of a form so it can be edited. The select field is part of that form and shows what context that element belongs to. – Aerodynamika Dec 10 '14 at 15:36
  • Have you tried `$('#addToContexts option:eq(1)').prop('selected',true)`? – j08691 Dec 10 '14 at 15:38
  • Is this what you want? http://stackoverflow.com/questions/9490906/how-to-change-a-select-value-from-javascript – ksb Dec 10 '14 at 15:39
  • this is very simple view this thread http://stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery – saqibahmad Dec 10 '14 at 16:38

4 Answers4

0

http://jsfiddle.net/washington_guedes/ovpkLexj/5/


I used an ul-li "click" event as "certain action"... and it worked well

$("li").on("click", function(){
    var aux = $(this/*li*/).html();
    $('#addToContexts > option')
        .prop("selected", false)
        .each(function(){
            if( $(this/*option*/).html() === aux){
                $(this/*option*/).prop("selected", true);
            }
    });
});
0
<body>
    <select name="addToContexts" id="addToContexts">
         <option selected>private</option>    
         <option>public</option>
         <option>shared</option> 
    </select>
    <button id="changeSelect">Change</button>
    <script>
        $("#changeSelect").click(function(){
            $("#addToContexts option:nth-child(2)").prop("selected", true);
        });     
    </script>
</body>

Something like this?

Rinrub
  • 137
  • 10
0

Hope this help.

http://jsfiddle.net/6Ljn1rzr/

$('input[type=checkbox]').on(
            'change',
            function() {
                $('option').attr("selected",false);
                $('option:contains(public)').attr("selected",true);
            }  
          );
aahhaa
  • 2,240
  • 3
  • 19
  • 30
0

its very simple you can visit this thread http://www.stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery

it has explained the in a very good manner and hopefully you will get your answer from this thread

saqibahmad
  • 962
  • 1
  • 9
  • 18