Unknown developer
Unknown developer

Reputation: 5970

JQuery val(" ") return null only in IE

Here is HTML code:

<select name="gender" id="gender">
  <option value="MAN">MAN</option>
  <option value="WOMAN">WOMAN</option>
</select>

Here is Jquery:

$("#gender").val("");

IE shows nothing in the selected list(that's what I want). Firefox and Chrome shows "MAN"! What do I have to do as to oblige Firefox and Chrome let the selected list null? Thank you

P.S. I do not want to add a blank option

Upvotes: 0

Views: 1604

Answers (5)

billyonecan
billyonecan

Reputation: 20270

You can't select an option which doesn't exist (in your case, one with no value). You could prepend an empty option, and then set the value as empty:

$('#gender').prepend('<option />').val('');

Here's a fiddle


Edit

In response to your comment, you can just make the new option hidden:

$('#gender').prepend('<option style="display: none;">Choose</option>').val('');

Fiddle

Upvotes: 3

Jai
Jai

Reputation: 74738

If you want it on pageload and onchange event then you can append the .change() event at the end:

$(function(){ //<---------this is doc ready
  $('#gender').change(function(){
     alert($(this).val());
  }).change(); //<----this will triggerred on page load.
});

Upvotes: 0

vinothini
vinothini

Reputation: 2604

Like $("#gender").val() you can get the value

The .val() method is primarily used to get the values of form element

not .val("")

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

$("#gender").val(""); will set the option with the empty value, which you don't have right now in your current HTML code.

Add an empty option like <option value=""></option> and it should work in all the browser.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

<select name="gender" id="gender">
  <option value=""></option>             <-- added a blank option
  <option value="MAN">MAN</option>
  <option value="WOMAN">WOMAN</option>
</select>

Upvotes: 0

Related Questions