Custom event to detect change of value in data tag

381 Views Asked by At

I have a div with a form in it that has a data tag that i have named data-av

I am appending the div as follows

> $("#desti_div").append("<div class='tmar"+count+"'><div
> class='form-group col-md-6 getspace'><label><i class='gicon fas
> fa-circle'></i> New Destination</label><input class='form-control
> input-lg form-field very_form' type='text' id='added_dest"+count+"'
> data-av='' name='added_dest' placeholder='New Destinaton' required><a
> href='' class='gored'><span
> class='form-control-feedback'></span>Delete</a></div><br/></div>");

I would like to fire an event every time the value of data-av changes. The id of the input that has the data-av has the id id='added_dest"+count+"' as shown in the code above so i should target the input with that id.

I am thinking of this

$('#someID').data("key", "newValue").trigger('changeData'); 

$('#someID').on('changeData', function (e) {    
    alert('My Custom Event - Change Data Called! for ' + this.id);
});

How can i watch if newValue changes so that i am able to show the custom event.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use Attribute selectors. Also trigger the event after defining the changeData event handler function:

$("#desti_div").append(`<div class='tmar"+count+"'><div
 class='form-group col-md-6 getspace'><label><i class='gicon fas
 fa-circle'></i> New Destination</label><input class='form-control
 input-lg form-field very_form' type='text' id='added_dest"+count+"'
 data-av='' name='added_dest' placeholder='New Destinaton' required><a
 href='' class='gored'><span
 class='form-control-feedback'></span>Delete</a></div><br/></div>`);

$('[data-av]').on('changeData', function (e) {    
    alert('My Custom Event - Change Data Called! for ' + this.id);
});
$('[data-av]').data("av", "newValue").trigger('changeData'); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="desti_div"></div>