Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery wait until element attribute has a value

Tags:

jquery

wait

I have an element

<span id="current" data=""></span>

The value of the data attribute will be filled by an asynchronous AJAX function. I can't change this function to synchronous or have it return a value.

Here's part of the code

$("#popup #save").click(function () {

    //setting a lot of vars here

    var id = $("#current").val();

    if (id == '') {
        //new  so insert

        $.ajax({
            type: "GET",
            url: myurl,
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#loadstatus").html('');
                //returns new id
                if (data > 0) {
                    $('#current').val(data);
                }
            }
        });
    }
    else {
        //existing  so update
        //more code
    }

    return false;

});



    var id = $("#current").val();
    if (id == '') {
        //save  
        $("#popup #save").click(); //this function contains the AJAX call which also sets `$("#current").val()` with a value returned in that same AJAX call

        //I can only set the value of id after the success of the aforementioned AJAX function
        //so here I need to set some sort of timeout
        id = $("#current").val();
    }

I want to execute another function, but within that function I want to wait until the attribute data is not equal to empty. I was checking out this: http://javascriptisawesome.blogspot.com/2011/07/faster-than-jquerydocumentready-wait.html But I prefer to do this with default jQuery.

How can I do so?

like image 705
Adam Avatar asked Dec 09 '14 01:12

Adam


1 Answers

You could poll for the value of data:

function check() {
    if (!$('#current').attr('data')) {
        return setTimeout(check, 1000);
    }

    // do work here
}

check();
like image 188
neouser99 Avatar answered Sep 30 '22 19:09

neouser99