mOna
mOna

Reputation: 2459

get user country by ip and show it on top of dropdown list but NOT preselect it

I have a drop-down list in my form which preselect user's country based on his/her IP and it works fine.

Problem: This drop-down list question is required field, so if user didn't answer it, he should not be able to go to the next page. My problem is that since it is preselected in the list, even if user didn't selected it, he can go to next page.

What I need: I would like to know if it is possible to get users country by their IP, but NOT preselect it, and just simply show it on top of the list for instance before "Leave Blank" option (so user can see it easily).

This is my code:

<label> Where were you born?<span>*</span></label>
<div class="fieldset content">  
<select name="q5[]" multiple="multiple" width="200px" size="10px">

<?php
require 'vendor/autoload.php';
$gi = geoip_open('/usr/local/share/GeoIP/GeoIP.dat', GEOIP_STANDARD);
$ip = $_SERVER['REMOTE_ADDR'];
$preselect_country = geoip_country_name_by_addr($gi, $ip);

include('newCountry.php');

while ($line = mysql_fetch_array($result)) {   
    if($preselect_country == $line['country']){
       $selected = "selected";
   }else{
       $selected = "";
    }

 echo "<option value=\"{$line['country']}\" {$selected}>{$line['country']}</option>\n";
  }
    geoip_close($gi);

 ?>
</select>
</div>

I appreciate if someone can help me fix it.

Thanks,

Upvotes: 0

Views: 941

Answers (1)

i alarmed alien
i alarmed alien

Reputation: 9520

You can create your select to have a blank first value and put the user's country as the second option in the list. The other countries can go below it. To set this up using your PHP script, you can create two strings, one for the top of the list (with the blank option and the user's country), and the other with the rest of the list:

$list_top = "<option>Choose one...</option>\n";
$list_bottom = "";
while ($line = mysql_fetch_array($result)) {   
    if($preselect_country == $line['country']){
        $list_top .= "<option value=\"{$line['country']}\">{$line['country']}</option>\n";
    }else{
        $list_bottom .= "<option value=\"{$line['country']}\">{$line['country']}</option>\n";
    }
}
echo $list_top . $list_bottom;

Upvotes: 1

Related Questions