Kishan Patel
Kishan Patel

Reputation: 509

Javascript Function for radio button other option

I've created a radio buttons for selection and there is "other" button when clicked by user it'll open text-box so that user can manually specify some text inside it.

<label><input type="radio" name="option" value="">Web</label>

<label><input type="radio" name="option" value="">Mobile Apps</label>

<label><input type="radio" name="option" value="other">Other</label>
<input typt="text" placeholder="Specify here" id="other-text">

And javascript

$(".option").change(function () {
//check if the selected option is others
if (this.value === "other") {
    //toggle textbox visibility
    $("#other-text").toggle();
}
});

This is what i've tried but somehow it's not working. I'm newbie to javascript so please help me.

Thanks in advance.

If possible can you also tell me how to put jsfiddle/codepen links?

Upvotes: 0

Views: 876

Answers (4)

Jack jdeoel
Jack jdeoel

Reputation: 4584

Set other text box display none first ! Then display text when click radio button other ...

<input typt="text" placeholder="Specify here" id="other-text" style="display:none">

<script type="text/javascript">
    $(":radio").change(function () {
        //check if the selected option is others
        $("#other-text").hide();
        if (this.value === "other") { 
              $("#other-text").show();
        }
});
</script>

Upvotes: 0

brk
brk

Reputation: 50291

You are using a class selector $(".option"). But you have not assigned any class to it. Unless you assign a class you have to use jquery input name selector to target the element

$( "input[name='option']" ).change(function(){
// $(".option").change(function () {  // if using class
if (this.value === "other") {
    $("#other-text").show();
}
else{
 $("#other-text").hide();
}
});

Check this JSFIDDLE

Upvotes: 0

Erick Boshoff
Erick Boshoff

Reputation: 1583

Try this

JAVASCRIPT

$("[name='option']").change(function () {
    //check if the selected option is others
    if (this.value === "other") {
        //toggle textbox visibility
        $("#other-text").show();
    } else {
        //toggle textbox visibility
        $("#other-text").hide();
    }
});

Upvotes: 0

Maths RkBala
Maths RkBala

Reputation: 2195

Please try this:

$(".js-option").click(function () {
//check if the selected option is others
    if ($(this).val() == "other") {
        $("#other-text").show();
    }else{
        $("#other-text").hide();
    }
});
#other-text{
  display:none;
}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<label><input type="radio" name="option" class="js-option" value="">Web</label>

<label><input type="radio" name="option" class="js-option" value="">Mobile Apps</label>

<label><input type="radio" name="option" class="js-option" value="other">Other</label>
<input typt="text" placeholder="Specify here" id="other-text">

Upvotes: 1

Related Questions