简体   繁体   English

如何使用JavaScript在HTML的下拉列表中获取每个选项的长度

[英]How can I get the length of each option in a dropdown list of HTML with JavaScript

I have this javascript function to verify the length of a phone number of a select dropdown list of HTML. 我具有此javascript函数,可以验证HTML的选择下拉列表中电话号码的长度。

<script type="text/javascript">
  function test(){

    var max_length_internet_number = 10;
    var max_length_mobilephone_number = 11;
    var total_length = 15;

    var length_telephone_prefix = document.getElementById('prefix').options.length;

    var telephone_textbox = document.getElementById('phone');
    var message = "";


    //MIGHT BE... - THIS IS ONLY A TEST

    if(length_telephone_prefix + telephone_textbox.value.length == total_length && telephone_textbox.value.length > max_length_mobilephone_number){

     message.setCustomValidity("ERROR, The length of a number of a mobile phone don't be greater than 15 digits");
     return false;
    }else{

    message.setCustomValidity('');
    return true;
    }


}
</script>

I think that the line that says: document.getElementById('prefix').options.length certainly will take the length of the option of the dropdown list that I have, but really? 我认为那行代码: document.getElementById('prefix').options.length当然会占用我拥有的下拉列表的选项的长度,但是真的吗? I think that this line will take all not each option depending on the option was selected. 我认为这行代码将根据选择的选项而不是全部使用所有选项。

This is the drop down list and the textbox. 这是下拉列表和文本框。

<select id="prefix">
  <option name="mobile" value="+234">+234</option>
  <option name="internet" value="+4388">+4388</option>
  <option name="others" value="">Other number</option>
</select>

<input type="text" id="phone" name="phone" maxlength="15"/>

Is possible to take the length of each <option></option> depending on what option was selected, using javascript, maybe taking his name or id of each option in different variables. 可以使用javascript来确定每个<option></option>的长度,具体取决于所选择的选项,或者使用不同的变量来获取每个选项的名称或ID。 And then call the function in the input. 然后在输入中调用该函数。

If you want to take the length of the selected dropdown option then you can try this: 如果要使用所选下拉选项的长度,则可以尝试以下操作:

var list = document.getElementById('prefix');
var selected_option_length = list.options[list.selectedIndex].value.length;
console.log(selected_option_length);

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

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