在模糊事件中添加异常

Adding exceptions in blur event

本文关键字:添加 异常 事件 模糊      更新时间:2023-09-26

我在做一个简单的选择题表格。我想验证一下,如果用户点击问题<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
}