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 <inputtype="radio"name="article"value="1"checked='checked'> 
No <inputtype="radio"name="article"value="0"><divid="send_to_yes"><b>Number</b><br><inputtype="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 <inputtype="radio"name="article"value="1"<?phpif($value == 1){ echo'checked'; } ?>> 

No <inputtype="radio"name="article"value="0"<?phpif($value == 0){ echo'checked'; } ?>><divid="send_to_yes"<?phpif($value == 0){ echo'style="display:none"'; } ?>><b>Number</b><br><inputtype="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() {

    <?phpif($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 <inputtype="radio" name="article"class='clickIt' value="1"> 
No <inputtype="radio" name="article"class='clickIt' value="0">

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