在模糊事件中添加异常
Adding exceptions in blur event
我在做一个简单的选择题表格。我想验证一下,如果用户点击问题<textarea>
并点击页面上的其他地方,而没有在问题选项的<input type="text" name="q1_option1">
中输入值,那么用户应该得到一个alert("Wait, you forgot to enter options for Question 1");
。我试过这样做,但这根本不是我想要的。
这是<html>
<div class="right">
<div class="row" style="margin:5px;">
<label><strong>Question 1</strong></label>
<div>
<textarea name="question1"></textarea>
</div>
</div>
<div class="row">
<div class="span-4"><input type="text" name="q1_option1" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option2" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option3" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option4" value="" class="q1" /></div>
<div class="clear"></div>
</div>
</div>
这是<script>
<script type="text/javascript">
$(function(){
$('textarea[name=question1]').blur(function(){
$('.right').click(function(event) {
if($(event.target).is('input[name=q1_option1]')) {
$('#alert_error_message').text('Please enter all options in Question 1!!');
callalert();
return false;
}
else
{
alert('Not working!');
}
})
})
})
</script>
现在看看这段代码中发生了什么,当用户单击<input>
输入选项时,blur
被触发,用户得到警报。
我想要的是,如果用户点击这些<input>
的答案,他不应该得到警报,否则,用户必须得到警报,因为没有在<input>
的选项中输入值!!
DEMO
我想出了下面的方法,我将解释我用下面的代码做什么。检查是否有内联注释
$(function(){
var hasFocus=false; //this variable is used to check whether focus was on textarea
//when clicked on document
$('textarea[name=question1]').blur(function(event){
setTimeout(function(){
hasFocus=false; //on blur set the variable to false but after sometime
},100);
}).focus(function(){
hasFocus=true; //on focus set it to true again
});
//A click event on document so that to display alert only if textarea had focus and the
//targetted element is not radio button
$(document).on('click',function(e){
if($(e.target).attr('class')!='q1' && hasFocus && $(e.target).attr('name')!="question1")
{
if(!$('.q1:checked').length) //if any radio has been checked
{
//if not checked then display alert
alert('Please select an option');
}
}
});
})
这个怎么样?
var all_filled = true;
// for each component having class "q1", if the value is empty, then all_filled is false
$('.q1').each(function(comp){
if(comp.val() == ''){
all_filled = false;
break;
}
});
// if not all input is filled, then do what you want
if(!all_filled){
// do what you want
}
相关文章:
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在映射数组中添加换行符
- 正在将数据主题添加到所有项目
- ZeroClipboard-在复制之前添加到值
- 我可以在json对象中添加一个函数吗
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何添加浮动和非浮动,其他
- 添加文字和评论功能更新Div
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 在函数中添加数组元素的数值
- 将方法添加到数字引发异常
- 如何将异常添加到“CSS Top, JavaScript Bottom”Wordpress Function
- 在模糊事件中添加异常
- 在ExpressJS中添加一个异常app.use()
- 给esLint添加异常
- 重新添加对话框时出现 JQuery 移动异常
- 在onbeforeunload纯javascript上添加异常
- 添加OnError后出现异常错误