开发者

get and set selected value

REFRASE QUESTION :

I have 6 selects. When I select value from select1 I invoke some function from server side and I get JSON array from that function.

I get 5 values at most from this array, sometimes I'll get 20,30,40,50,60 but sometimes 20,30 or just 20.

These values correspond to select2, select3, select4, select5, select6 option value index. So in case the array returns 20,30,40,50,60 -> select2 option index value should be set to 20, select3 to 30 etc. And if array returns just 20 then select2 index value sho开发者_Python百科uld be set to 20 and all others index values to 0.

What is the best way to do this?

Thank you


var s1 = document.getElementById("select1");
var s2 = document.getElementById("select2");
s2.selectedIndex = s1.selectedIndex;

Or, if you want it to happen when the first <select> is changed:

s1.onchange = function() {
    s2.selectedIndex = s1.selectedIndex;
};


//get
var sel1Index = document.getElementById("select1").selectedIndex;
//just in case you want the selected text too
var sel1Text = document.getElementById("select1").options[selectedIndex].text; 

//set
document.getElementById("select2").selectedIndex = sel1Index;


To get a value, or the index of the selected value, these work:

document.getElementById("select1").value;
document.getElementByID("select2").selectedIndex;

To set a value, use the same, but assign:

document.getElementById("select1").value = "whatever";
document.getElementById("select2").selectedIndex = 3;

Because your list values are disimilar, I assume you want to use the index; ie, selecting "one" in select1 would cause select2 to change to "seven", etc.

You could do that using:

document.getElementById("select2").selectedIndex
  = document.getElementById("select1").selectedIndex;

If you want one list to change when the other changes, effectively keeping them in sync, you can bind functions to the select's "onchange":

<script type="text/javascript>
function select1_onchange() {
  document.getElementById("select2").selectedIndex
    = document.getElementById(select1").selectedIndex;
}

function select2_onchange() {
  document.getElementById("select1").selectedIndex
    = document.getElementById(select2").selectedIndex;
}

</script>

<select name="select1" id="select1" onchange="select1_onchange">
...


<select name="select2" id="select2" onchange="select2_onchange">
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜