Search code examples
jquerycloneadditionappendto

create more divs that shows textboxes after option selected with jquery


i have scientific articles that i want to record. each article has mutliple references (up to 100), and a reference might be a book or an article. if a reference is a book, i have get author name of the book, page number of the book etc. if it is an article, then i have to get published journal of the article, published year of the article etc.(there are differences).

so, i want to let user select if it is an article or a book from a dropdown menu first. then related textboxes will be visible. user fills related information and reference 1 is OK. then he will press add button to add another reference,so what he sees first will be dropdown menu first, he selects an option, and related textboxes appear.. here is what i have,

html:

<div id="content">    
<select id="select">
                <option value="">-chooese-</option>
                <option value="article">article</option>
                <option value="book">book</option>
    </select>

    <input class="article" name="ref_author_name[]"  type="text" id="ref_author_name" />
    <input class="article" name="ref_article_title[]"type="text" id="ref_article_title" />    
    <input class="book"    name="ref_author_name[]"  type="text" id="ref_author_name" />
    <input class="book"    name="ref_thesis_title[]" type="text" id="ref_thesis_title" />
    <input class="button-a" type="button" value="add"/>
</div>

jQuery

$(function() {
        $('#select').change(function() {
            $("input").hide().filter("." + $(this).find("option:selected").val()).show();
            $(":button").show();
        });
        $(":button").click(function(){
            $('#content').clone().add('#content').appendTo(document.body);
        });
    });

now what happens is, when i select book (1st reference), related textboxes appear, if i change the option to book, book related textboxes appear. there is no problem with first select box.

but, when i press add button, new dropdown menu shows (2nd reference), and i select an option, related textboxes appear again. BUT, the thing is all of the selection changes, including first choices..

i am very new to jQuery and i guess there might be a tiny problem, but i can not locate.. any help is deeply appreciated..


Solution

  • I made this Fiddle for you: http://jsfiddle.net/MXXXT/16/

    Basically, what I do, is create a template for each option, and clone it, then show it (as the template is hidden by default, see the CSS).

    Hope this helps.

    Edited: Fiddle updated