根据下拉选择将输入字段设置为必填字段

Make input field mandatory based on drop down selection

本文关键字:字段 设置 输入 选择      更新时间:2023-09-26

如果我选择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 事件进行选择。在这里工作 jsFiddle

.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()" />

爪哇语

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

在这里工作演示

你应该

使用onchange而不是onclickif (cat == "C")而不是if(cat == "nil")

function selection()
{
 var cat = document.getElementById('select').value;
    if (cat == "C") {
        if (document.getElementById("test1").value == "") {
            alert('Mandatory');
        }
    }
}
<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" onchange="selection()" />
    <input type="button" value="submit" onclick="selection()" />

此外,您需要使用 input onchange="selection()" 来检测用户在选择输入时是否已清除输入c

<html>
<head>
    <title></title>
</head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<body>
    <script>
 $(document).delegate("#select","change",function(e){
        if ($(this).val() === 'C')
            $('#save').attr('onclick','chk()');
        else
           $('#save').removeAttr('onclick');
    });
 function chk()
 {
    var name=$('#name').val();
    if(name=="")
    {
        alert("Mr. Hussy Please fill this box");
    }
 }
</script>
<select name="test" id="select">
<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="name" />
 <input id='save' type="button" value="submit" />
    </body>
</html>