kalaba2003
kalaba2003

Reputation: 1229

<option selected="selected"> text </option> returns always a value despite having no value

My problem is option value which is
<option selected="selected" disabled="disabled">Select a city...</option>
The problem is : despite this option having no value, php code sees its value as * 'Select a city'*. So, my code if(isset($_POST['city']) returns always true even a city is not choosed. How can I solve this?

Here is html code :

<form id="city_form">

  <select id="city" name="city">
    <option selected="selected" disabled="disabled">Select a city...</option>
    <option value=1 name="city1">City 1</option>
    <option value=2 name="city2">City 2</option>
    <option value=3 name="city3">City 3</option>
    <option value=4 name="city4">City 4</option>
  </select>

  <input type="submit" value="Submit form" id="submit_button" />

</form>
<div id="show_city"></div>

Here is jquery codes :

$('#submit_button').click(function(e) {
  e.preventDefault();
  var data = $('#city_form').serialize();
  $.post(
         "fetch_city.php",
          data,
          function (response) {
             $('#show_city').html(response);
          }
        );
});

Here is fetch_city.php :

if (isset($_POST['city']) && !empty($_POST['city'])) {

  $city_id = $_POST['city']);
  echo $city_id;

} else {
  echo "You did not select a city...!";
}

Upvotes: 0

Views: 5154

Answers (2)

David Bolton
David Bolton

Reputation: 168

I think the answer here is jquery ignores the disabled on the first option. Try removing both the selected="selected" and disabled="disabled" from this. You'll now see a blank first entry. When the form is submitted your isset should return false.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You can't. Give it a meaningful sentinel value and ignore the control if that value comes up.

<option selected="selected" disabled="disabled" value="">Select a city...</option>

Upvotes: 4

Related Questions