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.
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.
Share Improve this question edited Jun 12, 2015 at 8:21 Prasanna 7795 silver badges13 bronze badges asked Jun 12, 2015 at 7:55 Bin4ryBin4ry 674 bronze badges 2- ("#dropdown option:selected").text(); – Bugfixer Commented Jun 12, 2015 at 8:00
- possible duplicate of jQuery toggle div from select option – Bugfixer Commented Jun 12, 2015 at 8:03
2 Answers
Reset to default 4$('#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));
});
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./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./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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745122556a4612498.html
评论列表(0条)