javascript - 根据下拉选择使输入字段成为必填项

标签 javascript jquery html

如果我选择A,B,C输入框不是必填的。如果我选​​择C,测试输入框应该是必填的。 我试过了,但它不起作用。

HTML:

<select name="test" id="select" onclick="selection()">
<option value="">A</option> 
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
    </select> 
<td>test</td>                           
<td><input type="text" name="test1" id="test1" />
 <input type="button" value="submit" onclick="selection()" />

JS:

function selection()
{
 var cat = document.getElementById('select').value;
    if (cat == "nil") {
        if (document.getElementById("test1").value == "") {
            alert('Mandatory');

        }

    }
}

最佳答案

使用onchange选择事件。 Working jsFiddle here

HTML

<select name="test" id="select" onchange="selection()">
<option value="">A</option> 
<option value="B">B</option>
<option value="C">C</option>
<option value="nil">nil</option>
    </select> 
<td>test</td>                           
<td><input type="text" name="test1" id="test1" />
 <input type="button" value="submit" onclick="selection()" />

Javascript

function selection()
{    
 var cat = document.getElementById('select').value;    
    if (cat == "nil") {
        if (document.getElementById("test1").value == "") {
            alert('Mandatory');
            return false;
        }

    }
    return true;
}

Working Demo Here

关于javascript - 根据下拉选择使输入字段成为必填项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943428/

相关文章:

javascript - 如何在我的案例中将数组存储在对象中

javascript - 如何在jquery/javascript中将对象转换为数组

javascript - jQuery 在 IE10 中未触发

javascript - SetState 被多次调用

javascript - 确定两个点是否在javascript中一条线的同一侧

javascript - 分配 anchor 标记的 href

html - 背景图像鼠标悬停,开始按钮效果

javascript - 使用scrollOverflow时fullPage.js不检测动态生成内容的高度

javascript - 将鼠标悬停在与 Raphaël.js 关联的链接上时出现路径填充效果问题

javascript - 如何使用 Google-Maps-Api-3 绘制多个多边形?