简体   繁体   中英

jQuery - Unchecked radio buttons not returning a value

For the life of me I can't figure out what I'm doing wrong, I have a basic form with a radio button and a text box. I'm trying to perform a basic validation so if I add a text area or select box in the future it will validate using if($this).val() === '') it works great for those but why not my radio buttons? When I try to alert the length I only get one alert message not two? Any help is greatly appreciated! JS Fiddle link http://jsfiddle.net/5Sacj/

<div class="two-column">
  <label id="gender" for="gender">Gender</label>
  <input type="radio" name="customer" value="male" />Male
  <input type="radio" name="customer" value="female" />Female
</div>

<div class="two-column">
  <label for="fname">*First Name</label>
  <input type="text" class="text" id="fname" name="fname" />
</div>

JQUERY

$(document).ready(function() {     
    $(":text, :radio").each(function() {
    if($(this).val() === "")
     alert($(this).length);
    });
});

This works for textboxes and radio buttons.

$(":text, :radio").each(function() {
    if($(this).val() === "" || !$(this).is(':checked'))
        alert($(this).length);
});

If you want it to work for textareas and all types of input, change your selector to:

$("input, textarea").each(function() {
   // same code
});

EDITED: http://jsfiddle.net/5Sacj/2

Because the value of both radio items are already set.

<input type="radio" name="customer" value="male" />Male
<input type="radio" name="customer" value="female" />Female

If you change your JS to
$(document).ready(function() {

  $(":text, :radio").each(function() { alert($(this).length); }); }); 

You will get three popups.

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