我在做一个简单的选择题形式。我想验证一下,如果用户单击问题<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>的选项!!
发布于 2015-10-06 05:35:17
我想出了下面的方法,我将解释我正在用下面的代码做什么。检查内联注释。
$(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');
}
}
});
})发布于 2015-10-06 05:00:52
这个怎么样?
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
}https://stackoverflow.com/questions/32961993
复制相似问题