Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear selected option in IE with javascript or jQuery

Imagine this HTML code

<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function clear_form() {
  $("select#block_id").find("option").removeAttr("selected");
}
</script>
</head>
<body>
<form>
<select id="block_id" name="block_id">
<option value=""></option>
<option value="1">1 Peach Road</option>
<option value="2" selected="selected">Bethnal Green Estate</option>
<option value="3">Ley Street</option>
<option value="4">Ogilby Street</option>
</select>
<input type="reset" onclick="clear_form()" value="Clear"/>
<input type="submit"/>
</form>
</html>

When you open this page in Firefox pressing a Clear button will reset selected option. But this doesn't work in IE, browser will not raise any errors but do nothing selected option still shown. Problem is because we have 'option value="2" selected="selected"' html code and looks like IE won't clear this selection it always appear on page. It will be great to get native javascript or jQuery 1.5.2 solution. Any suggestions?

like image 468
Serge Janssen Avatar asked Apr 30 '26 14:04

Serge Janssen


1 Answers

You could use JavaScript to reset the select to point to its first option element.

With jQuery...

$('#block_id').prop('selectedIndex', 0);

Without...

document.getElementById('block_id').selectedIndex = 0;
like image 196
alex Avatar answered May 02 '26 03:05

alex