2

I have n select array like this:

<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>

<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
.
.
.
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>

user can choose all select as 'BOTTOM'

But I want user only can choose one 'TOP'

for example, If choose 'TOP',all of other select be 'BOTTOM'

I try write it via jQuery:

$("[name=upporder]").on('change',(function(e) {
    e.preventDefault();

   if(this.val() == 2) 
       // do not do anything
   elseif(this.val() == 1) 
        //change all other 'select' value (with same name) to '2' except current 'select'

}
2
  • Looks like you are just trying to reinvent radio buttons purpose... And to answer your question: $(".form-control").not(this).val(2) Commented May 14, 2016 at 13:40
  • agreed, just use radio buttons... Commented May 14, 2016 at 13:41

2 Answers 2

1

Try this:

$(".form-control").change(function(){ // handle click event of all selectbox
    if($(this).val() == '1') { // check if TOP is selected
       $(".form-control").val('2'); // first set all select box value to 2
        $(this).val('1'); // set current selectbox to 1
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

with a little change: $(".form-control).val('2').prop('selected', true); thanks
0

you need to loop through lists by using .each()

$("select.form-control").on('change',function(e) {
    e.preventDefault();

   if($(this).val() == '2'){
       // do not do anything
   }else if($(this).val() == '1'){
   //change all other 'select' value (with same name) to '2' except current 'select'
   $("select.form-control").not($(this)).each(function(){
     $(this).find('option[value="2"]').prop('selected', true);
   });

    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>

<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.