I currently have many languages for an Airports project I'm working on.
-Currently you can select whatever language you would like from the drop-down menu and it will appear in the list. Working fine. Can delete them too.
-The goal: once a language has been added to the list, you should not be able to add it again. For example, you can hit the 'Add Languages' for French and add it as many times as you want. This goes for any language.
The current js code for adding a language:
function addLanguage()
{
var languages = $("#languages_dd").val();
language_display = languages.split("-");
alert(languages);
var units = $("#units_dd").val();
var unit_display = $("#units_dd :selected").text();
$(".none_class").hide();
$("#error_msg").html("");
$("#summary").append("<li><input type='radio' name='language_item'> <span class='route_summary_field_big'>"+language_display[0]+"</span>"+unit_display+"<input type='hidden' name='languages[]' value='"+languages+"'><input type='hidden' name='units[]' value='"+units+"'></li>");
}
I'm not too familiar with javascript and have been searching around online. I know it's going to be a conditional, something along the lines of:
if($("#languages_dd :selected")
{
//do something;
}
else if
//do something else;
}
Any input is appreciated to steer me in the right direction.
You can keep the selected languages in an array. Then before you append to the html, check whether the value already exists:
var selected_lang = new Array();
function addLanguage() {
//your code here..
if (!$.inArray(language_display, selected_lang)) {
selected_lang.push(language_display)
// rest of your code to append html
}
}
This is the solution I came up with (feel free to offer constructive criticism):
function addLanguage()
{
var languages = $("#languages_dd").val();
language_display = languages.split("-");
var units = $("#units_dd").val();
var unit_display = $("#units_dd :selected").text();
$(".none_class").hide();
var shouldAdd = "YES";
$("#summary li").each(function(){
var matches = 0;
$(this).find('input:hidden').each(function(){
var stringVal= $(this).val();
console.log(stringVal);
if(stringVal.indexOf(languages) != -1){
matches++;
}
if(stringVal.indexOf(units) != -1){
matches++;
}
});
if(matches == 2){
shouldAdd = "NO";
}
});
if(shouldAdd == "YES") {
$("#summary").append("<li><input type='radio' name='language_item'> <span class='route_summary_field_big'>"+language_display[0]+"</span>"+unit_display+"<input type='hidden' name='languages[]' value='"+languages+"'><input type='hidden' name='units[]' value='"+units+"'></li>");
}
$("#error_msg").html("");
}