I have the following code, which for some reason does not execute the function "verifyResponse()" when clicking the input that has an onclick placed that would execute the function.
Function:
<script language="javascript">
function comprobarRespuesta(respuestaUsuario){
if(respuestaUsuario==<?php echo $_SESSION['respuestaLetra'];?>)
alert("¡Correcto!")
else
alert("¡Incorrecto!")
}
</script>
Which should be called by clicking on:
<div class="custom-control custom-checkbox mb-0">
<input type="checkbox" class="custom-control-input" id="customCheck1" name="example1" onclick="comprobarRespuesta(a)">
<label class="custom-control-label" for="customCheck1"><?php echo $_SESSION['aRespuesta'];?></label>
</div>
Thanks in advance!
If it will be executing the function for you, the only thing it does not know is the parameter that you pass to it.
In other words, when you call the function ,
comprobarRespuesta(a)
it does not know how to interpret what that isa
, because when you go without quotes, it interprets that it is a variable.To fix that, add quotes to what you pass to the function.
comprobarRespuesta('a')
.Everything would be like this:
It doesn't work because the parameter
a
you pass in the call doesn't exist.If for example you want to pass the
name
delcheckbox
, you have to pass the parameterthis.name
.Or, if you want to pass a reference to the entire element, you pass
this
.Recommendation
In any case, it is not recommended to put the calling functions in the HTML code since you would be writing a code that is too dependent for future developments. That is, if something needs to be changed, you would have to dig through all the HTML files looking to see where the functions are to make that change. The two previous examples are a clear example. Suppose you initially pass only the
name
and then are told that the is also requiredid
, you're going to have to explore all the HTML to modify it.In this example, we free the checkboxes from their attribute
onchange
in the HTML, and listen from Javascript. If changes need to be made, we don't need to edit the HTML, we just do it at the Javascript level.Also, this function can be assigned to elements grouped by
name
, byclass
, etc.