如何检查以确保我的所有输入:无线​​电元素都有值?

时间:2015-10-12 22:39:29

标签: javascript jquery forms

我正在处理一个表单,我有一个用于验证无线电字段的代码。然而,我计划拥有许多,无数的无线电领域,我觉得我现在的方法,单独命名每个无线电领域,有点单调乏味。我觉得必须有一种方法可以简单地选择所有这些,以确保在处理表单之前已经对它们进行了全部检查。

这是我的jsFiddle

当前的jQuery

$("form").on("keyup change", function(){

food = $(":checked[name=food]");
color = $(":checked[name=color]");

if (food.val() == "" || food.val() == undefined || 
   color.val() == "" || color.val() == undefined){

//Do stuff

} else {

//Do other stuff

}
});

jQuery我正在尝试

$("form").on("keyup change", function(){

radio_req = $(".required:checked[type=radio]");

if ( radio_req == "" || radio_req == undefined ) {

//Do stuff

} else {

//Do other stuff

}
});

对于第二个,我试图看看我是否可以在我的所有无线电字段中添加一类必需,然后查看是否有任何.required单选按钮未选中/未定义。我觉得必须要有办法让它发挥作用。我是在正确的轨道上吗?我觉得我只是没有选择这个权利。

2 个答案:

答案 0 :(得分:1)

我已更新您的fiddle,请检查一下! 我希望它能解决你的问题。

您可以在下方测试该代码段。 这是我修改过的部分:

var checker = function(){    

var checked = $.unique($(".required:checked[type=radio]").map(function(){
    return  this.name;
}));
var not_checked = $.unique($(".required:not(:checked)[type=radio]").map(function(){
    return  this.name;
}));

if (checked.length !== not_checked.length){

    $("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
    $(".submit").text("* All fields must be completed and contain valid entries before submitting.");


} else {

$("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
    $(".submit").text("");
}   
};
$("form").on("keyup change", checker);
checker();

$(document).ready(function(){
  
  // for each Question we have 3 choices:
  // so when we answer we have 1 checked and 2 unchecked
 
  // we loop over question
  // we fill 2 arrays(checked, unchecked) 
  // with names of radio 
  
  // for each question we will have something like that
  // Question 1 : food
  // checked = ['food']; notchecked = ['food','food']
  // we make them unique ! it becomes
  // checked = ['food']; notchecked = ['food'];
  // we know now that the First question have been answered
  
  // we loop over all question :
  // checked = ['food'] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
  
  // we wait for checking !
  // let answer Qestion 2
  // checked = ['food' , 'color] , notchecked = ['food' , 'color' , 'town' , 'country' , 'car']
  // etc etc . . . 
  
  // when checked.length === notchecked.length => we have an answer for all question
  
var checker = function(){    

    var checked = $.unique(
      $(".required:checked[type=radio]").map(function(){
        return  this.name;
      })
    );
	var not_checked = $.unique(
      $(".required:not(:checked)[type=radio]").map(function(){
        return  this.name;
      })
    );
	
    if (checked.length !== not_checked.length){
    
        $("#submit").prop("disabled", true).removeClass("valid").addClass("invalid");
		$(".submit").text("* All fields must be completed and contain valid entries before submitting.");
	

    } else {
		
    $("#submit").prop("disabled", false).removeClass("invalid").addClass("valid");
		$(".submit").text("");
    }   
};
$("form").on("keyup change", checker);
checker();
    
});
input {
    margin: 7px;
}

.valid {
    background-color: green;
    border: 3px solid darkgreen;
    color: white;
}

.invalid {
    background-color: grey;
    border: 3px solid darkgrey;
    color: black;
}

.error {
    color: red;
}

#submit {
    display: block;
    border-radius: 10px 10px 10px 10px;
    width: 130px;
    margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  
  <br>Which of the following do you like the most?
  <br>
  <input type="radio" class="required" name="food" value="pizza">Pizza
  <input type="radio" class="required" name="food" value="burgers">Burgers
  <input type="radio" class="required" name="food" value="Salads">Salads
  <br>
  <br>Which of the following colors do you like the most?
  <br>
  <input type="radio" class="required" name="color" value="red">Red
  <input type="radio" class="required" name="color" value="blue">Blue
  <input type="radio" class="required" name="color" value="yellow">Yellow 
  <br>
  <br>Which of the following town do you like the most?
  <br>
  <input type="radio" class="required" name="town" value="red">New York
  <input type="radio" class="required" name="town" value="blue">Miami
  <input type="radio" class="required" name="town" value="yellow">Las Vegas 
  <br>
  <br>Which of the following country do you like the most?
  <br>
  <input type="radio" class="required" name="country" value="red">USA
  <input type="radio" class="required" name="country" value="blue">Canada
  <input type="radio" class="required" name="country" value="yellow">Chili
  <br>
  <br>Which of the following car do you like the most?
  <br>
  <input type="radio" class="required" name="car" value="red">Ferrari
  <input type="radio" class="required" name="car" value="blue">Dodge
  <input type="radio" class="required" name="car" value="yellow">Chevrolet

  <br><br>
  <input type="submit" id="submit" class="invalid">
  <span class="submit error"></span>
</form>

答案 1 :(得分:0)

您可以遍历具有名称属性:radio[name]的所有单选按钮以及数组,例如examined,它可以帮助您跳过已经检查过的按钮。无论您有多少组单选按钮,这都应该可以正常工作。

$('form').on('input change', function(e) {
    e.preventDefault();
    var all_selected = true;
    var examined = [];
    $(':radio[name]').each(function() {
        if( examined.indexOf( this.name ) === -1 ) {
            examined.push( this.name );
            if( !$(':radio:checked[name=' + this.name + ']').length ) {
                all_selected = false;
                return false;
            }
        }
    });
    if( all_selected ) {
        //DO STUFF
    } else {
        //DO OTHER STUFF
    }
});

$(function() {
    $('form').on('input change', function(e) {
        e.preventDefault();
        var all_selected = true;
        var examined = [];
        $(':radio[name]').each(function() {
            if( examined.indexOf( this.name ) === -1 ) {
                examined.push( this.name );
                if( !$(':radio:checked[name=' + this.name + ']').length ) {
                    all_selected = false;
                    return false;
                }
            }
        });
        if( all_selected ) {
            //DO STUFF
            console.log( 'All parts completed' );
        } else {
            //DO OTHER STUFF
            console.log( 'Form not complete' );
        }
    });
});
input {
    margin: 7px;
}

.valid {
    background-color: green;
    border: 3px solid darkgreen;
    color: white;
}

.invalid {
    background-color: grey;
    border: 3px solid darkgrey;
    color: black;
}

.error {
    color: red;
}

#submit {
    display: block;
    border-radius: 10px 10px 10px 10px;
    width: 130px;
    margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    Which of the following do you like the most?<br>
    <input type="radio" class="required" name="food" value="pizza">Pizza
    <input type="radio" class="required" name="food" value="burgers">Burgers
    <input type="radio" class="required" name="food" value="Salads">Salads <br><br>
        
    Which of the following colors do you like the most?<br>
    <input type="radio" class="required" name="color" value="red">Red
    <input type="radio" class="required" name="color" value="blue">Blue
    <input type="radio" class="required" name="color" value="yellow">Yellow
        
    <input type="submit" id="submit" class="invalid">
        <span class="submit error"></span>
</form>