Toggle class from dropdown menu

I'm trying to switch a class by selecting an option from the drop-down menu, I tried using alert () to check if it works, but I can't 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 problem.

+6
source share
2 answers

$('#dropdown option:selected') not a living object. Your code binds the click handler to the selected parameter when the page loads. You should either use event delegation, or better listen to the 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)); }); 
+4
source

You need:

  • Checking document.ready
  • Assign Change Event

To associate some events with DOM elements, document.ready is required to ensure that the DOM element is created at the time the event is mapped.

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> 
+3
source

Source: https://habr.com/ru/post/988982/


All Articles