我有一个表单,一旦用户向该字段添加值,每个字段上方都会显示小标签。
这个for有时会加载一些预先填充的字段。
如果任何表单字段有值,我如何检查页面加载?如果有,是否可以看到标签?
这是我的当前代码,用于在字段具有值时显示标签:
$('.form-control').blur(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
答案 0 :(得分:0)
试试这个:
$('.form-control').each(function() {
if( $(this).val() ) {
$(this).prev().show();
}
});
答案 1 :(得分:0)
$(document).ready(function(){
$('.form-control').each(function(){
if($(this).val() != ''){
$(this).prev().show();
}
});
});
在文档就绪时,对于每个.form-control,如果输入的值不为空,请执行您要显示标签的任何代码。
答案 2 :(得分:0)
使用focusout
事件不会有太大的影响,是吗?
<script type="text/javascript">
(function ($) {
$(document).ready(function (e) {
// ALTHOUGH BLUR IS OK, ONE COULD SIMPLY BIND THE .form-control CLASSES TO THE focusout EVENT
// THIS ENSURES THAT THERE IS A HIGHER LIKELIHOOD THAT THE FIELD IN QUESTION ONCE HAD FOCUS
// WHICH MAY IMPLY THAT THE USER ALSO INTERACTED WITH THE FIELD IN SOME WAY...
$('.form-control').each(function(elem){
var objElem = $(this);
objElem.focusout(function(evt) {
if ($(this).val()) {
// NOW, YOU SHOULD KNOW WHICH METHOD TO USE TO TRAVERSE THE DOM
// AND GET AT THE LABEL....
// IN YOUR CASE IT SEEMS TO BE THE PREVIOUS ELEMENT BEFORE THE FORM-FIELD.
$(this).prev().show();
}
});
});
});
})(jQuery);
</script>