Reputation: 800
I have a JS that shows a test field if "1" is selected from a radio button. And hides if "0" is selected. It's working while the text field is hidden from the beginning but not if I want the text field to be visible as default if the value is "1" from the database.
JS
$(document).ready(function() {
$("#send_to_yes").hide();
$("input:radio[name=\'article\']").change(function() {
if(this.value == \'1\' && this.checked){
$("#send_to_yes").show();
}
else {
$("#send_to_yes").hide();
}
});
});
HTML
Yes <input type="radio" name="article" value="1">
No <input type="radio" name="article" value="0">
<div id="send_to_yes">
<b>Number</b> <br><input type="text" name="number"><br><br>
</div>
CSS
#send_to_yes {
display: none;
}
The "1" and "0" comes from a database. With this code I need to press "Yes" and then the text field comes up. Even if "Yes" is checked I need to press it. I want it to be visible if "1" (Yes) is checked as default.
Upvotes: 0
Views: 4678
Reputation: 1294
You are hiding the field with the first line after the document.ready:
$("#send_to_yes").hide();
So no matter if the YES is set by default the field will be hidden. You would need to fire off the change event, after the page loads, if you want it to automatically display.
You could simplify the hide/show by using the .toggle() function. And you could define the initial load of the field based on the value returned from the DB for the radio buttons.
$(document).ready(function() {
<?php
if($radioValueFromDb == 1) {
echo <<<JAVASCRIPT
$("#send_to_yes").show();
JAVASCRIPT;
} else {
echo <<<JAVASCRIPT
$("#send_to_yes").hide();
JAVASCRIPT;
}
?>
$('.clickIt').bind('click', function(){
$("#send_to_yes").toggle();
});
});
Changing the HTML a bit:
Yes <input type="radio" name="article" class='clickIt' value="1">
No <input type="radio" name="article" class='clickIt' value="0">
Upvotes: 1
Reputation: 6131
I think you want like this
Html
Yes <input type="radio" name="article" value="1" checked='checked'>
No <input type="radio" name="article" value="0">
<div id="send_to_yes">
<b>Number</b> <br><input type="text" name="number"><br><br>
</div>
Js
$("input[type=radio]").change(function() {
if($(this).prop('value') == '1'){
$("#send_to_yes").show();
}
else {
$("#send_to_yes").hide();
}
});
Upvotes: 4
Reputation: 9646
You probably need to check/uncheck
the radio button and hide/show
the div based on the database value as well.
Yes <input type="radio" name="article" value="1" <?php if($value == 1){ echo 'checked'; } ?>>
No <input type="radio" name="article" value="0" <?php if($value == 0){ echo 'checked'; } ?>>
<div id="send_to_yes" <?php if($value == 0){ echo 'style="display:none"'; } ?>>
<b>Number</b> <br><input type="text" name="number"><br><br>
</div>
FIDDLE WITH YES CHECKED BY DEFAULT
Upvotes: 1