0

Can someone please explain why the droppable is not accepting a correct value if I use the jQuery each method on the array. It works fine if I use a normal JavaScript for loop with identical code.

So I don't understand, why it is not working with the jQuery each method?

fiddle and code below.
http://jsfiddle.net/BuGA9/

$(function() {
var answer = ["apple", "tree"];
$("p.sen").draggable({revert: 'invalid'});
$("#dropBox").droppable({
    accept: function(element){
        $word = element.text().trim();


        for (var index in answer) {
           if($word === answer[index] || rem($word) === answer[index] )  { 
            return true;
            } 
        }
        /*

        $(answer).each(function(index) {
            if($word === answer[index] || rem($word) === answer[index] )  {
            return true;
            } 
        });  
        */

    },
    drop: function(event, ui) {
        $( this )    
            .addClass("correct")
            .find( "p" )
                .html("Correct well done!!!!");   
   }
});
});

function rem(sentence) {
sentence = sentence.substring(0, sentence.length - 1);
return sentence;
}

Thanks.

2 Answers 2

1

The return in the each returns the value from the iteration function, and not your accept function. You must create a variable outside the scope and set it in order to return it later.

var isCorrect = false;            
 $(answer).each(function(index) {
 if($word === answer[index] || rem($word) === answer[index] )  {
   isCorrect = true;
   return false;
 } 
});  
return isCorrect;

Also, I suggest you use native JavaScript loops when you can - the jQuery each is usually a bit slower.

http://jsperf.com/for-vs-foreach/37

1
  • Thanks for the explanation and the code example. And I was unaware of native JavaScript for loops being faster, so thanks for that tip also. Oct 9, 2013 at 6:44
0

as per JQuery documentation

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

1
  • Thanks for the link to the documentation, your snippet did explain the reason why it was not working, thanks. Oct 9, 2013 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.