简体   繁体   English

jQuery if 多个 .val 下拉值的条件

[英]jQuery if condition for multiple .val dropdown values

I'm appending data to an input field depending on a drop down selection, what would be the cleanest way to do this as I have around 25 to do, at the moment I have it working like this:我根据下拉选择将数据附加到输入字段,最干净的方法是什么,因为我有大约 25 个要做,目前我让它像这样工作:

$('#dropdown').change(function() {
  if($(this).val() == 10){
    ('#number').val('108-0<?php echo $number; ?>');
  }
});

Several drop down options share the same appended number so I don't want to duplicate code, I am aware I can do something like:几个下拉选项共享相同的附加编号,因此我不想重复代码,我知道我可以执行以下操作:

$('#dropdown').change(function() {
  if($(this).val() == 10||
     $(this).val() == 11||
     $(this).val() == 12){
    $('#number').val('108-0<?php echo $number; ?>');
}

But even this seems like too much, what would you do?但即使这看起来也太过分了,你会怎么做?

Check to see if an array of the possible values include the .val() :检查可能值的数组是否包含.val()

$('#dropdown').change(function() {
  if ([10, 11, 12].includes(Number($(this).val()))) {
    $('#number').val('108-0<?php echo $number; ?>');
  }
});

No need for a big library like jQuery for something this trivial:不需要像 jQuery 这样的大库来处理这种微不足道的事情:

const [dropdown, number] = ['dropdown', 'number'].map(id => document.getElementById(id));
dropdown.addEventListener('change', () => {
  if ([10, 11, 12].includes(Number(dropdown.value))) {
    number.value = '108-0<?php echo $number; ?>';
  }
});

If you need to check multiple arrays of values, extract it into a variable first:如果需要检查多个值数组,请先将其提取到变量中:

$('#dropdown').change(function() {
  const val = Number($(this).val());
  if ([10, 11, 12].includes(val)) {
    $('#number').val('108-0<?php echo $number; ?>');
  } else if ([1, 5, 15].includes(val)) {
    $('#number').val(5000);
  }
});

An array is the best way if the values don't have a pattern, but for your example, it's better to use:如果值没有模式,数组是最好的方法,但对于您的示例,最好使用:

$('#dropdown').change(function() {
  var val = parseInt($(this).val());
  if(val >= 10 && val <= 12){
    $('#number').val('108-0<?php echo $number; ?>');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM