1

データを入力したい選択ボックスのある単純なフォームがありますが、その方法がわかりません。

これは私のフォームです:

<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>

これは私がJSで試したことです:

var name = 'test';
var i = 1;
document.form.req_one =new Option(name, i);

これにより、同等の結果が得られるはずです。

<option value="1"> Test </option>

私は何が間違っているのですか?

4

4 に答える 4

3

Your HTML is invalid, you are closing the select tag

Also wait until the select is available in the DOM

Here is an example

window.addEventListener("load", function() {
  const name = 'test';
  const value = 1;
  const sel = document.querySelector("[name=req_one]"); // or give it an ID and use document.getElementById("req_one")
  if (sel) {
    sel.options[sel.options.length] = new Option(name, value);
  } else {
    alert("Where did the sel go?");
  }
})
<form name="myform">
  <select name="req_one" style="width:250px;"></select>
</form>

于 2013-02-26T06:21:56.900 に答える
1

jqueryを使った簡単な方法を提案します。

var name = 'test';
var i = 1;
$("select[name='req_one']").append('<option value="'+i+'">'+value+'</option>');

jqueryの使い方を知っているといいのですが。

于 2013-02-26T06:26:33.167 に答える
0

Option新しく作成したものをselect要素のオプションリストに追加するのを忘れています。

document.form.req_one.options[0] = new Option(name, i);

JSFiddleの例:http ://jsfiddle.net/zxT8U/2/

于 2013-02-26T06:34:02.087 に答える
0

あなたは小さな間違いを犯しました。コード全体を統合しました:

<html>
<head>
<script type="text/javascript">
function l1(){
    var name = 'test';
    var i = 1;
    document.form.req_one.options[0] =new Option(name, i);//you forgot to include .options[0]
}
</script>
</head>
<body onload="l1()">
<form name="form">    
 <select name="req_one" style="width:250px;"/> </select>    
</form>
</body>
</html>
于 2013-02-26T06:24:29.963 に答える