Home > Software design >  country code will automatically added before mobile number
country code will automatically added before mobile number

Time:10-15

If any one type in input box only number like : 01234567890 (total 13 digit with country code) then automatically add 88 before mobile number but if if anyone number with 8801234567890 it wont added before number. Another one if type 1234567890 total 10 digit then add 880 before number. how to fix it? I tried with add value but its not working. I need only my conditions not every time.

$(document).ready(function() {

    $('#phone').keyup(function() {
        let total_length = this.value.length;
        
        if(total_length='11'){
          $("#phone").val("88" $("#phone").val());
        }
        else if(total_length='10'){
          $("#phone").val("880" $("#phone").val());
        }
        else{
           $("#phone").val();
        }
    });

    $.validator.addMethod("countryValid", function(value, element) {
        return this.optional(element) || /^(?:\ 88|88)?(01[3-9]\d{8})$/i.test(value);
      }, "Please enter valid phone no."); 

  
    $("#my_form").validate({
        rules: {
        phone : {
            required: true,
            number: true,
            countryValid: true
        }
        }
    });

  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>

<form id="my_form">

<input type="text" name="phone" id="phone" />
<br><br>
<button type="submit">Submit</button>

</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Fixed it with replace keyup to change and add the ==(Equal to) from =(assignment operators)

$('#phone').change(function() {
        let total_length = this.value.length;
        
        if(total_length=='11'){
          $("#phone").val("88" $("#phone").val());
        }
        else if(total_length=='10'){
          $("#phone").val("880" $("#phone").val());
        }
        else{
           $("#phone").val();
        }
    });

Thanks @CherryDT for this help.

  • Related