-1

I am submitting a form using ajax. What I have done so far is that I have got all checked checkbox (with same name). I am using $.each() function to iterate through them But I need it to be synchronized.

jQuery.each(jQuery("input[name='checkboxes_name']:checked"), function(){
        if (jQuery(this).val()=='some_val') { // processing goes here}
if (jQuery(this).val()=='some_val2') { // processing goes here}
}

Whats happening now is that it enter IF statement when condition is met, starts processing it and moves on to next iteration of EACH function (previous one is still in progress). That way it starts executing multiple IF statement simutaneously. What I need to do is Next iteration does not start until processing is done for previous iteration.

I hope you guys understand.

Nauman
  • 118
  • 1
  • 13
  • 2
    Javascript is single threaded, so unless you have something asynchronous going on, it already does what you want – adeneo Feb 04 '15 at 20:37
  • Have you tried it??? – A. Wolff Feb 04 '15 at 20:40
  • If you are worried about conflicts, you could use an [`IIFE`](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) like `(function($){ /* your code */ })(jQuery)` to avoid having to type `jQuery` each time. – SeinopSys Feb 04 '15 at 20:41
  • I believe he's saying that in his processing it's making an async call that he needs to wait for before continuing with the process –  Feb 04 '15 at 20:42
  • Could you instead post a relevant minimalistic sample which replicate your issue? – A. Wolff Feb 04 '15 at 20:43
  • Yes I have logged the responses. And its running simultaneously. I need it to finish processing IF statement first and then move to next iteration of "each" function. – Nauman Feb 04 '15 at 20:44
  • `And its running simultaneously` That's not possible! I guess you mean on same loop iteration, but again, unless you change value in first `if` to `some_val2`, that's still not possible. If ya, then use `if/else if` – A. Wolff Feb 04 '15 at 20:47
  • 1
    I know how to do it if you wait for my response – johnny 5 Feb 04 '15 at 20:53

2 Answers2

1

Although it is not required, I advise you to use an IIFE in this case to avoid having to write jQuery every time if you cannot use $ for whatever reason.

What you want to achieve is not possible with .each() alone, you can, however, use recursive function calls to get the desired result.

Also, repeatedly getting the element's value on each check while also using jQuery to do so adds a lot of unnecessary waiting time. Getting the value from this.value is faster, more straight-forward and is generally better.

Taking into consideration that you're only checking for one variable's value, you can use a switch statement instead of the chained ifs.

(function(jQ){
    var $checked = jQ("input[name='checkboxes_name']:checked"), i = 0;
    function nextIteration(){
        i++;
        var elem = $checked.get(i);
        switch (elem.value){
            case "some_val":
                // your processing goes here, e.g.
                jQ.post('/save',{val:this.value},function(){
                    // If finished, call nextIteration(), optionally with return
                    return nextIteration();
                });
            break;
            case "some_val":
                // your processing goes here, e.g.
                jQ.post('/save',{val:elem.value},function(){
                    // If finished, call nextIteration(), optionally with return
                    return nextIteration();
                });
            break;
        }
    }

    nextIteration();
})(jQuery)
Community
  • 1
  • 1
SeinopSys
  • 8,787
  • 10
  • 62
  • 110
  • I've hard time to understand the purpose of it, could you explain a pratical use case where this could be useful? A jsFiddle maybe?! – A. Wolff Feb 04 '15 at 21:07
  • @A.Wolff If you had a form with 10 check boxes, representing specific types of e-mail notifications that you can choose to receive or not, this code could go through each check box and send a `POST` request to the server that handles the subscription preference change, then moves on to the next check box and so on. That's the best example I could come up with, but it can generally be used on any dynamically saved form that requires AJAX requests to be fired in a specific order. – SeinopSys Feb 04 '15 at 21:11
  • Looks like overcomplicated when you could use onchange event of checkboxes to send relevant POST request. Anyway, i'm not sure this is relevant to posted question, OP didn't ask about any ajax request. – A. Wolff Feb 04 '15 at 21:21
  • @A.Wolff The OP is clearly doing something non-asynchronous that doesn't make his code pause while it's happening and I've chosen AJAX requests to demonstrate it since it's the simplest non-async thing I can imagine off the top of my head. – SeinopSys Feb 04 '15 at 21:23
  • @DJDavid98 Ya maybe. But as OP doesn't give any feedback, it is quite hard to figure it out. I guess whatever he was doing, he was checking it wrongly – A. Wolff Feb 04 '15 at 21:32
  • @DJDavid98, Yes you understood my problem correctly. I am checking value of checkbox and ont basis of that sending ajax request for furthe processing and when done, move to next checkbox value. Sorry for late reply, I was trying to make you code work for me. Thanks for your help. – Nauman Feb 04 '15 at 21:46
  • @nomi416 You should really consider to use onchange event of checkboxes, whatever you are trying to do... – A. Wolff Feb 04 '15 at 21:50
  • @A.Wolff nopes. its a form. and all the fun starts when user submits it. – Nauman Feb 04 '15 at 21:52
  • long story short, user checks some or all the checkboxes, submits it, get the value of every checked checkbox(one by one), process through csv against that value(its a timeconsuming process), save it to db and move on to next checkbox. – Nauman Feb 04 '15 at 21:56
  • @nomi416 Wait, 1 hour before you tell it is regarding a FORM submit. I guess you'd really have better to ask a new question. Are you submiting FORM using ajax? – A. Wolff Feb 04 '15 at 21:59
  • @A.Wolff yes i am submitting a form using ajax. Sorry i did not understand you. what u were trying to say say in your last comment. – Nauman Feb 04 '15 at 22:14
  • @nomi416 Sorry, i meant you should ask a new question or edit this one including all your relevant code and maybe providing a sample as a jsFiddle to replicate your issue. Because honestly, actually, this doesn't make much sense – A. Wolff Feb 04 '15 at 22:18
  • @A.Wolff You are not getting the point. its quiet simple actually. I have a form containing checkboxes. User checks few or all of them and submit the form(I am using ajax for this). I have to get the values of checkboxes, and run specific functions against each of the values. BUT ONE BY ONE. when the function has finished working then move on to next value of checkbox and call its function and so on. – Nauman Feb 05 '15 at 06:13
-1

Have you trie to use javascript for loop instead of jquery each function?

var _this = jQuery("input[name='checkboxes_name']:checked");
var count = _this.length;
for(var i = 0; i < count; i++){
    if (_this.val()=='some_val') { 
        // processing goes here
    } else if (_this.val()=='some_val2') { 
        // processing goes here
    }
}
Yerko Palma
  • 12,041
  • 5
  • 33
  • 57