admin管理员组文章数量:1405393
I'm trying to check if the form inputs are all empty. It works fine when any input has value (returns true) but doesn't return false when input gets empty again.
var data;
$('form :input').on('input', function() {
data = $('form').serialize();
console.log(data.indexOf('=&') > -1)
})
<script src=".1.1/jquery.min.js"></script>
<form>
<input type="text" name="in-1" />
<input type="text" name="in-2" />
<input type="text" name="in-3" />
<input type="text" name="in-4" />
<input type="text" name="in-5" />
<input type="text" name="in-6" />
<input type="text" name="in-7" />
<input type="text" name="in-8" />
</form>
I'm trying to check if the form inputs are all empty. It works fine when any input has value (returns true) but doesn't return false when input gets empty again.
var data;
$('form :input').on('input', function() {
data = $('form').serialize();
console.log(data.indexOf('=&') > -1)
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="in-1" />
<input type="text" name="in-2" />
<input type="text" name="in-3" />
<input type="text" name="in-4" />
<input type="text" name="in-5" />
<input type="text" name="in-6" />
<input type="text" name="in-7" />
<input type="text" name="in-8" />
</form>
Share
Improve this question
asked Jan 27, 2017 at 11:00
g5wxg5wx
7301 gold badge10 silver badges31 bronze badges
3 Answers
Reset to default 3(data.indexOf('=&') > -1
will return true when at least one of the fields is blank - you're checking for the existence of the =&, and as soon as one field is blank, this string will exist. However, relying on the serialised version of the data is a bit of a hack anyway IMHO. Much better to check the inputs directly:
$('form :input').on('input', function() {
var allBlank = true; //assume they're all blank until we discover otherwise
//loop through each of the inputs matched
$('form :input').each(function(index, el)
{
if ($(el).val().length != 0) allBlank = false; //they're not all blank anymore
});
console.log(allBlank);
});
var serialized = $(form).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){
//you've got empty values
}
Using jQuery
, you can test it before serializing:
$(form).find('input').each(function(index, elem){
if($(elem).val().length == 0){
//this field is empty
}
});
data.split('&').every(e => { return e.indexOf('=') === (e.length - 1); })
本文标签: jqueryJavascriptcheck if serialized form is emptyStack Overflow
版权声明:本文标题:jquery - Javascript - check if serialized form is empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744304975a2599766.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论