Using two functions on the same OnClick

0

I have two JavaScript functions that are triggered by the same button, one that is responsible for validations and another that pushes the page forward.

I can not add these functions or change the page progress, since it is done by the company's own framework, I can only manipulate the validation function.

The problem is that even inserting return null into the validation function, the forward page function is triggered, that is, the form is validated but the page progresses anyway.

For reasons of confidentiality I can not show the code, but I hope the situation is clear.

So if I have the following situation:

onClick="functionValidacao(); functionAvancarPagina();"

How to "undo" functionAvancarPagina() if functionValidacao() points errors?

    
asked by anonymous 05.12.2018 / 18:07

2 answers

3

Create the two functions, after that within the validation function, you do a validation (IF), if all is correct, you fire the forward function. Hope this helps !

function validar(){
    if(camposValidadosCorretamente == true){ // se a validação está correta
        this.irParaProximaPagina(); // chama função e vai para a próxima página
    }
}

function irParaProximaPagina(){
    ...
}
    
05.12.2018 / 18:13
2

You can intercept the click event before it hits the button, run the tests you need, and decide whether to let the event get to the button or not.

In order to do this you will need to understand how events are propagating through the DOM, has a more detailed explanation, complete but a summary would be:

  • The user clicks the
  • Event click propagates from window to button . (Capture Phase)
  • The event arrives at button . (Target Phase)
  • The event "bubbles" back to window . (Bubbling Phase)
  • Maybe it's easier to understand with the image below:

    Thatsaid,youcouldheartheclickeventintheparentofthebuttonintheCapturePhaseandchoosewhetherornottoallowtheeventtopropagatetobutton.

    Todothis,simplyusethemethod Element.addEventListener() with the parameter useCapture as true for the handler to run in Capture Phase.

    btnParent.addEventListener('click', meuHandler, true);
    

    Inside meuHandler you can prevent the event from reaching the button using the Event.stopPropagation() .

    Here is an example of the concepts explained:

    var btn = document.getElementById('btn')
    var check = document.getElementById('check')
    var wrapper = document.getElementById('wrapper')
    
    btn.addEventListener('click', function () {
      console.log('-> Esta função sai da página!')
    })
    
    wrapper.addEventListener('click', function(event) {
      if (check.checked) {
        console.log('Evento de click cancelado...')
        event.stopPropagation()
      }
    }, true)
    <span id="wrapper">
      <button id="btn">Click</button>
    </span>
    
    <label>
      <input id="check" type="checkbox"> Cancelar envio
    </label>
        
    05.12.2018 / 19:32