Newbie to Node.js here:
What is an easy way to make dynamic dropdowns in node.js?
Basically, I have two tables: Skill
and Skill_Category>
So one dropdown will cause the other to show. Unless the second dropdown has hundreds of options you won't want to make a separate server side request to get it in. This means your logic should all be in the browser/client side.
This means you want your "Skill_Category" select box to have a JS function called to hide the current "Skill" select box and show the newly chosen "Skill" select box. They will all be rendered in html by your templating, but only one will ever be shown (display:block
) while the others are hidden (display:none
).
Sample HTML:
Sample Jquery code:
$('#skill_category').on('change',function(){
$('.skill').hide()
$('#'+this.value).show()
});
If you have a large list of options for the secondary select box then you can make an ajax (HTTP GET) request, and returning the lsit of dropdowns from your server as JSON. You will probably have one of two scenarios: all of you skills in a static JSON file, or saved in a database.
Your node code will look like:
app.get('/skill_category/:skill', function(req, res){
//JSON file in the /public/skills directory
res.sendFile(__dirname + '/public/skills/'+req.params.skill+".json");
//or some database lookup followed by a json send:
var skills = someDatabaseLookup();
res.json(skills);
});
HTML
while the jquery will now be:
$('#skill_category').on('change',function(){
$.get('skill_category/'+this.value,function(data){
for(var j = 0; j < length; j++)
{
$('#skill').contents().remove();
var newOption = $('');
newOption.attr('text', data[j].text);
newOption.attr('value', data[j].value);
$('#skill').append(newOption);
}
});
});
Do note this code is untested but should work