0

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.

4

3 回答 3

4

我想你想要这样

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();
            }
    });
于 2013-09-12T08:00:50.600 回答
1

您在 document.ready 之后隐藏了第一行的字段:

$("#send_to_yes").hide();

因此,无论默认情况下是否设置了 YES,该字段都将被隐藏。如果您希望它自动显示,则需要在页面加载后触发更改事件。

您可以使用 .toggle() 函数简化隐藏/显示。您可以根据从数据库返回的单选按钮值来定义字段的初始加载。

$(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();
    });

});

稍微改变一下 HTML:

Yes <input type="radio" name="article" class='clickIt' value="1"> 
No <input type="radio" name="article" class='clickIt' value="0">
于 2013-09-12T08:03:11.613 回答
1

您可能还需要基于数据库值 check/uncheck的单选按钮和div。hide/show

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 是默认检查

于 2013-09-12T07:57:15.033 回答