简体   繁体   中英

Custom event to detect change of value in data tag

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM