JQuery $ .each variable

Problem with scope problem with $.each in jQuery . How can I get a global variable in a function to be set in a loop, or at least pass something from it?

 var some_function = function() { // false by default var something = false; $.each(array, function(key, val) { if (val == 'something') { // even if one item evaluates true I need to check outside of the loop something = true; } }); if (something == true) { // do something else, but always false } } 

Since I need to evaluate all the elements in the array, and if only one is true , then do something extra, outside of $.each .

Update

 $(document).ready(function () { something(); $(':radio').trigger('change'); )}; 

Ok, so this is the actual code. He warns β€œfalse” below, and then warns β€œhello” twice, as if he is going in the reverse order.

 var something = function() { var q_radios = { 'radio1' : 'radio1_selector', 'radio2' : 'radio2_selector', }; var show_me = false; $.each(q_radios, function(name, q_selector) { $('input:radio[name=' + q_selector + ']').change(function() { show_me = true; alert('hello'); }); }); if (show_me == true) { alert('yes'); } else { alert('false'); } }; 
+7
source share
2 answers

More or less, exactly what you have now ... you just need to pass the data to the function (allowing you to accept the argument). See a live example .

 var some_function = function(array) { // false by default var something = false; $.each(array, function(key, val) { if (val == 'something') { something = true; } }); if (something == true) { alert("There was a something"); } else { alert("There wasn't a something"); } }; some_function([1,2,3]); some_function([1,"something",3]);​ 
+5
source

I recommend native array iteration methods:

 var something = array.some(function ( val ) { return val === 'something'; }); 

Here, something will be true if at least one element of the array has the value 'something' .

+2
source

All Articles