llamar funcion eventos evento ejemplo ejecutar desde boton javascript html forms validation html-validation

javascript - funcion - Cómo llamar a una función JS utilizando el evento OnClick



llamar funcion javascript desde html onclick (6)

Al usar el atributo onclick o aplicar una función a las propiedades de JS onclick se borrará la inicialización onclick en.

Lo que debe hacer es agregar eventos de clic en su botón. Para hacer eso necesitarás métodos addEventListener y 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>

Intento llamar a mi función JS que agregué en el encabezado. Por favor, encuentre el código a continuación que muestra mi problema. Nota: no tengo acceso al cuerpo en mi aplicación. Cada vez que hago clic en el elemento con id="Save" , solo llama a f1() pero no a fun() . ¿Cómo puedo hacer que llame incluso mi fun() ? Por favor ayuda.

<!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>


El código en línea toma mayor prioridad que los otros. Para llamar a su otra función func () llámela desde f1 ().

Dentro de tu función, agrega una línea,

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

Reescribiendo todo tu 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>


Eliminé su document.getElementById("Save").onclick = antes de sus funciones, porque ya se está llamando a un evento en su botón. También tuve que llamar a las dos funciones por separado mediante el 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>


Está intentando adjuntar una función de escucha de eventos antes de que se cargue el elemento. Coloque fun() dentro de una función onload event listener. Llame a f1() dentro de esta función, ya que se ignorará el atributo onclick .

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


Puede usar addEventListener para agregar tantos oyentes como desee.

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

También agregue una etiqueta de script después del elemento para asegurarse de que el elemento Save esté cargado en el momento en que se ejecuta el script

En lugar de mover la etiqueta de secuencia de comandos, podría llamarla cuando se cargue dom. Entonces debes colocar tu código dentro del

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

example


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); }