Question

I have a radio input with 2 options, to let user define their gender. After clicking the button jquery should check if anything is selected, and,

if it is - hide the div with the radio input and show the other one;

if it`s not (nothing is selected) show the error text.

Problem is, the code does show error text if nothing is selected, but it does not hide this div and show another one even if the user HAD selected the gender.

The jQuery part:

           $('#button_1').click(function(){
        gender = $('input:radio[name=1_gender]:checked').val();
              if ('input:radio[name=1_gender].not(:checked') {
              $("label#1_gender_error").show();
              $("input#1_gender").focus();
              return false;
              } 
            if ('input:radio[name=1_gender]:checked') {
            $('#gender_div').hide();
            $('#other_div').show();
            }
          });

The HTML part:

      <div id="gender_div">
    <form name="form_gender" action="">
    <fieldset>
      <label for="gender" id="1_gender_label">You are...</label><br />
      <input type="radio" name="1_gender" id="1_men"  value="men" class="text-input" />
      <label for="men">Men</label><br />

   <input type="radio" name="1_gender" id="1_woman"  value="woman" class="text-input" />
   <label for="woman">Woman</label>
    <br />

    <label class="error" for="1_gender" id="1_gender_error">Text for shaming for not selecting gender</label>
    <br />
    <input type="button" name="submit" class="button" id="button_1" value="Next" />
    </fieldset>
    </form>
  </div>

Any help or tips would be greatly appreciated

Was it helpful?

Solution

Something like

   $('#button_1').click(function () {


      if (!$("input:radio[name=1_gender]").is(":checked")) {
          $("label#1_gender_error").show();
          $("input#1_gender").focus();
          console.log("not checked")
          return false;
      } else {
          if ('input:radio[name=1_gender]:checked') $('#gender_div').hide();
          $('#other_div').show();
          console.log("checked")
      }
  });

Will work for you

Fiddle

You're validating a string in your if statement

if ('input:radio[name=1_gender].not(:checked')

And it will always result to true

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top