簡體   English   中英

如何根據從下拉菜單中選擇的選項設置不同的輸入字段模式?

[英]How can I set different pattern of input field based on the option selected from the dropdown menu?

我正在創建一個具有用於選擇區域的下拉菜單的表單。 並且,下一個字段是該區域中特定區域的代碼。 並且特定區域的代碼模式因地區而異。

例如

亞洲-AAAA0000歐洲-AAAAA000澳大利亞-000AAA

對於aisa區域,每個特定區域的代碼將包含4個字母字符和4個數字。 與歐洲特定區域的代碼相同,將包含5個字母字符和3個數字。

我如何使用javascript或jquery驗證特定區域的輸入模式。

<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  <select id="region">
  <option value="asia">Asia</option>
  <option value="europe">Europe</option>
  <option value="australia">Australia</option>
  </select><br>
  Area:<br>
  <input type="text" name="area", id="area">
</form>

$('#region').change(function () {
 var ele = document.getElementById("region");

 if (ele.value == "Asia"){
    document.getElementById('area').pattern = '\d{4}[a-z]{4}';
 }
 else if (ele.value == "Europe"){
 }
 else if (ele.value == "Australia"){
 }

});

任何提示將不勝感激。

您可以在javascript中使用RegEx匹配來查找在字段區域中輸入的值是否匹配。

`    $('#region').change(function () {
          var ele = document.getElementById("region");
          var AsiaRegex = RegExp('^([A-Z]{4}[0-9]{4})$','g');
          var EuropeRegex = RegExp('^([A-Z]{5}[0-9]{3})$','g');
          var hasMatched = false;
          if (ele.value == "asia"){
             var code = document.getElementById('area').value;
             hasMatched = AsiaRegex.test(code);
             //console.log(hasMatched)
          }
          else if (ele.value == "Europe"){
            var code = document.getElementById('area').value;
            hasMatched = AsiaRegex.test(code);
            //console.log(hasMatched)
          }
       })`

^ [AZ] {n}-匹配大寫字母的前n個字符[0-9] {n}-匹配n個數字字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM