Reputation: 557
So when I load a page I retrieve info from a DB and will check a radiobutton based on its value...
I need the textboxes to show initially - based on the radiobutton being already checked
works fine when I perform the click event, but I need to show the textboxes when the page loads because the 1st radiobutton is checked from the DB...
<p>
Show textboxes <input type="radio" name="radio1" value="Show" checked="checked">
Do nothing <input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text"><p>Textbox #1 <input type="text" name="text1" id="text1" maxlength="30"></p></div>
<div class="text"><p>Textbox #2 <input type="text" name="text2" id="text2" maxlength="30"></p></div>
Here is my FIDDLE - DEMO http://jsfiddle.net/rbla/5fq8q2bj/
here is the jquery using toggle
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function(){
$('.text').toggle(this.value === 'Show');
}).trigger('change');
});
any ideas...
Upvotes: 0
Views: 29
Reputation: 66123
The reason your solution is not working is because you are going through all your radio inputs and then toggling the element based on its value—regardless if it is checked or not. So at runtime, this is what your script does:
onchange
event, fires onchange
callback, and shows the .text
elementonchange
event, fires onchange
callback, and hides the .text
element againIf you put a console log in your callback, you will realized that the .text
element is shown and hidden in quick succession.
What you really want to do is only to perform the toggling when it is checked. Therefore, your example will work by simply enforcing a check that this.checked
is truthy before performing the toggling:
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
See working example below:
$(document).ready(function() {
$(".text").hide()
$('[name=radio1]').on('change', function() {
if (this.checked) {
$('.text').toggle(this.value === 'Show');
}
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Show textboxes
<input type="radio" name="radio1" value="Show" checked="checked"> Do nothing
<input type="radio" name="radio1" value="Nothing">
</p>
Wonderful textboxes:
<div class="text">
<p>Textbox #1
<input type="text" name="text1" id="text1" maxlength="30">
</p>
</div>
<div class="text">
<p>Textbox #2
<input type="text" name="text2" id="text2" maxlength="30">
</p>
</div>
Upvotes: 1