【问题标题】:Set value of hidden input based on ZIP code entry根据邮政编码条目设置隐藏输入的值
【发布时间】:2021-12-24 22:03:48
【问题描述】:

我正在尝试为特定区域设置数组,然后将它们与输入的邮政编码进行比较以设置隐藏字段的值(以命名该区域)。我输入的所有内容都设置为“未找到”。我很难过,任何和所有的帮助将不胜感激。

HTML:

<input id="zip" name="ZIPCODE" type="text" />
<input id="REGION" name="REGION" type="hidden" /> 

脚本:

var eastZips = [19144, 19103, 19104];
var westZips = [90210, 90211, 90212];
        
    
$("#zip").keyup(function() {        
    if ($(this).val() == eastZips) {
        $("#REGION").val("East");
    } else if ($(this).val() == westZips) {
        $("#REGION").val("West");
    } else 
        $("#REGION").val("Not Found");
});  

【问题讨论】:

标签: javascript jquery arrays variables


【解决方案1】:

输入的值永远不会匹配eastZipswestZips,因为您正在比较不同“类型”的事物。您存储的变量是数组,输入值是字符串。

这里有几个步骤可以解决这个问题。

虽然您输入的是一组数字,但 JS 会将字段值读取为字符串,因此您必须确保处理该值以正确地与您存储的整数进行比较。这可以通过将字段值放入 parseInt

来实现

接下来您需要检查输入值是否属于任一数组,这可以通过使用 includes 来实现。

var eastZips = [19144, 19103, 19104];
var westZips = [90210, 90211, 90212];
        
    
$("#zip").keyup(function() {
  // Store input value for easier access, and wrap
  // it in a parseInt to ensure you are storing
  // an integer for comparison.
  var zip_value = parseInt( $(this).val() );

  // Check if either array stores the input value
  if ( eastZips.includes( zip_value ) ) {
    $("#REGION").val( "East" );
  } else if ( westZips.includes( zip_value ) ) {
    $("#REGION").val( "West" );
  } else {
    $("#REGION").val( "Not found" );
  }
});

【讨论】:

  • 非常感谢。特别是对于解释/学习经验。那是/远远高于我的技能水平。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
相关资源
最近更新 更多