Sagar Patra
Sagar Patra

Reputation: 51

php drop down list with "two values" for each "option" and multiple selections

I have a table with two columns: City and ZIPcode

Using HTML / PHP / MySQL

created a drop down select list with City as Label and ZIPcode as Value. Now I want to catch both City and ZIPcode of selected (using multiple selections through array[]). "explode" does not support arrays[].

Please help me how to achieve this.

Upvotes: 0

Views: 1552

Answers (1)

Schiem
Schiem

Reputation: 589

If you need to do it with just HTML and PHP (no Javascript), you could place both of them in the same select with a separator character, like so:

<option value="City,Zip">City</option>

And then process it on the server like so:

<?php
     $location_data = $_POST["location_variable"];
     $exploded = explode(",", $location_data);
     $city = $exploded[0];
     $zip  = $exploded[1];
?>

You would want to include error handling, checking to make sure that the exploded data was appropriate length, etc.

However, if you have access to javascript/jQuery, you could bind the zip or city with a data attribute and send that along as well using a new hidden data attribute.

<option value="City" data-zip="zip">City</option>

And then in Javascript:

$("form").submit(function() {
     //find our zip value
     var zip   = $(this).find(":selected").data("zip");

     //create a new hidden input named "zip"
     var input = $("<input>").attr("type", "hidden").attr("name", "zip").val(zip);

     //add it to our form
     $(this).append(input);
 });

Upvotes: 1

Related Questions