Giancarlo
Giancarlo

Reputation: 399

php drop downlist with 2 values the 2nd value post to hidden field

I've got a regular drop downlist for selecting the countries name as text and countries_id as value. Example:

<option value="1">Afghanistan</option>

Now I need an hidden form field with the ISO2 code for the country. Example:

<input type="hidden" name="iso2" id="inputIso2" class="form-control">

And when the country is changed by the drop downlist, the hidden field should also change. I've added the ISO2 to the option like this:

<option value="1" data-iso2="AF">Afghanistan</option>

But how do I pass it to the hidden field? Or is there a better way of doing this?

The ISO2 field is being used by another script in the form, so it should work pre post.

Upvotes: 0

Views: 31

Answers (1)

Difster
Difster

Reputation: 3270

This isn't really a PHP problem so much as it is a javascript problem. You need to put an event listener on your select element and when it changes, grab data-iso2 and apply the value to the hidden field.

Using jQuery, you'd do this:

$("#country").change(function(){
   var iso2 = $(this).find(':selected').data('iso2');
   $("#inputIso2").val(iso2);

});

Upvotes: 1

Related Questions