3

所以我有这个代码。我想为 javascript 人完成一些可能很简单的事情。如果选择了某个选项,则在 div 上添加一个输入字段。

<select name="amount" >
    <option value="50">50$</option>
    <option value="100">100$</option>
    <option value="Other">Other</option>
</select>

<div id="custom_price">

</div>

所以我想在选择“其他”选项后添加输入字段。我知道有一个简单的方法可以解决这个问题,但我无法让它发挥作用:

document.getElementById('custom_price').innerHTML += "<input type="text" name="amount"/>"

所以 custom_div 看起来像:

<div id="custom_price">
Custom price:<br>
<input type="text" name="amount"/>
</div>
4

5 回答 5

6

最好的方法是实际制作 dom 元素。

var newInput = document.createElement("input");
newInput.type="text";
newInput.name="amount";
document.getElementById('custom_price').appendChild(newInput);

也许有这样的处理程序:

为您的选择分配一个 ID:<select name="amount" id="amount">

$("#amount").change( function() {
 if( $(this).val() == "Other" ){
  document.getElementById('custom_price').innerHTML = "";
  var newInput = document.createElement("input");
  newInput.type="text";
  newInput.name="amount";
  document.getElementById('custom_price').appendChild(newInput);
 }
});
于 2012-08-14T19:16:37.517 回答
3

根据您使用 jQuery 的问题的标签来判断。所以添加一个输入是相当容易的。

$("select[name=amount]").change(function() {
    if ($(this).val() == 'Other') {
        $("#custom_price").append('<input type="text" name="amount"/>');
    }
})
于 2012-08-14T19:18:22.083 回答
1

它是

document.getElementById('custom_price').innerHTML += '<input type="text" name="amount" />';

如果使用"_ "_\"'

于 2012-08-14T19:20:00.893 回答
0

使用 jQuery

$("#custom_price").empty().append('Custom price:<br><input type="text" name="amount"/>')
于 2012-08-14T19:17:03.087 回答
0

只需将输入放在 div 内并最初隐藏 div。然后在必要时使用 jQuery/JS 显示这个 div。

$('select[name="amount"]').change(function() {
    if($(this).val() == 'Other') {
        $('#custom_price').show();
    } else {
        $('#custom_price').hide();
    }
});

<div id="custom_price" style="display: none;">
    <p>Custom price:</p>
    <input type="text" name="amount"/>
</div>
于 2012-08-14T19:17:53.727 回答