Reputation: 155
I'm trying to improve on some javaScript I wrote to push elements into an array if they were not previously in the array. Then, I want that array displayed in a selection field. I had this all working in javascript but thought it would be an interesting exercise for myself to try doing the same thing in jQuery. I think I'm close but for some reason, the console in my browser gives me an error as follows:
"[Error] SyntaxError: Cannot use the keyword 'var' as a variable name. (anonymous function)"
Here is my code so far. I've included (in this order) my attempt at the jQuery and then my working javascript code (commented out), as well as my function updating the drop list. I'll eventually attempt to recreate that function in jQuery as well. Can anyone tell me why I'm getting this error and or what I'm doing wrong in my jQuery? Thank you.
var clientArray = [];
var clientInput = document.getElementById("newClt");
var sel = document.getElementById("cltList");
$("#addCltBtn").click(function(){
var found = $.inArray(clientInput, clientArray) > -1;
if(found >= 0) {
//Element was found update errorMessage div
$(errorMessage).html("This Client Already Exists");
} else{
clientArray.push(clientInput.value);
}
});
//
// document.getElementById("addCltBtn").onclick=function(){
//
// console.log(clientArray.length);
// if (!contains(clientArray,clientInput.value)) {
// clientArray.push(clientInput.value);
// console.log("Objects: " + clientArray.join(", "));
// updateDropList(clientInput.value);
// }
// else alert("You already have a client by that name!");
// }
function updateDropList(value){
var opt = document.createElement('option');
opt.innerHTML = value;
opt.value = value;
sel.appendChild(opt);
}
function contains(a, obj){
for(var i =0; i< a.length; i++){
if(a[i] === obj){
return true;
}
}
return false;
}
Upvotes: 2
Views: 1032
Reputation: 487
var found = $.inArray(clientInput, clientArray) > -1;
Why are you placing a comparison in this statement? This is what is throwing your error. You check if found is greater than or equal to 0 elsewhere, so removing the > -1 should make everything work.
Upvotes: 4