Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class from dropdown menu

I try to toggle a class by selecting a option in the dropdown menu, i've tried using a alert() to check if it works but i cant seem to get it to work.

HTML:

<html>
<body>
    <select id="dropdown">
        <option value="1">Steinkjer</option>
        <option value="2">Verdal</option>
    </select>
</body>
</html>

Javascript:

$('#dropdown option:selected').click(function(){
    var getText = $('#dropdown option').text();
    alert($('.overlay-'+getText));
});

Please help me solve this issue.

like image 587
Bin4ry Avatar asked Jun 12 '15 07:06

Bin4ry


People also ask

How do I toggle a drop down menu?

dropdown class indicates a dropdown menu. To open the dropdown menu, use a button or a link with a class of . dropdown-toggle and the data-toggle="dropdown" attribute.

What is dropdown toggle?

Dropdowns are toggleable, contextual overlays for displaying lists of links and more. They're made interactive with the included Bootstrap dropdown JavaScript plugin. They're toggled by clicking, not by hovering; this is an intentional design decision.

How do I change the position of a drop down menu in Bootstrap?

Use data-offset or data-reference to change the location of the dropdown.


2 Answers

$('#dropdown option:selected') is not a live object. Your code binds the click handler to the selected option on page load. You should either use event delegation or better listen to change event of the select element.

$('#dropdown').on('change', function() {
    // Get text content of the selected option
    var getText = $('option:selected', this).text();
    // Get current value of the select element
    // var getValue = this.value;
    console.log(getText);
    console.log($('.overlay-'+getText));
});
like image 175
undefined Avatar answered Oct 20 '22 01:10

undefined


You need to:

  • Check document.ready is executed
  • Assign the change event

To bind some events to DOM elements, requires a document.ready, to ensure the DOM element is sure created at the time you associate the event.

  • A page can't be manipulated safely until the document is "ready.": https://learn.jquery.com/using-jquery-core/document-ready/

Check this snippet:

$(document).ready(function() {

  $('#dropdown').change(function() {
    var getText = $('#dropdown option:selected').html();
    $("#test").removeClass();
    $("#test").toggleClass("overlay-" + getText);
  });



});
.overlay-Steinkjer {
  background-color: red;
}
.overlay-Verdal {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <select id="dropdown">
    <option value="1">Steinkjer</option>
    <option value="2">Verdal</option>
  </select>

  <p id="test">test paragraph</p>
</body>

</html>
like image 35
Alejandro Teixeira Muñoz Avatar answered Oct 20 '22 00:10

Alejandro Teixeira Muñoz