Imran Khan
Imran Khan

Reputation: 2401

JQuery Check for DIV contents change

I want to check a DIV contents, when contents of div change so i will find that there exist a form field or not. I am trying with this code but it not responding:

$.fn.exists = function(){return this.length>0;}
$("div.provider_name").live("change",function(){
    if ($('input[id=checkout_provider_checkout_moneyorder]').exists)
    {
        alert('Input field exist');
    }
});

The input fields display dynamicaly, so that's why i wnat to check if this specific field exist.

Upvotes: 2

Views: 16785

Answers (1)

Fenton
Fenton

Reputation: 250882

The change event is not available on all elements - so it will not fire even if the contents of a div element changes.

The change event is available on form elements.

It looks like your need is to work out when a particular form element becomes available, you could check for that using an interval:

var checkForInputTimer;
var checkForInput = function () {
    if ($("#checkout_provider_checkout_moneyorder").length > 0) {
        window.clearInterval(checkForInputTimer);
        alert("Do your processing here");
    }
};

checkForInputTimer = window.setInterval(checkForInput, 2000);

In this example I am just checking for the element by id, which is the most efficient search given that ids must be unique.

You could also create a custom event, but you will have to remember to trigger the event in whatever code you are using to update the div element. I have created a JS Fiddle for this:

$('div.provider_name').bind('contentChanged', function(event, data) {
    if ($('#checkout_provider_checkout_moneyorder').length > 0) {
        alert('Do your processing here');
    }
});

And wherever you update the div, you trigger this event:

$('div.provider_name').html('<input type="text" name="example" id="checkout_provider_checkout_moneyorder" value="example">')
    .triggerHandler('contentChanged');

Upvotes: 3

Related Questions