0

strong textI am trying to add plus and minus to input form. the input is only created in js script so it doesnt exist on DOM yet when calling the event.

I tried async function but that didn't really work (or i didn't do it right)

this is the function:

const plusFunction = async function() {

  function incrementValue(e) {
    e.preventDefault();
    const fieldName = $(e.target).data('field');
    const parent = $(e.target).closest('div');
    const currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
  
    if (!isNaN(currentVal)) {
      parent.find('input[name=' + fieldName + ']').val(currentVal + 1);
    } else {
      parent.find('input[name=' + fieldName + ']').val(0);
    }
  }
  
  function decrementValue(e) {
    e.preventDefault();
    const fieldName = $(e.target).data('field');
    const parent = $(e.target).closest('div');
    const currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
  
    if (!isNaN(currentVal) && currentVal > 0) {
      parent.find('input[name=' + fieldName + ']').val(currentVal - 1);
    } else {
      parent.find('input[name=' + fieldName + ']').val(0);
    }
  }
  

  const btnPlus = document.querySelector('.button-plus')
  btnPlus.addEventListener('click', function (e) {
    
    incrementValue(e);
  });

  const btnMinus = document.querySelector('.button-minus')
  btnMinus.addEventListener('click', function (e) {
    decrementValue(e);
  });

}

plusFunction()

it is working if the element is already on the html,

any help appreciate.

edit: I saw some solution with jquery but i need it with vanilla js

webmar
  • 7
  • 2

0 Answers0