Answering How to check if value exist in jQuery .data() function
(Please no downvotes on the validity of adding a bunch of data values to a form object, not my decision)
I created a jsfiddle using each
which gives
Object {v1: "value11", v2: "value2", v3: "value3", v4: "value4", v5: "value5"} fiddle.jshell.net:25
Uncaught TypeError: Object #<Object> has no method 'each'
NOTE: If I wrap the object in $(..) it does not work either
SOLVED USING $.each jsfiddle using $.each
$(function() {
$("form[name=update]").data("values", {"v1": "value11", "v2": "value2", "v3": "value3", "v4": "value4", "v5": "value5"});
$(".but").on("click",function(e) {
var $fData = $("form[name=update]").data("values");
var val = $(this).val();
console.log($fData);
$fData.each(function(n,i) {
console.log("!!!",n,i)
if (n[i]===val) {
alert("duplicate value");
return false;
}
})
e.preventDefault()
});
});
and
jsfiddle using grep which fails completely at the task.
$(function() {
$("form[name=update]").data("values", {"v1": "value11", "v2": "value2", "v3": "value3", "v4": "value4", "v5": "value5"});
$(".but").on("click",function() {
var $fData = $("form[name=update]").data("values");
var val = $(this).val();
var idx = $.grep($fData, function(n,i) {
console.log("n",n); // why no console output for this???
return n[i]===val;
});
console.log(idx);
if (idx!=-1) {
alert("duplicate value")
}
});
});
Questions:
- why can’t I run
eachon the returned object - what is up with the
grepI am doing (only used grep once before) - why is there no console output from inside the
grep
$.eachis only available to jQuery objects, so you need to wrap your object:Or pass it to
$.each:As for
$.grep(), the problem is that your input is an object, not an array.$.grepsort of silently fails on you: