2014-10-03 31 views
1

我得到的形式下拉。我有两个区域在我的形式,我想,如果用户选择出现一个框“等......”在选择菜单中的JavaScript或操作不工作

我写这可能两个下拉的工作的功能,通过里面的字符串比较下拉的价值选择(其中包含“其他1”和“其它2”)与两个字符串“其他1”和“其它2”我的函数里面的选择。

$('.select-other').change(function() { 
     if($(this).find('option:selected').val() === ('other1' || 'other2')){ 
      ($(this).closest('div').next().show()); 
    } 
}); 

但似乎只测试的第一个值,无视我的比较操作...

是否有可能纠正呢?

我错过了什么吗?

+0

你申请或两个变量,other1和其他2。既然他们是字符串,你会得到真实的,那么你检查三重等于真。其他类型?为什么三重平等? – Elric 2014-10-03 20:49:01

回答

1

试试这个:

$('.select-other').change(function() { 
    var value = $(this).find('option:selected').val(); 
    if(value === 'other1' || value === 'other2'){ 
     ($(this).closest('div').next().show()); 
} 
+1

作为附录我会打电话'$(本).find(“选项:选择”)。VAL()'一次,并存储在比较前值。 – Lloyd 2014-10-03 20:47:57

+0

补充说,在张贴有点懒。 :) – Tyr 2014-10-03 20:49:16

2

不幸的是,你可以不写条件语句的方式。你必须明确。

而且我会保存所选择的选项:

var value = $(this).find('option:selected').val(); 

if (value === 'other1' || value === 'other2')) { 
0

您的条件是错误的,你不能做到这一点:

$(this).find('option:selected').val() === ('other1' || 'other2'); 

由于非空字符串将始终返回true,('other1' || 'other2')将始终返回“other1”

您需要单独检查这些值:

var value = $(this).find('option:selected').val(); 
value === 'other1' || value === 'other2' 
0

您需要的价值两个选项进行比较。你想现在要做的方式是像做$(this).find('option:selected').val() === 'other1'

你可以做2检查这样的:

$('.select-other').change(function() { 
    var currentValue = this.value; 
    if(currentValue === 'other1' || currentValue === 'other2'){ 
     ($(this).closest('div').next().show()); 
    } 
}); 

或者使用正则表达式:

$('.select-other').change(function() { 
    var currentValue = this.value; 
    if(currentValue.match(/^(other1|other2)$/)){ 
     ($(this).closest('div').next().show()); 
    } 
}); 
+0

很好的答案,非常感谢。 – user3781018 2014-10-03 20:54:41