2

I'm trying to show the phone code based on the country selected. Like when you try to register and while choosing a country the phone code changes at the same time.

here's my code.

<select class="form-control" name="country_id" required>
        <option value selected disabled>Select Country</option>
        @foreach ($countries as $country)
            <option value="{{ $country->id }}" id="shop-country">{{ $country->name }}</option>
        @endforeach
    </select>

    <div class="form-group">
        <label>Phone Number</label>
            @foreach ($countries as $country)
                <span id="phonecode">{{ $country->phonecode }}</span>
            @endforeach
    </div>
AlphaChino
  • 51
  • 2
  • 9

1 Answers1

1

First, you need to populate the select options with a custom attribute, for example, phonecode

<select id="countryList" class="form-control" name="country_id" required>    
 @foreach ($countries as $country)
    <option phonecode="{{ $country->phonecode }}" 
            value="{{ $country->id }}" 
            id="shop-country">{{ $country->name }}
   </option>
 @endforeach
</select>

Remove foreach loop from pone code text.

<div class="form-group">
  <label>Phone Number</label>
  <span id="phonecode"></span>
</div>

Now, use Javascript to listen to change events on the select list.

<script>
 let countryList = document.getElementById("countryList") //select list with id countryList
 let phoneCode = document.getElementById('phonecode') //span with id phonecode

 countryList.addEventListener('change', function(){
  phoneCode.textContent = this.options[this.selectedIndex].getAttribute("phonecode");
 });
</script>
user3532758
  • 2,221
  • 1
  • 12
  • 17