开发者

how to access arraylist sent from server in Javascript

I have a requirement of displaying a dropdown list based on the arraylist being sent from the server on certain conditions on load of the page and on change of the event For example ArrayList1,ArrayList2

 if(condition is true)

 display the contents to dropdownlist from arraylist1

else

 display the contents to dropdow开发者_StackOverflow社区nlist from arraylist 2

Can any one tel how this arraylist can be saved on the page as hidden field so i can access the same in javascript. ??


If you already have the array you could do somthing like this:

 <form>
    <select id="my_seelecyt">
    </select>
</form>
<script type="text/javascript">
    var list1=['a','b','c'];
    var list2=['e','f','g'];
    var list;
    var select_box = document.getElementById('my_seelecyt');
    if(condition is true){
        list=list1;
    }else{
        list=list2;
    }
    for(var i=0; i<list.length; i++){
        var op = document.createElement('option');
        op.value=list[i];
        op.innerHTML =  list[i];
        select_box.appendChild(op);
    }
</script>


you have to options:

  • Using ajax to create a request to the server and store the response in a variable I. e. the js-framework jquery allows you to make a post request and get it back)
  • Using a server side technology like php, jsp, asp to put the response into a javascript variable


If you meant that you pre-generate the drop-down lists and then toggle that in JS based on some criteria, then this is how it could be done:

First generate HTML:

<div id="arraylist1" style="display:none">
  <select>
    <option>Option1</option>
    <option>Option2</option>
  </select>
</div>
<div id="arraylist2" style="display:none">
  <select>
    <option>Option1</option>
    <option>Option2</option>
  </select>
</div>

<!-- This is the placeholder for the dropdown -->
<div id="list"></div>

And then use this in JavaScript:

var arrayList = condition ? $('div#arrayList1') : $('div#arrayList2');
$('#list').append(arrayList);
arrayList.show();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜