2016-04-04 55 views
0

我有2個下拉菜單。下拉在jQuery中的onchange函數

JS

$("#location").on("change", function() { 

}); 

$("#unitTypes").on("change", function() { 

}); 

HTML

Location: 
<select id="location"> 
    <option>USA</option> 
    <option>INDIA</option> 
</select> 

Unit Types: 
<select id="unitTypes"> 
    <option>Value 1</option> 
    <option>Value 2</option> 
    <option>Value 3</option> 
    <option>Value 4</option> 
</select> 

這裏印度已經具有 「值1」 和 「值2」。而「美國」是「價值3」和「價值4」。

我要改變位置的值爲「印度」,如果我選擇單位類型爲「值1」和「值3」,這裏值3不是「印度」,所以我想顯示一個警告消息 「價值是錯誤的」 我怎樣才能做到這一點使用JSON格式

+2

http://jsfiddle.net/arunpjohny/2pza5/ –

+0

非常感謝你 –

+0

我會advi您只需製作兩個帶有INDIA和USA相應值的「unitTypes」列表,在第一個下拉列表中只顯示適用於當前選擇的值列表 –

回答

0
Try this code - 
<script> 
$(document).ready(function(){ 

    $('#location').on("change",function() 
    { 
abc(); 
    }) 
    $('#unitTypes').on("change",function() 
    { 
abc(); 
    }) 
    }); 

    function abc() 
    { 
    var loc = $('#location').val(); var uT = $('#unitTypes').val(); 
    if((loc == "USA" & (uT == "Value 3" | uT == "Value 4")) | (loc =="INDIA" & (uT == "Value 2" | uT == "Value 1"))) 
    { 
    alert ("Wrong selection"); 
    } 
    else 
    { 
    alert ("Right selection"); 
    } 
    } 
</script> 
0

關於什麼的每個國家創建單獨的選擇 像:。

HTML

Unit Types: 
<select id="unitTypesForUSA"> 
    <option>Value 1</option> 
    <option>Value 2</option> 

</select> 
<select id="unitTypesForIndia"> 
<option>Value 3</option> 
    <option>Value 4</option> 
</select> 

JS

$("#location").on("change", function() { 
    if($(this).text()==='USA'){ 
     $('#unitTypesForUSA').show(); 
     $('#unitTypesForIndia').hide(); 
    }else{ 
     $('#unitTypesForUSA').hide(); 
     $('#unitTypesForIndia').show(); 
    } 
}); 

這種方式,你可以跳過JavaScript驗證和警報消息alltoegether。

0

試試這個,它正在:

HTML:

<label>Location:</label> 
<select id="location"> 
    <option>--Select--</option> 
    <option value="USA">USA</option> 
    <option value="INDIA">INDIA</option> 
</select> 

<label>Unit Types:</label> 
<select id="unitTypes"> 
</select> 

JS:

jQuery(function($) { 
var locations = ['value1','value2','value3','value4']; 
    var unitTypes = $('#unitTypes'); 
$("#location").on("change", function() { 
var location = $(this).val(); 
    if (location == 'USA') { 
    var html = '<option value="' + locations[2] + '">' + locations[2] + '</option>' + 
      '<option value="' + locations[3] + '">' + locations[3] + '</option>'; 
     } else { 
     var html = '<option value="' + locations[0] + '">' + locations[0] + '</option>' + 
      '<option value="' + locations[1] + '">' + locations[1] + '</option>'; 
     } 
     unitTypes.html(html); 
}); 
});