On the page there are a lot of such input and all without ID

function doAdd(btn) { var c = getCookie('m_ids'); if (c) { var a = c.split(','); for (i = 0; i < a.length; i++) { if (a[i] == btn.alt) { alert(''); return false; } } a.push(btn.alt); setCookie('m_ids', a.join(','), '', '/'); } else { setCookie('m_ids', btn.alt, '', '/'); } order('cost', 'alt'); ordc(); return false; } 
 <input class="button btn js-add-to-cart" alt="^[$id]" value="Добавить в заказ" readonly="readonly" onclick="return doAdd(this)"> 

How to replace onclick="return doAdd(this)" with $('body').on('click', smth, function(e)

  • Combine the input with some common parameter, such as a class or some other attribute, such as name - yolosora
  • They have a common class. The script takes the alt of each input and adds it to the cookie. But if you call without explicit onclick right on the input line - the script does not know where to get the alt and adds an empty one. - ysmhypno
  • What is the reason for the desire to replace? Is the layout still the same? - Grundy
  • The reason is that I’ve hung up another function that works from $ ('body'). On ('click') - and if the element itself has onclick then the global one does not work. - ysmhypno

1 answer 1

Working version in accordance with the comment question about cookies.

 function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function newAdd() { console.log($(this).attr("alt")); setCookie('yourID', $(this).attr("alt"),5); } var elementList = document.querySelectorAll('input.button'); for (i = 0; i < elementList.length; i++) { elementList[i].onclick = newAdd; } 
  • Did as you wrote. The function is executed, but there is emptiness in the cookie. About this was the question of how to get the value out of alt and enter it in the cookie. Just paste my script inside newAdd - does not work. - ysmhypno
  • did not see the comment with these specifications - Pavel
  • updated the example, it is working, but in the snippet it cannot work because of the document is the sandboxed and lacks the 'allow-same-origin' flag. Therefore, the snippet removed. - Pavel
  • one
    Works great! Thank! - ysmhypno