0

I have select with country code

<select name="countryCode" id="">
    <option data-countryCode="GB" value="44" Selected>UK (+44)</option>
    <option data-countryCode="US" value="1">USA (+1)</option>
    <optgroup label="Other countries">
        <option data-countryCode="DZ" value="213">Algeria (+213)</option>
        <option data-countryCode="AD" value="376">Andorra (+376)</option>
    </optgroup>
</select>

On next field i have enter your phone

 <input type="text" placeholder="Enter your mobile phone" data="required" id="phone" data-content='Your mobile phone'>

What i need is when user select country code to append phone input like this If user select Algeria (+213), and when he click on input phone, to append his value like this +213, and then allow him to enter the futher number.

0

2 Answers 2

2

Use the following code:

$(function() {
    $('#phone').on('focusin', function() {
        var cc = $('select[name=countryCode]').val().replace(/^.*\(([\)]+)\).*$/,'$1');
        $(this).val( cc ).data('cc', cc);
    })
    .on('focusout',function() {
        if( this.value == $(this).data('cc') )
            $(this).val('');
        }
    });
});

OR:

$(function() {
    $('select[name=countryCode]').on('change', function() {
        var cc = this.value.replace(/^.*\(([\)]+)\).*$/,'$1');
        $('#phone').val( cc )..data('cc', cc);
    });
    $('#phone').on('focusout',function() {
        if( this.value == $(this).data('cc') )
            $(this).val('');
        }
    }); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

This works great txanks man, is it possible if user does not enter number, to remove that value when he moves mouse from input #phone. If value of pnone is same as value of select remove value from phone on mouse out?
0

As above code will set value in phone number but you need to set focus also as updated below

$('select').change(function(){
        $('#phone').val( $(this).val() );
        $('#phone').focus();
    });

this will help you focus on the field also on change

1 Comment

Need to perpend the "+" symbol to val()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.