I have the following code:
<script>
$('#advert').live('change', function () {
if ($(this).is(':checked')) {
$(":text").show();
} else {
$(":text").hide();
}
});
</script>
This code shows and hides text fields when the checkbox is checked. It works perfectly but I want the text field to be hidden when the page opens.
I have the following code:
<script>
$('#advert').live('change', function () {
if ($(this).is(':checked')) {
$(":text").show();
} else {
$(":text").hide();
}
});
</script>
This code shows and hides text fields when the checkbox is checked. It works perfectly but I want the text field to be hidden when the page opens.
Share Improve this question edited Mar 21, 2013 at 20:12 JSuar 21.1k4 gold badges43 silver badges85 bronze badges asked Mar 21, 2013 at 20:09 JérémyJérémy 4051 gold badge4 silver badges22 bronze badges 2- 1 multiple ways.. add text { display: none} css. or hide it when the document loads. $(function(){ $(':text').hide(); }); – Sujesh Arukil Commented Mar 21, 2013 at 20:12
-
You can use .toggle() and pass in the condition -
$(':text').toggle(this.checked)
to shorten your code – wirey00 Commented Mar 21, 2013 at 20:33
4 Answers
Reset to default 5Hide the text fields on document ready.
The document ready event, says "When I'm finished loading, execute this code". So on page load it fires .hide() on your text fields. It's very powerful!
$(document).ready( function () {
$(":text").hide();
});
Another approach is to set the style to "display: none;" on each of these. Then they start out hidden
<script>
$(function() {
$('#advert').live('change', function(){
if($(this).is(':checked')){
$(":text").show();
} else {
$(":text").hide();
}
}).trigger('change');
});
</script>
This will also handle the case when the user clicks the box, goes to another page, clicks the back button, and has the box checked by the browser automatically.
give your text fields a class of maybe .text and then use css like so:
.text{
display: none;
}
or jquery like so:
$(document).ready( function () {
$(":text").hide();
});
Exchange
.show();
and
.hide();