如何使html5和java脚本中显示所需的字段?以下是我的代码

时间:2014-09-29 18:31:09

标签: javascript html5

如果您查看下面的代码,我会使用javascript在单击另一个单选按钮时显示字段。有没有办法使用html5和javascript来显示那些显示必需的字段。

function yesnoCheckcanwork() {
    if (document.getElementById('no_to_work').checked) {
        document.getElementById('notoworkexplain').style.display = 'block';
    }
    else
        document.getElementById('notoworkexplain').style.display = 'none';
}

function yesnoCheckcanfelony() {
    if (document.getElementById('yes_to_felony').checked) {
        document.getElementById('yestofelonyexplain').style.display = 'block';
    }
    else
        document.getElementById('yestofelonyexplain').style.display = 'none';
}
<label>Are you a U.S. citizen or otherwise authorized to work in the U.S. on an unrestricted basis?:</label>
<input type="radio" id="yes_to_work" value="yes_to_work" name="can_work"  onclick="javascript:yesnoCheckcanwork();" required="required"><label for="yes_to_work" class="light">Yes</label>
<input type="radio" id="no_to_work" value="no_to_work" name="can_work"    onclick="javascript:yesnoCheckcanwork();" required="required"><label for="no_to_work" class="light">No</label>

<div id="notoworkexplain" style="display:none">
    <label for="no_to_work_explain">Please explain:</label><textarea id="no_to_work_explain" name="no_to_work_explain"></textarea>
</div>

<label>Have you ever been convicted of a felony?:</label>
<input type="radio" id="yes_to_felony" value="yes_to_felony" name="felony" onclick="javascript:yesnoCheckcanfelony();" required="required"><label for="yes_to_felony" class="light">Yes</label>
<input type="radio" id="no_to_felony" value="no_to_felony"   name="felony" onclick="javascript:yesnoCheckcanfelony();" required="required""<label for="no_to_felony" class="light">No</label>

<div id="yestofelonyexplain" style="display:none">
    <label for="yes_to_felony_explain">Please provide date of conviction and fully describe the circumstances:</label><textarea id="yes_to_felony_explain" name="yes_to_felony_explain" ></textarea>
</div>

1 个答案:

答案 0 :(得分:0)

您需要做的就是将元素的required属性设置为truefalse

所以试试这个:

function yesnoCheckcanwork() {
    if (document.getElementById('no_to_work').checked) {
        document.getElementById('notoworkexplain').style.display = 'block';
        document.getElementById('no_to_work_explain').required = true;
    } else {
        document.getElementById('notoworkexplain').style.display = 'none';
        document.getElementById('no_to_work_explain').required = false;
    }
}

function yesnoCheckcanfelony() {
    if (document.getElementById('yes_to_felony').checked) {
        document.getElementById('yestofelonyexplain').style.display = 'block';
        document.getElementById('yes_to_felony_explain').required = true;
    } else {
        document.getElementById('yestofelonyexplain').style.display = 'none';
        document.getElementById('yes_to_felony_explain').required = false;
    }
}

以下是演示:http://jsfiddle.net/dbhz2nj9/