Reputation: 2506
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.
Upvotes: 0
Views: 751
Reputation: 24648
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('');
}
});
});
Upvotes: 2
Reputation: 1587
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
Upvotes: 0