Como chamar uma função JS usando o evento OnClick

Estou a tentar ligar para a minha função JS que adicionei no cabeçalho. Por favor, Encontre abaixo o código que mostra o meu cenário de problema. Nota: Não tenho acesso ao corpo na minha aplicação. Toda vez que eu clicar no elemento com id="Save" ele só chama f1() mas não fun(). Como posso fazê-lo chamar-me de meu? Ajudar.

  <!DOCTYPE html>
  <html>
  <head>

  <script>

   document.getElementById("Save").onclick = function fun()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }   

    function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    
    }

  </script>
  </head>
  <body>
  <form name="form1" id="form1" method="post">
            State: 
            <select id="state ID">
               <option></option>
               <option value="ap">ap</option>
               <option value="bp">bp</option>
            </select>
   </form>

   <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

   </body>
   </html>
Author: Gopal Joshi, 2014-01-31

6 answers

Está a tentar anexar uma função de ouvinte de eventos antes do elemento ser carregado. Colocar fun() dentro de uma função onload ouvinte de eventos. Invocar f1() dentro desta função, dado que o atributo onclick será ignorado.

function f1() {
    alert("f1 called");
    //form validation that recalls the page showing with supplied inputs.    
}
window.onload = function() {
    document.getElementById("Save").onclick = function fun() {
        alert("hello");
        f1();
        //validation code to see State field is mandatory.  
    }
}

JSFiddle

 30
Author: George, 2014-01-31 10:42:49

Pode usar o addEventListener para adicionar quantos ouvintes quiser.

  document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 

Adicionar também script marca após o elemento para ter a certeza que Save o elemento é carregado no momento em que o programa executar

Em vez de mover a marca de script você poderia chamá-lo quando dom é carregado. Então você deve colocar o seu código dentro do

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("Save").addEventListener('click',function ()
    {
     alert("hello");
     //validation code to see State field is mandatory.  
    }  ); 
});

Exemplo

 7
Author: jonasnas, 2014-01-31 10:38:58

Removi o teu document.getElementById("Save").onclick = antes das tuas funções, porque é um evento que já está a ser chamado no teu botão. Eu também tive que chamar as duas funções separadamente pelo evento onclick.

     <!DOCTYPE html>
      <html>
      <head>
      <script>
       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   
        function f1()
        {
          alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.    
        }
      </script>
      </head>
      <body>
      <form name="form1" id="form1" method="post">
                State: 
                <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>

       <table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>

   </body>
   </html>
 2
Author: JORDANO, 2017-07-16 16:20:27

Se usar o atributo onclick ou aplicar uma função às suas propriedades JS onclick, irá apagar a sua inicialização onclick .

O que tem de fazer é Adicionar carregue em eventos no seu botão. Para isso, você precisará de métodos addEventListener e attachEvent (ie).

<!DOCTYPE html>
<html>
<head>
    <script>
        function addEvent(obj, event, func) {
            if (obj.addEventListener) {
                obj.addEventListener(event, func, false);
                return true;
            } else if (obj.attachEvent) {
                obj.attachEvent('on' + event, func);
            } else {
                var f = obj['on' + event];
                obj['on' + event] = typeof f === 'function' ? function() {
                    f();
                    func();
                } : func
            }
        }

        function f1()
        {
            alert("f1 called");
            //form validation that recalls the page showing with supplied inputs.    
        }
    </script>
</head>
<body>
    <form name="form1" id="form1" method="post">
        State: <select id="state ID">
        <option></option>
        <option value="ap">ap</option>
        <option value="bp">bp</option>
        </select>
    </form>

    <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

    <script>
        addEvent(document.getElementById('Save'), 'click', function() {
            alert('hello');
        });
    </script>
</body>
</html>
 1
Author: eltyweb, 2014-01-31 10:40:46

O código interno tem precedência maior do que os outros. Para chamar a sua outra função func () chamá-lo a partir do f1 ().

Dentro da tua função, adiciona uma linha,

function fun () {
// Your code here
}

function f1()
    {
       alert("f1 called");
       //form validation that recalls the page showing with supplied inputs.    

fun ();

    }

Reescrever todo o teu código,

 <!DOCTYPE html>
    <html>
      <head>

      <script>

       function fun()
        {
         alert("hello");
         //validation code to see State field is mandatory.  
        }   

        function f1()
        {
           alert("f1 called");
           //form validation that recalls the page showing with supplied inputs.   
           fun (); 
        }

      </script>
      </head>
      <body>
       <form name="form1" id="form1" method="post">

         State: <select id="state ID">
                   <option></option>
                   <option value="ap">ap</option>
                   <option value="bp">bp</option>
                </select>
       </form>
       <table><tr><td id="Save" onclick="f1()">click</td></tr></table>

      </body>
</html>
 0
Author: Arunkumar Srisailapathi, 2014-01-31 10:36:18
function validate() {

    if( document.myForm.phonenumber.value == "" ) {
        alert( "Please provide your phonenumber!" );
        phonenumber.focus;
        return false;
    }
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))  {  
        return (true)  
    }  
    alert("You have entered an invalid email address!");
    return (false);
}
 -4
Author: harsh, 2015-09-14 11:39:15