1

Идея:

window.onload = function() {
  var forms = document.getElementsByClassName('ajax_form');
  console.log(forms);
  var forms = Array.prototype.slice.call(forms, 0);
  forms.forEach(function(i, item, array) {
    item.onsubmit = function() {
      alert(i);
      // start ajax from here
      // by getting attributes from form.ajax_form
    }
  });
  
}
<form class='ajax_form' url='/ajax/somewhere/' method='post'>
  <input name='test' send='1'>
  <input type='submit' value='send'>
</form>
<form class='ajax_form' url='/ajax/somewhere/' method='post'>
  <input name='test' send='1'>
</form>

onsubmit ничего не происходит. Предположение в том, что я преобразовал коллекцию html к массиву. Если это так то просьба показать как правильно (и красиво) перебрать коллекцию. Ответы просьба исключительно на чистом javascript

2 ответа 2

1

У Вас перепутан порядок параметров в обработчике forEach:

window.onload = function() {
  var forms = document.getElementsByClassName('ajax_form');
  console.log(forms);
  var forms = Array.prototype.slice.call(forms, 0);
  forms.forEach(function(item, i, array) {
    item.onsubmit = function() {
      alert(i);
      // start ajax from here
      // by getting attributes from form.ajax_form
    }
  });
  
}
<form class='ajax_form' url='/ajax/somewhere/' method='post'>
  <input name='test' send='1'>
  <input type='submit' value='send'>
</form>
<form class='ajax_form' url='/ajax/somewhere/' method='post'>
  <input name='test' send='1'>
</form>

0
0

window.onload = function() {
  var forms = document.getElementsByClassName('ajax_form');
  console.log(forms);
  for (i = 0; i < forms.length; i++) {
    forms[i].onsubmit = function() {
      alert(this.getAttribute('url'));
      // start ajax from here
      // by getting attributes from form.ajax_form
    }
  };

}
<form class='ajax_form'  url='/ajax/somewhere/' method='post'>
  <input name='test' send='1'>
  <input type='submit' value='send'>
</form>
<form class='ajax_form' url='/ajax/som2ewhere/' method='post'>
  <input name='test' send='1'>
  
  <input type='submit' value='send2'>
</form>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.