如何在特定的jquery验证结构中验证无线电

How to validate radio in specific jquery validation structure

本文关键字:验证 结构 无线电 jquery      更新时间:2023-09-26

你好,我正在编写一个多步骤表单,并用带有<fieldset> </fieldset>标签的jquery脚本划分表单的不同部分

我的表单验证在这个脚本上运行,看起来像这个

$(".next").click(function(){
  var erros = 0;
    //error checking in the first fieldset
  if (fieldsetn == 1) {
    //verify name
      if ($('input[name="name"]').val().length ===0){
           $('input[name="name"]').attr("placeholder","Please enter your name");
              $('input[name="name"]').addClass('warning');

        erros = 1;
    }
    else {
    $('input[name="name"]').removeClass('warning');
    }
    //verify surname
    if ($('input[name="surname"]').val().length ===0){
         $('input[name="surname"]').attr("placeholder","Please enter your surname");
          $('input[name="surname"]').addClass('warning');
        erros = 1;
    }
    else {
    $('input[name="surname"]').removeClass('warning');
    }

但我在验证一个无线电场时遇到了一个问题,我的无线电场是这样的:

 Chose the Logo pack <a href="services.html"  style="float:right" target="_blank">More Information about Logo Packs Pleas click here</a> 
                        <div id="emotion" name="emotion">
    <input type="radio" name="emotion" id="basi" />
        <label for="basi"><img src="images/basi.jpg" width="630px" alt="I'm sad" /></label><br>
         <input type="radio" name="emotion" id="deli" />
        <label for="deli"><img src="images/deli.jpg" width="630px" alt="I'm sad" /></label><br>
    <input type="radio" name="emotion" id="premi" />
        <label for="premi"><img src="images/premi.jpg" width="630px" alt="I'm happy" /></label>
</div>

如何验证我在jquery验证代码结构中设置的单选字段,以便必须选择一个选项?提前感谢

试试这个-

if($('input[name="emotion"]:checked').length==0)
{
  alert("Please select radio button");
}

if(!$('input[name="emotion"]:checked').length)
{
  alert("Please select radio button");
}

演示

这将适用于

 if($('input[type="radio"][name="emotion"]').is(':checked')) 
 { 
      alert("it's checked"); 
 }else{
      alert("it's not checked"); 
 }
if($('input[name="emotion"]:checked').length==0)
{
  alert("Please select radio button");
}

这项工作对

if(!$('input[name="emotion"]:checked').length)
{
  alert("Please select radio button");
}