Helo
I’m trying to setup a form that has a field that will contain a phone number
The part that’s not working is that the user is able to delete the country code while inputing phone number.
What i wan’t to do is define the phone country code via javascript based on another field containing the country.
In the form i have the following:
<?php $form = ActiveForm::begin(); ?>
<?=
$form->field($model, 'country_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Countries::find()->select(['id', 'name'])->orderBy('name')->asArray()->all(), 'id', 'name'),
'options' => ['placeholder' => Yii::t('app', 'Select a country ...')],
'pluginOptions' => [
'allowClear' => true
],
])
?>
....
<?php
if ($model->isNewRecord)
echo $form->field($model, 'office_number')->widget(MaskedInput::classname(), [
'clientOptions' => [
'alias' => 'phone',
'url' => Url::to(['/stuff/phone-codes.json']),
'countrycode' => '',
]
]);
else
echo $form->field($model, 'office_number', ['addon' => ['prepend' => ['content' => $model->country->phone_country_code]]])->widget(MaskedInput::classname(), [
'clientOptions' => [
'alias' => 'phone',
'url' => Url::to(['/stuff/phone-codes.json']),
'countrycode' => $model->country->phone_country_code,
'nojumpsThreshold' => strlen($model->country->phone_country_code)
]
]);
?>
...
<?php
$this->registerJS("
$('#" . Html::getInputId($model, "country_id") . "').on('change',function(e) {
if(e.val != ''){
$.ajax({
'url': '" . Url::to('/countries/getphonecountrycode') . "',
'data': {'id':e.val},
'success': function(data) {
json = $.parseJSON(data);
if(json.status == 'success') {
alert(json.phone_country_code);
alert(json.phone_country_code.length);
$('#" . Html::getInputId($model, "office_number") . "').val(json.phone_country_code);
$('#" . Html::getInputId($model, "office_number") . "').inputmask('phone',{
'url': '". Url::to(['/stuff/phone-codes.json'])."',
'countrycode': json.phone_country_code,
'nojumps': true,
'nojumpsThreshold': json.phone_country_code.length+1
});
$('#" . Html::getInputId($model, "fax_number") . "').val(json.phone_country_code);
$('#" . Html::getInputId($model, "fax_number") . "').inputmask({'mask': json.field_mask});
}
}
}
)};
});
");