简体   繁体   中英

If statement returns true though only one of several conditions are met (jQuery)

I want to notify users answering a form if any of the optional radio buttons are left unanswered before submitting (as to ensure that they've been skipped intentionally). My problem is that although I'm setting up an if-statement with several conditions the if-statement returns true when any one of the conditions is met instead of when all of them are met. I'm using jQuery 1.7.1.

Javascript:

$("#optmsg").show();
function updateFormEnabledOpt() {
if (verifyOpt()) {
    $("#optmsg").hide();
} else {
    $("#optmsg").show();
}
}

function verifyOpt() {
if ($("#formidable input:radio[name='q11']:checked").val() !== 'undefined' && $("#formidable input:radio[name='q12']:checked").val() !== 'undefined' && $("#formidable input:radio[name='q13']:checked").val() !== 'undefined') {
    return true;
} else {
    return false;
}
}

$('#formidable input:radio[name="q11"]').change(updateFormEnabledOpt);
$('#formidable input:radio[name="q12"]').change(updateFormEnabledOpt);
$('#formidable input:radio[name="q13"]').change(updateFormEnabledOpt);​

So: As soon as any of the three questions has a checked radio button #optmsg gets hidden. Jsfiddle (with some html to go with the script): http://jsfiddle.net/rnPA6/

UPDATE: Thanks for the help! With blazing speed I might add! Here's a working fiddle: http://jsfiddle.net/rnPA6/14/

val() method returns and empty string if nothing is set in the input element which is not equal to undefined due to which if condition was passing through. Try this which will not pass if the value is empty.

if ($("#formidable input:radio[name='q11']:checked").val() 
     && $("#formidable input:radio[name='q12']:checked").val() 
     && $("#formidable input:radio[name='q13']:checked").val() ) {

}

When no value is set for a input radio button jQuery returns "on" when you call val() method on it. So you should set atleast a empty value to each of the radio button if not set.

You are comparing using and(&&). In this jsfiddle, I fixed your code to use or(||).

您正在与包含文本'undefined'而不是值undefined的字符串进行比较。

This will do:

function updateFormEnabledOpt() {
  $("#optmsg").show();
  if (($("#formidable input:radio[name='q11']:checked").val() !== undefined) && ($("#formidable input:radio[name='q12']:checked").val() !== undefined) && ($("#formidable input:radio[name='q13']:checked").val() !== undefined)) {
      $("#optmsg").hide();
  } 
}

$('#formidable input:radio[name="q11"]').change(updateFormEnabledOpt);
$('#formidable input:radio[name="q12"]').change(updateFormEnabledOpt);
$('#formidable input:radio[name="q13"]').change(updateFormEnabledOpt);

See it in action: http://jsfiddle.net/BwUWp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM