mario
mario

Reputation: 1543

Using Jquery to Dynamically Add Text Field

Hello I'm trying to add text fields that correspond to a user's selection in a select input. Ideally if a user selects the option with value "created_at" a text input field should be created inside the div "search_input_div" which is, at first, just an empty div.

*************Edit - Something I forgot to mention **********

The "search_column_select" select is created by another button. So it doesn't exist when the page is loaded, I'm not sure if how/if this affects the functionality.

*************End of Edit*****

For some reason nothing happens why I use the following code:

JS

 $('#search_column_select').change(function(){
        if($("#search_column_select").val() == 'created_at'){
            $('#search_input_div').html("<input class='search_input' placeholder='(YYYY-MM-DD) or (YYYY-MM)'/>");
        }
    });

And just in case it matters here is the HTML:

HTML:

<div class="search_box" id="search_column_div">
    <select id='search_column_select'>
<option value='select'>search by...</option>
<option value='created_at'>by date created</option>
<option value='street_address'>by street address</option>
</select>
</div>
        <div id="search_input_div">
            <!-- Search_input text field goes here -->
        </div>

If anyone can point out where I went wrong or how to fix this I'd greatly appreciate it! Thanks!

Upvotes: 0

Views: 102

Answers (2)

Andrei
Andrei

Reputation: 3106

Make sure you add your javascript code when the document is ready

http://jsfiddle.net/4Jt5q/1/

$(function(){ 
    $('#search_column_select').change(function(){
        if($("#search_column_select").val() == 'created_at'){
            $('#search_input_div').html("<input class='search_input' placeholder='(YYYY-MM-DD) or (YYYY-MM)'/>");
        }
    });
});

What this does is to wrap the jQuery event addition into a $(function(){...}); so now, when your document is ready and search_column_select exists, your javascript will be triggered.

Update

Since it is created dynamically you have to either add the change listener after it is created or use event delegation like this:

$(document).on('change', '#search_column_select', function(){
    if($("#search_column_select").val() == 'created_at'){
        $('#search_input_div').html("<input class='search_input' placeholder='(YYYY-MM-DD) or (YYYY-MM)'/>");
    }
});

Instead of document you can also add the direct parent of the '#search_column_select'.

Upvotes: 1

Oliver Schaub
Oliver Schaub

Reputation: 71

You have to put the jQuery into a document-ready function:

$( document ).ready(function() {
    $('#search_column_select').change(function(){
        if($("#search_column_select").val() == 'created_at'){
            $('#search_input_div').html("<input class='search_input' placeholder='(YYYY-MM-DD) or (YYYY-MM)'/>");
        }
    });
});

Upvotes: 1

Related Questions