【问题标题】:How do I check to make sure all my input:radio elements have a value?如何检查以确保我所有的 input:radio 元素都有一个值?
【发布时间】:2015-10-13 22:11:42
【问题描述】:

我正在处理一个表单,并且我有一个用于验证无线电字段的代码。但是,我计划拥有很多很多无线电场,并且我觉得我当前的方法(单独命名每个无线电场)有点乏味。我觉得必须有一种方法可以简单地选择所有这些,以确保在处理表单之前它们都已被检查。

这是我的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,然后查看是否有任何 .required 单选按钮未选中/不明确的。我觉得必须有办法让这个工作。我在正确的轨道上吗?我觉得我只是没有选择这个权利。

【问题讨论】:

标签: javascript jquery forms


【解决方案1】:

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

你可以在sn -p下测试。 这是我修改的部分:

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>

【讨论】:

  • 嗯,这似乎工作。我现在没有时间认真看这个东西。我想确保我首先完全理解这里发生了什么。但这可能只是这样做!
  • 我制作了 2 个数组,一个全部选中,一个不选中,使它们唯一并比较长度,如果它们相等,则全部都被选中
  • 好的,我看到两个变量检查​​唯一的选中和未选中按钮。我想我有点理解整个 .map() 的事情(是 return this.name 构建数组吗?)。但我不明白这两个数组应该如何匹配。最后,当它全部填写完毕时,是否选中的单选按钮应该是 2(在这种情况下)和未选中的 0?它们是如何匹配的?
  • 你首先有一个每个问题的广播列表,想象只有一个问题,名称 = 'q1' :可能有 2 个或更多响应(广播),比如 3。如果没有检查我们有checked : nullnot checked : q1 , q1 , q1 使其独一无二成为checked : null not checked : q1 现在如果我们检查我们有not checked : q1checked : q1 我们只有1 个问题所以checked.length === not_checked.length 并且一切都完成了!
  • 我在我的代码 sn-p 中添加了一些 cmets /explanation !
【解决方案2】:

您可以遍历所有具有名称属性: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>

【讨论】:

  • 只需将事件从submit 更改为input change,sn-p 就可以根据您的喜好工作。
猜你喜欢
  • 1970-01-01
  • 2023-02-21
  • 2017-07-09
  • 2012-07-18
  • 2019-12-22
  • 2015-07-18
  • 2014-01-03
  • 1970-01-01
  • 2020-05-10
相关资源
最近更新 更多