我有5个输入文本(应答选项),如果在非空输入之前有空白输入,则会给出错误。从A到E选项说,用户只填写C和D.系统会给出错误,表示选项A和B为空(而E不报告为错误)。代码如下。问题是,有没有更简单的方法呢?
https://jsfiddle.net/cyw8otLo/
<div>
<input type="text" id="optA" value="" /><br/>
<input type="text" id="optB" value="" /><br/>
<input type="text" id="optC" value="C" /><br/>
<input type="text" id="optD" value="D" /><br/>
<input type="text" id="optE" value="" /><br/>
<input type="submit" id="register" value="Register" />
</div>
脚本
function getInputTextOf(searchStr, str, caseSensitive) {
var optArr = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'};
var startIndex = 0, searchStrLen = searchStr.length;
var index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(optArr[5 - index]);
startIndex = index + searchStrLen;
}
return indices;
}
var $input = $('input:text'),
$register = $('#register');
$('#register').on('click', function() {
var trigger = true;
var str = '';
$($('div > input[id^="opt"]').get().reverse()).each(function (i) {
str = str + ($(this).val() === '' ? 0 : 1);
});
var space = '*****';
var start = str.indexOf("10"); //input start at
if (start > -1) {
var abc = space.substring(0, start+1) + str.substring(start+1, str.length);
var indices = getInputTextOf("0", abc, false);
alert('Option ' + indices.sort() + ' still empty!');
}
});
答案 0 :(得分:1)
您可以尝试类似
的内容
var $input = $('input:text'),
$register = $('#register');
$('#register').on('click', function() {
var error, filled;
$($input.get().reverse()).each(function() {
if (this.value != '') {
filled = true;
} else if (filled && this.value == '') {
error = true;
return false;
}
})
if (error) {
alert('e')
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="text" id="optA" value="" /><br/>
<input type="text" id="optB" value="" /><br/>
<input type="text" id="optC" value="C" /><br/>
<input type="text" id="optD" value="D" /><br/>
<input type="text" id="optE" value="" /><br/>
<input type="submit" id="register" value="Register" />
</div>
&#13;
答案 1 :(得分:0)
你可以尝试将标志设置为布尔false
:
var flag = false;
$('input[type="text"]:not(:last)').each(function() {
if ($.trim(this.value) == "") {
$(this).addClass('error').focus();
return false;
} else {
flag = true;
}
return flag;
});
&#13;
.error {
border: solid 1px red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="optA" value="aaaa" />
<br/>
<input type="text" id="optB" value="bbb" />
<br/>
<input type="text" id="optC" value="C" />
<br/>
<input type="text" id="optD" value="D" />
<br/>
<input type="text" id="optE" value="" />
<br/>
<input type="submit" id="register" value="Register" />
</div>
&#13;