<select id="gameid">
//<option is a number 1-999>
</select>
<select id="netid">
//<option is a number 1-999>
</select>
<select id="camp_id">
<script>
var a = $("#gameid").val();
var b = $("#netid").val();
var c = a+b;
for (var i = 1; i<=999; i++)
{
document.write("<option value='"+c+i+"'>"+c+i+"</option>");
}
</script>
</select>
上面的代码是为选择生成一些选项。
我想要做的是,如果#gameid中的val被更改,选项列表也会改变,#netid也会改变。
但是,该选项不会改变。它保留在#gameid和#netid的默认值中。
我不知道我在这里失踪了什么。我需要帮助。
[UPDATE]
这段代码几乎可以工作。但是,当我在选择后对#cameid进行第二次更改时,它不再更改#campid选项。如果我在#netid上做了更改,它会再次更改它。
$("#gameid" && "#netid").on('change', function(){
a = $("#gameid").val(),
b = $("#netid").val(),
c = a+b;
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
答案 0 :(得分:2)
Use change event
$('#gameid,#netid').on('change',function (){
var a = $("#gameid").val();
var b = $("#netid").val();
alert($(this).attr('id'));
var c = parseInt(a)+parseInt(b);
if ( $(this).attr('id') == 'gameid') {
$el = $("#netid");} else {$el = $("#gameid")};
$el.text('');
for (var i = 1; i<=999; i++)
{
$el.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
note: I used jquery, jsfiddle: https://jsfiddle.net/1zgre9pw/4/
答案 1 :(得分:2)
Use something like this:
var options = '';
for (var i = 1; i<=999; i++)
{
options += "<option value='"+c+i+"'>"+c+i+"</option>";
}
document.getElementById('camp_id').innerHTML = options;
Use similar to insert options to other select boxes if needed
答案 2 :(得分:2)
Don't forget to add Jquery library,
<select id="gameid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="netid" onchange="generateOptions();">
<!-- Your Options -->
</select>
<select id="camp_id">
</select>
<script type="text/javascript">
var a,b,c,str="";
function generateOptions()
{
a = $("#gameid").val();
b = $("#netid").val();
c = a+b;
for (var i = 1; i<=999; i++)
{
str= str + "<option value='"+c+i+"'>"+c+i+"</option>";
}
$('#camp_id').html(str);
}
</script>
答案 3 :(得分:2)
var a = $("#gameid").val(),
b = $("#netid").val(),
c;
$("#gameid").change(function(){
a = $(this).val();
c = parseInt(a)+parseInt(b);
$("#camp_id").empty();
for (var i = 1; i<=999; i++){
$("#camp_id").append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
});
答案 4 :(得分:1)
As you want to add options to HTML select
dynamically. I have tried to achieve the same using jquery i.e. to be call on $('#gameid').populate();
.
Firstly, Add jquery library in <head>
of page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>`
$.fn.populate = function () {
var $this = $(this);
for (var i = 1; i<=999; i++){
$this.append("<option value='"+(c+i)+"'>"+(c+i)+"</option>");
}
}
$('#gameid').populate();
You can add same for second select
(drop-down) as well.