检查两个输入字段中的至少一个是否有数据
问题描述:
我有两个输入字段,并且我想确保在单击按钮时至少填充了其中一个字段。检查两个输入字段中的至少一个是否有数据
First name: <input type="text" name="FirstName" id="first"><br>
Last name: <input type="text" name="LastName" id="second"><br>
<button type="submit" value="Submit">submit</button
这怎么能通过jQuery来完成? html代码中没有表单标签。
答
使用条件$('#first').val() || $('#second').val()
,像这样:
$('body').on('click', 'button', function() {
if ($('#first').val() || $('#second').val()) { // will fail if both are ''
alert("At least one has data");
} else {
alert("Oops! No data");
}
});
答
尝试这样的:使用trim
从开始和结束或仅空间安全。
$('body').on('click', 'button', function() {
if ($('#first').val().trim().length > 0 || $('#second').val().trim().length > 0) {
alert("we have some data");
} else {
alert(" No data entered");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First name: <input type="text" name="FirstName" id="first"><br>
Last name: <input type="text" name="LastName" id="second"><br>
<button type="submit" value="Submit">submit</button>
感谢您的回答。这是我正在寻找的。 – Rahul 2014-12-19 07:18:25