Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle input when checkbox is checked

I'm trying to build something like wordpress options section. When you click the checkbox you can toggle the display of the corresponding <input type="text"> field, I want to do this all in one function so I don't have tons of different functions so what would be the best way to toggle the corresponding input with the checkbox, I made a quick jsFiddle but when I use my checkbox it toggles all the inputs because I'm selecting all of them obviously, so what would be a better solution using like this or something so toggle the corresponding field, thanks in advance, http://jsfiddle.net/MEC9n/

HTML

<div class="options">
    <input type="checkbox" name="title"><label>Title</label>
    <input type="checkbox" name="author"><label>Author</label>
    <input type="checkbox" name="category"><label>Category</label>
</div>
<div class="container">
    <form method="post">
        <input type="text" name="title" placeholder="Title:">
        <input type="text" name="author" placeholder="Author:">
        <input type="text" name="category" placeholder="Category:">
        <input type="submit" value="Submit">
    </form>
</div>

jQuery

   $(document).ready(function(){
        $('input[type="checkbox"]').click(function(){
            $('input[type="text"]').toggle();
        });
    });
like image 952
Mitchell Layzell Avatar asked Oct 27 '25 17:10

Mitchell Layzell


1 Answers

This should help

Basic Solution

$(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
        var item = $(this).attr('name');
        $('input[name="'+item+'"][type="text"]').toggle();
    });
});

Fiddle

Maybe better?

If you really want to make it efficient, extend jQuery

$(document).ready(function () {
    jQuery.fn.rmCorrespondingText = function () {
        var context = $(this);
        context.bind('click', function () {
            var item = context.attr('name');
            $('input[name="' + item + '"][type="text"]').toggle();
        });
    };

    $('input[type="checkbox"]').rmCorrespondingText();
});

Fiddle

like image 57
SomeShinyObject Avatar answered Oct 30 '25 14:10

SomeShinyObject