是否可以从javascript重新创建一个选择?

时间:2018-02-16 20:37:25

标签: javascript html

我正在尝试从Javascript中更改现有选择的值,过了一段时间在互联网上寻找我不确定是否可行。

我有这段代码:

function clickPic(pic_select, choosen, opt){
    //Here I change the border of a selected image
    if (opt!=0){
    pic_select.style.border = "3px solid blue";
    }else{pic_select.style.border = "3px solid red";}
    // here I send the variable (it's a number) which I want to change the values of the select.
    var option_master = opt; 
    cambiarSelect(option_master);   
}

    function cambiarSelect(num){
       //here num is 4 or 6 or 12, depending
       //this is the select itself
        var people = document.getElementById('people');
       //I guess here I reset the select
        people.options.length=0;

        for(var i=1;i<=num.length;i++){
            //here I want to change the values of the select with the same number than num, because thats the value I'm interested to select later
            people.options[i]=new Option(i);
        }
    }

我很抱歉我的编程方式但是我已经很长时间没有触摸键盘了,但是我记得有可能有​​些如何

1 个答案:

答案 0 :(得分:3)

&#13;
&#13;
function cambiarSelect(num) {
  //here num is 4 or 6 or 12, depending
  //this is the select itself
  var people = document.getElementById('people');
  //I guess here I reset the select
  
  people.innerHTML = ''; //Clean your select

  for (var j = 1; j <= num; j++) {
    //here I want to change the values of the select with the same number than num, because thats the value I'm interested to select later
    people.add(new Option(j, j));
  }
}

cambiarSelect(6);
&#13;
<select id='people'>
<option>Temporary</option>
<option>Temporary2</option>
<option>Temporary3</option>
</select>
&#13;
&#13;
&#13;

资源