IGGt
IGGt

Reputation: 2769

jQuery- Detect change in the content of a SPAN field

I have the below piece of code which is used to simulate a text box:

<label for="alertCmpVal">ALERT VALUE:</label>
<span class="center textBox displayField highlight" id="alertCmpVal" contenteditable> <?php print $alert_val;?> </span>

I need to know when the content changes, e.g. I click on it, and change it from 0 to 1.

I tried:

$(document).ready(function() 
{
    $(document.body).on('change','#alertCmpVal',function()
    {   
        alert("boo");
        $('#alertCmpVal').removeClass('highlight');
    })
}

but this doesn't seem to work.

(n.b. $(document.body) is used because on my main page, the initial field is loaded dynamically)

I'm guessing it is the 'change' that it doesn't like, but can't see what to replace it with. (jQuery / HTML5 is fine, as it is only used internally).

I've seen a few examples, but they generally seem to be for more complex scenarios, requiring multiple functions to detect the change when certain other things occur, but I figure there must be a simpler solution similar to the on change method.

Upvotes: 13

Views: 29646

Answers (2)

Ankit Kathiriya
Ankit Kathiriya

Reputation: 1231

i think this code will help you.

$(document).ready( function() {
    $('#myId').bind( "contentchange", function(){
        alert("Changed");
    });

    $( "#btn" ).click( function () {
        $('#myId').html( "Value" ).trigger( "contentchange" );
    });
});

http://jsfiddle.net/RKLmA/192/

Upvotes: -7

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You can use this event DOMSubtreeModified:

$("span").on('DOMSubtreeModified', function () {
  alert("Span HTML is now " + $(this).html());
});

Snippet

$(function () {
  $("a").click(function () {
    $("span").html("Hello, World!");
  });
  $("body").on('DOMSubtreeModified', "span", function () {
    alert("Span HTML is now " + $(this).html());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span>Hello</span>
<a href="#">Click</a>

Upvotes: 41

Related Questions