Reputation: 74
I been working a script that will check if the new input 'value/string' is already exist, but so far I cant find the correct/efficient solution.
<input type="text" class="existingKeywords" value="string1, string2, string3">
<input type="text" class="newKeyword" value="">
the value of .newKeyword will defend on user input and once submit button is click, it will check if the newKeyword.val() already exist from .existingKeywords.val(); separated by ','
I tried but returns 'json parse unexpected character'
var arr = JSON.parse("[" + $('.existingKeywords').val() + "]");
var newKey = $('.newKeyword').val();
if( jQuery.inArray (newKey, arr) ){
alert('Found!');
}
Can someone tell me, why its not working or Is there a better approach than this?
Thanks!
Thank you so much guys, the script is now perfectly working. I want to 'Vote Up' everyone's answer but it requires 15 Reputation, and as of this writing I only have 13 reputation. And again gracias everyone.
Upvotes: 1
Views: 90
Reputation: 2664
Maybe you could use the good old String.split()
?
Something like this:
var arr = $('.existingKeywords').val().split(',');
var newKey = $('.newKeyword').val();
if( jQuery.inArray(newKey, arr) != -1 ){
alert('Found!');
}
Upvotes: 1
Reputation: 4463
This will check for case-insensitive duplicate values as well and please try getting values of input with ID instead of class it is safer...
var array = $('.existingKeywords').val().split(',');
var new_array =[] ;
for(var key in array)
new_array.push(array[key].toLowerCase());
var newkeyword = $('.newKeyword').val().toLowerCase();
if( $.inArray (newkeyword , new_array)!== -1 ){
//found your value
}
Upvotes: 1
Reputation: 626
It is not working because this line:
var arr = JSON.parse("[" + $('.existingKeywords').val() + "]");
interprets this way:
var arr = JSON.parse("[string1, string2, string3]");
which is not a correct JSON - strings inside shall be in quotes, otherwise JSON.Parse
doesn't know what is string1
.
As other suggested you need to use split
here instead, I'd like to add only trimming the leading/trailing spaces:
var arr = $('.existingKeywords').val().split(',').map(function(s) { return s.trim();})
var newKey = $('.newKeyword').val().trim();
if( $.inArray (newKey, arr) != -1 ){
alert('Found!');
}
But why don't you use select
with multiple choises? It is more convenient that type keywords I think.
Upvotes: 1
Reputation: 715
var arr = $('.existingKeywords').val().split(',');
var newKey = $('.newKeyword').val();
if( $.inArray (newKey, arr) ){
alert('Found!');
}
Upvotes: 1