Getting value from select box with jquery

162 Views Asked by At

Im trying to get the value thats in a select box and change the input of another field frontend

as you can see the mask is _- in the zip code input

If i choose Portugal i want my mask to be like 9999-999 and if its another country to be empty or other format

this is the code

if ($("input[name='postcode']").length) {
            $("input[name='postcode']").inputmask({"mask": "9999-999"});
        } else if ($("input=[name='postcode']").length && $("option=[value='PT']")) {
            $("input[name='postcode']").inputmask({"mask": "99999-99999"});
        }

How can i achieve that?

PS: im doing this on Magento

This is the select code

<select class="select" data-bind="
attr: {
    name: inputName,
    id: uid,
    disabled: disabled,
    'aria-describedby': getDescriptionId(),
    'aria-required': required,
    'aria-invalid': error() ? true : 'false',
    placeholder: placeholder
},
hasFocus: focused,
optgroup: options,
value: value,
optionsCaption: caption,
optionsValue: 'value',
optionsText: 'label',
optionsAfterRender: function(option, item) {
    if (item && item.disabled) {
        ko.applyBindingsToNode(option, {attr: {disabled: true}}, item);
    }
}"name="country_id" id="CV73BUT" aria-required="true" aria-invalid="false">

and this is the Postal code

<input class="input-text" type="text" data-bind="
value: value,
valueUpdate: 'keyup',
hasFocus: focused,
attr: {
    name: inputName,
    placeholder: placeholder,
    'aria-describedby': getDescriptionId(),
    'aria-required': required,
    'aria-invalid': error() ? true : 'false',
    id: uid,
    disabled: disabled

}" name="postcode" aria-required="true" aria-invalid="false" id="J5KT615">

the ids of select and input are always changing after refresh

1

There are 1 best solutions below

3
Alexis Garcia On

You can do something like this. See example below

$('#countrys').change(function(){
    var country = $('#countrys').find(':selected').attr('data-countryCode');
    if (country == 'pt')
    {
      $('#zipcode').val('999-999');
    }else{
      $('#zipcode').val('n/a');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="countrys">
  <option data-countryCode="fr">france</option>
  <option data-countryCode="it">Italy<option>
  <option data-countryCode="pt">Portugal</option>
  <option data-countryCode="sp">Spain</option>
</select>

<input id="zipcode">