admin管理员组

文章数量:1399887

Imagine this HTML code

<html>
<head>
<script src=".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?

Imagine this HTML code

<html>
<head>
<script src="http://code.jquery./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?

Share Improve this question asked Feb 9, 2012 at 22:39 Serge JanssenSerge Janssen 712 silver badges5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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;

Seems like Reset button is reason why it is restoring the value in IE.

A reset button resets all form fields to their initial values

In your case option 2 was initially selected and so the value is retained.

  1. Change the button type to button instead of reset
  2. Change the clear function as in Alex post.

    document.getElementById('block_id').selectedIndex = 0;
    

本文标签: Clear selected option in IE with javascript or jQueryStack Overflow