scabiati
scabiati

Reputation: 33

Reset selected attribut of select option

I know that it's a mainstream question but i already search a lot and i didn't found any answer for this. I just need to reset my fields.

So I have a php class (classMenu.php) who geneate an html form for my main page. To get last selected options, i past $_POST as argument when i call my classMenu.php like this :

mainPage.php

new menu("mainPage.php", $_POST);

classMenu.php

<select class="selectpicker" id="eventType" title="Event Type" name="eventType" data-width="150px" data-live-search="true" data-actions-box="true">
    <option value="workshop" 
<?php 
    $this->isSelected("eventType", "workshop") 
?>
    >Workshop</option>
    <option value="master" <?php $this->isSelected("eventType", "master") ?>>Master</option>
    <option value="webinar" <?php $this->isSelected("eventType", "webinar") ?>>Webinar</option>
  </select>

And here is my isSelected function ($setValues = $_POST parameter):

private function isSelected($field, $value){
if(isset($this->setValues[$field]) && $this->setValues[$field] == $value){
  echo "selected";
  }
}

I already tried those options for my javascript code :

function resetSelect() {
  $('#eventType').prop('selectedIndex', 0);
};

function resetSelect() {
  document.getElementById('eventType')[0].selectedIndex = 0;
};

function resetSelect() {
  $("#eventType").val('');
};

function resetSelect() {
  $('select').each(function(){
    $(this).find('option:selected').prop('selected', false);
  });
};

function resetSelect() {
  $('select').each(function(){
    $(this).find('option:selected').removeAttr('selected');
  });
};

I hope that my question is clear for you.

Thanks

Upvotes: 3

Views: 299

Answers (3)

Uğur &#199;akmak
Uğur &#199;akmak

Reputation: 1

This code is working for me. $('.multiselect-ui option').prop('selected', false).trigger('chosen:updated');

Upvotes: -1

Baldr&#225;ni
Baldr&#225;ni

Reputation: 5640

As I see it I would use :

$('option:selected').removeAttr('selected');

If you have multiple select then :

$('.selectpicker').each(function(){
    $(this).find('option:selected').removeAttr('selected');
});
$('.selectpicker').prop('selectedIndex', 0);
$('.selectpicker').selectpicker('refresh');

You could use as well

$('option:selected').prop('selected', false)

Upvotes: 1

Calos
Calos

Reputation: 1942

jQuery: Prop selectedIndex to 0:

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

If use javascript:

document.getElementsById('eventType')[0].selectedIndex = 0

Upvotes: 1

Related Questions