I
I
Igor2017-05-18 10:36:46
JavaScript
Igor, 2017-05-18 10:36:46

How to add an event to a form that is in js and not html?

Hello
There is a simple landing page
, you need to set a Yandex goal on button click
, the form is written using js, from which I know only alert ()

<form id="form" action="">
          <input type="text" name="name" placeholder="Ваше имя">
          <input type="text" name="tel" placeholder="Ваш номер телефона">
          <div class="form_bottom">
            Заказать звонок <!--кнопка-->
          </div>
        </form>

Do not tell me how to hang this event immediately on the div (button)?
just adding to div
onclick="yaCounterXXXXXX.reachGoal('zakazatZvonok'); return true;"
obviously it doesn’t give anything
if it’s too simple and a platinum question, then at least a direction to ask where to figure it out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Kartushin, 2017-05-18
@onedeadyankee

If you need to hang an event on any element in js, you first need to make this very element and then insert data (Markup) into it, for example:

var myBtn = '<button id="btn"> click it </button>';
var myElement = document.createElement('div');
myElement.innerHTML = myBtn ;

Then it will be possible to capture this element from js and hang events on it:
var fooBtn = myElement.getElementById('btn');
fooBtn.addEventListener('click', function(){
 alert();
})

And if you already have this form stored in memory somewhere, just refer to it as I wrote above and hang up the event. Through jquery, you can make everything even easier, if your markup is stored as a string, then you can wrap it in $ and get a ready-made jquery element, for example:myForm.querySelector('form_bottom');
Then you can hang events:
myDiv.find('button').on('click', function(){
 alert();
});

If this is some element in memory, then you can also wrap it in a tag and hang an event, for example:
var myDiv = document.createElement('div');
myDiv.append('button');
$(myDiv).on('click', function(){
 alert();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question