[英]Check value of form input and give alert if it is empty
我正在做一個測驗,並試圖在單擊“下一步”按鈕時檢查輸入字段是否為空。 如果有人沒有回答問題,那么我想發出警報,阻止他們繼續下一個問題。
出於某種原因,就我的代碼而言,即使您在第二次嘗試中輸入了響應,對於第二個問題,它也會發出“無響應”警報。 我不知道為什么。
這是引發警報的代碼部分:
$("button").click(function() {
// check for empty input
var inputVal = $.trim($(".question:visible input").val());
console.log("The value of the input is: " + inputVal);
if (inputVal.length == 0 || inputVal == "") {
alert("Please enter a response.");
} else {
position++;
quesNum = position + 1;
// hide previous question
$(".question").hide();
// show next question
if (position < totalQues) {
$(".question").eq(position).show();
$(".questionNumber").text("Question " + quesNum + " of " +
totalQues);
} else {
// at the end of the questions, hide the questions and show the results
$(".question, .questionNumber, button").hide();
// calculate risk percentage
calculatePerc();
//show results template
$(".results").show();
showResults();
}
}
}); // end button click function
這是我的JS小提琴:
http://jsfiddle.net/amykirst/mpjg2vbk/
我應該怎么做才能使下拉警報正常工作,以便在第二次嘗試輸入響應時可以繼續操作?
您必須知道下拉列表(選擇)不是輸入標簽是選擇標簽,您正在搜索輸入,但是下拉列表是選擇而不是輸入
發生這種情況是因為在第二個問題中,您沒有使用input
,而是一個select
標記,可以使用簡單的if語句找到它: DEMO
if($(".question:visible input").length==0){
inputVal=$(".question:visible select").val();
}
一條建議:
我相信使用switch()
而不是在代碼中使用那么多的if()
語句會容易得多,效率也更高。
更新:
發生radio
問題是因為對於radio
輸入,您必須獲取已checked
無線電的值。 這是它的修復,您需要在代碼中添加另一個if()
語句: DEMO
if($(".question:visible input").length==0){
inputVal=$(".question:visible select").val();
}
else if($(".question:visible input[type=radio]").length>0){
inputVal=$(".question:visible input[type=radio]:checked").val();
if($(".question:visible input[type=radio]:checked").length==0) inputVal='';
}
UPDATE2:
您需要添加另一個if()
語句: DEMO
if($(".question:visible input").length==0){
inputVal=$(".question:visible select").val();
if(inputVal==null) inputVal='';
}
else if($(".question:visible input[type=radio]").length>0){
inputVal=$(".question:visible input[type=radio]:checked").val();
if($(".question:visible input[type=radio]:checked").length==0) inputVal='';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.