jQuery,尝试根据所选内容验证一个字段或另一个字段 [英] jQuery,trying to validate one field or the other based upon what is chosen

查看:133
本文介绍了jQuery,尝试根据所选内容验证一个字段或另一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图设置一个表单,用户必须从选择中选择一个选项或在输入中输入一个值。一个必须要求,但不是两个。我试图写一个if else语句

Im trying to set up a form where a user has to pick an option from a select or enter a value in an input. One must be required but not both. I was attempting to write an if else statement

如果状态被选中然后删除省上的类,如果省填充然后删除状态上的类

if the state is selected then remove the class on province, if province is filled then remove class on state

$("#state").bind('change' , function() {
     if ( $(this).is(':selected') ) {
          $(this).parents('.foreign').removeClass("required");
      }  
      else{
      $(#province).is(':filled');
      $(this).parents('.usa').removeClass("required");
          }  
});

但我知道这不是怎么做的。希望有人能够了解我正在尝试的内容。提前致谢!基本上你可以选择这个或那个但不是两个。

But I know this is not how to do it. Hopefully someone gets the idea of what I am trying. thanks in advance! Basically you can pick this or that but not both.

推荐答案

在我的脑海中,试试这个:

Off the top of my head, try this:

<select id="state_province">
   <option value="state">State</option>
   <option value="province">Province</option>





$('#state_province').bind('change', function() {
   if($('option:selected', this).val() == 'state') {
      $('option[value=state]', this).show().addClass("required");
      $('option[value=province]', this).hide().removeClass("required");
   } else {
      $('option[value=province]', this).show().addClass("required");
      $('option[value=state]', this).hide().removeClass("required");
   }
});

根据您的评论进行编辑:

Edit based on your comment:

啊,所以你想要这样的东西:(抱歉,我是从记忆中做到的,所以可能会有调整)

Ah, so you want something like: (sorry, I'm doing this from memory, so there may be tweaks)

<select id="state" class="state_province">
...
</select>

<input type="text" id="province" class="state_province" />

===

$('.state_province').bind('change', function() {
   var jThis = $(this);
   if ( jThis.is('select:selected') ) { // state selected
      jThis.addClass("required");
      $('input.state_province').removeClass("required");
      $(this).parents('.usa').addClass("required");
   }
   if ( jThis.is('input:filled') ) { // province filled
      jThis.addClass("required");
      $('select.state_province').removeClass("required");
      $(this).parents('.usa').removeClass("required");
   }
});

这篇关于jQuery,尝试根据所选内容验证一个字段或另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆