I need to pass a parameter to a JS function but:
when executing this code, it calls the function before clicking and also does not pass the parameter
/*Este es el codigo AJAX al que quiero agregarle el parametro*/
$('#atribute').on('click',comprobar("hola"))
function comprobar(parametro){
alert("Este parametro es: ",parametro);
}
<!--***Este es el input***-->
<input id="atribute" type="text" title="Precio">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
">
</script>
In your case, you have the function execution syntax wrong and you are also not concatenating correctly in the alert. The solution to your problem would be:
Where to execute the event on "click" you must first make it recognize the click event as a function so that it executes the others.
The second parameter of the function
.on()
receives the reference of a function while you send it the result of a function , which is obviously not the same thing.One way to achieve what you want is to add an attribute to your element, once you click the button, you read the attribute and send it to the function:
The problem is because you are executing the function instead of passing it the definition of a function so that when the event is executed, your function is called.
The problem you have is that the parameter that you pass to the alert you are not taking into account with the javascript syntax. Take a look at your code:
For you to show a string concatenated with a javascript variable, the correct thing is "string"+variable. So:
Here is your code with the fix:
Having seen the other solutions, I also offer you the following one, where in the method
.click()
you pass the parameters as an object.You can also do it with
.on()
:with jquery to pass functions to an event it is done through callbacks.
In this function use
+
to concatenate the two strings inside the alert.in this case use arrow notation
()=>{}
for the callback but you can also use the notationfunction(){}
, the important thing is that the code that we want to execute goes inside the{}
If you wanted to do the same with javascript you could pass the function directly to it:
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
This is one of the many possible solutions to your question: