简体   繁体   中英

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.

<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? 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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