Skip to content Skip to sidebar Skip to footer

JS: Show/hide Text Field Depending On Radio Button Issue

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

Solution 1:

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

Solution 2:

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


Solution 3:

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">

Post a Comment for "JS: Show/hide Text Field Depending On Radio Button Issue"