Reputation: 33
I want to clear the selected data on multiple select boxes but it won't work for me.
<select name="age" id="age" class="span2 typeahead" multiple data-rel="chosen">
<?php
$age_arr = explode(",", $result['age']);
foreach ($age as $a)
{
$select = "";
for ($is = 0; $is < count($age_arr); $is++)
{
if ($age_arr[$is] == $a['age_id'])
{
$select = "selected";
}
} ?>
<option id="age2" value="<?php echo $a['age_id']; ?>" <?php echo $select; ?>><?php echo $a['age']; ?></option>
<?php
}
?>
</select>
<input type="hidden" id="age_val" name="age_val" value="<?php echo $result['age']; ?>" />
<input type="button" value="Clear" id="clear" class="btn" onClick="clearFields()">
This is what I tried:
<Script>
function clearFields(){
document.getElementById("age_val").value = "";
document.getElementById("age").value = '';
}
</Script>
Please advice me how to clear data when clear button clicked,
Upvotes: 0
Views: 2633
Reputation: 3461
Javascript:
function clearFields(){
document.getElementById("age_val").value = "";
var collection = document.getElementById('age').getElementsByTagName('option');
for(var i = 0; i<collection.length; i++){
collection[i].selected = false;
}
// for chosen
$('#age').trigger('chosen:updated');
}
But as long as you using jquery, then you can use code in answer provided by @Rory McCrossan and add to the function: $('#age').trigger('chosen:updated');
Upvotes: 1
Reputation: 337743
As you have a multiple select, not a standard select, you need to set the selected
property of each option
element to false
. Try this:
function clearFields() {
$('#age option:selected').prop("selected", false);
$('#age_val').val('');
}
Upvotes: 2