javascript - jQuery on click starts working correctly after second button click -


(fiddle: http://jsfiddle.net/qdp3j/)

i have div:

<div id="addcontactlist"></div>

i use ajax , change innerhtml like:

  <div id="<%= data[i].id %>">     <img src="<%= picture %>">     <button class="addasfriend">add friend</button>   </div> 

in js, have

$('#addcontactlist').on('click', '.addasfriend', function () {   $(this).text('request sent!');   $(this).attr('disabled','disabled'); }); 

what happens when click on button first time, see click function ran; "request sent!" being shown reverts initial button. when click second time, works fine.

i tried using event.stoppropagation , preventdefault same issue happens.

as stated, comes ajax part:

basically, have 3 input fields on page, , users can enter data in them. if there data in fields, posted , use data query database. there delay function of 250ms prevent posting every time letter typed.

var addcontactslist = document.getelementbyid('addcontactlist');  $('#addcontactform').on('keyup change', function () {   var self = this;    // add short delay not post every letter typed   delay(function() {     var usersearchdata = {};     usersearchdata.userid = 23;      $.each(['email', 'username', 'fullname'], function (_, el) {       var val = $(self).find('input[name="' + el + '"]').val();       if (val.length >= 3) {         usersearchdata[el] = val;       }     });      if ( !isempty(usersearchdata) ) {       $.post('/post/addcontact', { usersearchdata: usersearchdata }, function (data) {         if (data) {           new ejs({url: '/templates/addacontact.ejs'}).update('addcontactlist', { data: data })         } else {           addcontactslist.innerhtml = '';         }       });     } else {       addcontactslist.innerhtml = '';     }   }, 225 );  }); 

it's because of "keyup change". change being triggered again when clicking elsewhere (the add friend button).

now though problem when people use autocomplete feature using mouse, not trigger because change isn't there anymore.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -