Reputation: 1543
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
Reputation: 3106
Make sure you add your javascript code when the document is 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)'/>");
}
});
});
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.
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
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