Reputation: 1573
I'm trying to show hide an select element on on/off of a checkbox. But its not working.
On page load I want the select to be hidden and on checking the checkbox I want it to be visible.
The code is
<input type="checkbox" id="inputBasicOff" checked />
<select id="fieldSelect" data-placeholder="Choose Field">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
And the JS is
(function(document, window, $) {
'use strict';
var Site = window.Site;
$(document).ready(function() {
Site.run();
$('#fieldSelect').hide();
$("#inputBasicOff").change(function() {
if(this.checked) {
$('#fieldSelect').fadeIn();
}
else{
$('#fieldSelect').hide();
}
});
});
})(document, window, jQuery);
Upvotes: 1
Views: 70
Reputation: 25527
You can do like this way,
$("#inputBasicOff").change(function () {
this.checked ? $("#fieldSelect").fadeIn() : $("#fieldSelect").fadeOut()
});
The problem with your code is, you are trying to select the element with attribute (name)selector. Currently there is no name attribute present on that element.
Upvotes: 3
Reputation: 32162
hi now try to this way
$(document).ready(function(){
$('#inputBasicOff').on('change', function(){
$('#fieldSelect').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" id="inputBasicOff" checked />
<select id="fieldSelect" data-placeholder="Choose Field">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Upvotes: 0
Reputation: 337560
Your hide()
call appears to be on a completely different element. If you select the right element your code should work. That said, you can improve it by using toggle()
:
(function (document, window, $) {
'use strict';
var Site = window.Site;
$(document).ready(function () {
Site.run();
$('#fieldSelect').hide();
$("#inputBasicOff").change(function () {
$('#fieldSelect').toggle(this.checked);
});
});
})(document, window, jQuery);
Note that the fiddle has the references to Site
commented out - I assume this is a method/property you have defined yourself, as it is not standard.
Upvotes: 0