简体   繁体   中英

Form Validation Jquery object

I am trying to format the phone number field based on the country .The logic works fine when the user fill in the details but does not work when the country is changed and filled in again. Ex: Filled in the form for Germany and then without reloading the page if try change county to US and fill in phone "+" is being added even though format for it is different.

$(document).ready(function($){

$('#country').on('change', function() {


      if ( this.value == 'US' || this.value == 'CA')
      {


      $('#C_BusPhone')



    .keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;

        $phone = $(this);

            if (key !== 8 && key !== 9) {
            if ($phone.val().length === 4) {
                $phone.val($phone.val() + ')');
            }
            if ($phone.val().length === 5) {
                $phone.val($phone.val() + ' ');
            }           
            if ($phone.val().length === 9) {
                $phone.val($phone.val() + '-');
            }
        }


        return (key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105)); 
    })

    .bind('focus click', function () {
        $phone = $(this);

        if ($phone.val().length === 0) {
            $phone.val('(');
        }
        else {
            var val = $phone.val();
            $phone.val('').val(val); 
        }
    })

    .blur(function () {
        $phone = $(this);

        if ($phone.val() === '(') {
            $phone.val('');
        }
    });

      }
      else
      {
        $('#C_BusPhone')

    .keydown(function (e) {
      if ($(this).val().indexOf("+") === -1) {
      $(this).val("+" + $this.val());
    }
      })

}  

    });  
    }); 

Not sure if this was the cause for your error, but this line needs to get corrected from

  $(this).val("+" + $this.val());

to this

$(this).val("+" + $(this).val());

It was a fast catch, just use your browser javascript console for debugging.

See the updated fiddle here . You might want to add the starting parenthesis to your international prefix as well.

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