hankknight
asked on
jQuery: Reset all selects but not inputs
Using jQuery, how can I reset all <select> values but not all <input> values?
In this example, all <select> values should be set to "xyz" when the button is clicked:
In this example, all <select> values should be set to "xyz" when the button is clicked:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('input').val('123');
$('select').val('0');
$('#restAllSelect').click(function() {
$('select').each(function() {
$(this).val($(this).find('option:eq(2)').val());
});
});
});
</script>
</head>
<body>
<div>
<input type="text" value="abc" />
<select>
<option value="0">0</option>
<option value="XYZ" selected="selected">XYZ</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<select>
<option value="0">0</option>
<option value="abc">abc</option>
<option value="bbb">bbb</option>
<option value="XYZ" selected="selected">XYZ</option>
</select>
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="XYZ" selected="selected">XYZ</option>
</select>
<button id="restAllSelect">Reset selects but not inputs</button>
</div>
</body>
</html>
test page : http://jsfiddle.net/FjYYy/
$(document).ready(function() {
$('input').val('123');
$('select').val('0');
$('#restAllSelect').click(function() {
$('select option[value="XYZ"]').prop('selected', true);
});
});
ASKER
Thank you both. I should have specified that the point of this question is to RESET the value. The actual values will not be XYZ. They could be anything. I want to reset the select elements to the value where the option has the attribute selected="selected".
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
to set all selects to the value "XYZ" just use this:
Open in new window
See:http://jsfiddle.net/EE_RainerJ/3avYq/
HTH
Rainer