使用JavaScript更改HTML元素的性质

时间:2014-02-17 03:24:47

标签: javascript jquery html

我有一个带有选择菜单的html表单。菜单上的最后一个选项是“其他”。我想要做的是,如果用户选择“其他”,则选择菜单将变为文本字段。我知道这可以通过jQuery的show / hide功能完成,但我试图保持简单。我觉得这不太可能,但是有一个JavaScript命令(jQuery与否)会将select元素转换为输入元素吗?

2 个答案:

答案 0 :(得分:2)

这可行(demo

<select id='choices' name='Choice'>
    <option>Ford</option>
    <option>Toyota</option>
    <option>Honda</option>
    <option>Other</option>    
</select>

使用此JavaScript

$('#choices').on('change', function() {
    var choice = $(this);
    if(choice.val()=== 'Other') {
        choice.replaceWith('<input name="Choice"/>')
    }
});

或者更强大的解决方案(demo

<div class='ChoiceWithOther'>
    <select name='Choice'>
        <option>Ford</option>
        <option>Toyota</option>
        <option>Honda</option>
        <option>Other</option>    
    </select>
    <input name='Choice' disabled='disabled'/><a href='#' class='UndoChoice'>&times;</a>
</div>

使用此JavaScript:

var select = $('select[name=Choice]'),
    input = $('input[name=Choice]'),
    undo = $('.UndoChoice');

select.on('change', function() {
    if(select.val()=== 'Other') {
        select.prop('disabled', true); //Disbaled inptus won't be sent on FORM submits
        select.hide(); //Don't confuse user

        input.prop('disabled', false);
        input.show();
        undo.show();
    }
});

undo.on('click', function() {
    select.prop('disabled', false); //Disabled inputs won't be sent on FORM submits
    select.show(); //Don't confuse user
    select.val($('option:first', select).val()); //reset to first value

    input.prop('disabled', true);
    input.hide();
    undo.hide();
});

input.hide();
undo.hide();

答案 1 :(得分:0)

纯JavaScript解决方案:JSFiddle Demonstration

用文本字段替换select元素。如果要保留select元素,请注释document.getElementById("choice").remove();并取消注释else语句,以便最终用户可以更改其选择。

<强> HTML:

<form id="myForm">
    <select id="choice" onchange="checkOptions(this.value);">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
      <option value="other">Other</option>
    </select>
</form>

<强> JavaScript的:

function checkOptions(value) {
    form = document.getElementById("myForm");
    if(value == "other") {
        input = document.createElement("input");
        input.setAttribute("id", "otherText");
        form.appendChild(input);
        document.getElementById("choice").remove();
    }
    /*else {
        if(document.contains(document.getElementById("otherText")))
            document.getElementById("otherText").remove();
    }*/
}