简体   繁体   中英

How to fix another drop-down value after selecting first in javascript or jquery?

I have one one form with 2 drop-downs. What i want is, when I select 1st drop down box, then a specific option gets fixed (which can't be change by user in that form) to another drop-down box. How can i do this in javascript or jquery?

<select id="item_type" name="item_type" style="width:300px;" ">
                              <option value=''>-- Select --</option>
                              <option value="City">City</option>
                              <option value="Source">Source</option>
                              <option value="Follow Up">Follow Up</option>
                              <option value="Next Day">Next Day</option>                            
</select> 

<select id="item_value_type" name="item_value_type" style="width:300px;" ">
                              <option value=''>-- Select --</option>
                              <option value="value">value</option>
                              <option value="id">id</option>                            
</select>  

The jQuery way would be

var valueType = $('#item_value_type')
$('#item_type').on('change', function(e) {
  valueType.val('thefixedvalue'); // sets the value
  valueType.attr('disabled', true); //disables the select
});

To reenable the select, just use

valueType.removeAttr('disabled');

The javascript way is

var valueType = document.getElementById('item_value_type');
var itemType = document.getElementById('item_type');
itemType.onchange = function(event) {
  valueType.value = 'yourFixedValue';
  valueType.setAttribute('disabled', 'disabled');
}

reenable the select with:

valueType.removeAttribute('disabled');

You can do this:

<select id="item_type" name="item_type" style="width:300px" onchange=javascript:change(this.value)>
         <option value=''>-- Select --</option>
         <option value="City">City</option>                         
</select>

and in change function you can modify other select field.drop-down box.

Jquery:

$("#target_sel").attr("disabled",true);
$("#first_sel").on("change",function(){
   $("#target_sel").val($(this).val())
})

Working demo http://jsfiddle.net/LXRqm/

API: change : http://api.jquery.com/change/ prop : http://api.jquery.com/prop/

you can also do prop('disabled', false) to set it in active state.

Hope this helps, and feel free to play around with demo,

code

var secondSelect = $('#item_value_type');
var hulkChange = "value";

$('#item_type').change(function() {
     secondSelect.val(hulkChange); 
     secondSelect.prop('disabled', true);
});​

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