2

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.

Imran Khan
  • 2,373
  • 2
  • 22
  • 35

1 Answers1

3

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');
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • sorry, can you explain it a bit more... can we apply find event there!! – Imran Khan Apr 10 '13 at 07:05
  • It alerts the msg on page load..... but actually there is no field exist in page source. – Imran Khan Apr 10 '13 at 07:09
  • `exists` is a method not a property. – Ram Apr 10 '13 at 07:15
  • 1
    I have updated my example to avoid using `exists` - example running on JS Fiddle: http://jsfiddle.net/6m95k/ – Fenton Apr 10 '13 at 07:19
  • Thanks Steve, Its working but a problem.... we can't assume time limit to 2000. It may take 10 minutes or 30 minutes..mean we need a logic (like live) that when ever its happend the method execute... – Imran Khan Apr 10 '13 at 07:26
  • 1
    The interval will keep firing every 2 seconds forever (or until the element exists). But I have added an additional way to do this using custom events too. – Fenton Apr 10 '13 at 07:30