Como chamar uma função JS usando o evento OnClick
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>
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
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.
} );
});
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>
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>
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>
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);
}