I want to make a button that can pass parameters but as you can see where I give the parameter "Jason" to it, it ends the line for the 'onclick' value. What should I do?
<script type="text/javascript">
function greeting(name,age){
alert("Hello, "+name+", you are "+age+" years old.");
}
</script>
<form>
<input type="button" value="Click me" onclick="greeting("Jason",20)" />
I want to make a button that can pass parameters but as you can see where I give the parameter "Jason" to it, it ends the line for the 'onclick' value. What should I do?
<script type="text/javascript">
function greeting(name,age){
alert("Hello, "+name+", you are "+age+" years old.");
}
</script>
<form>
<input type="button" value="Click me" onclick="greeting("Jason",20)" />
Share
Improve this question
edited Dec 7, 2018 at 6:42
Cœur
38.8k25 gold badges206 silver badges278 bronze badges
asked Feb 27, 2013 at 2:01
user1869879user1869879
171 silver badge3 bronze badges
2 Answers
Reset to default 6Use single quotes inside double quotes, otherwise you're terminating the string:
onclick="greeting('Jason',20)"
-^- -^-
You need to use different quotes.
<input type="button" value="Click me" onclick="greeting('Jason',20)" />
Or you can use HTML entities.
<input type="button" value="Click me" onclick="greeting("Jason",20)" />
But onclick
is pretty antiquated. I'd do something like this.
HTML:
<button type="button" class="js-greeting" data-name="Jason" data-age="20">Click me</button>
JS (plus jQuery; you can do it without, but cross-browser issues still make it gross):
$(function() {
$('.js-greeting').click(function() {
var name = $(this).data('name');
var age = $(this).data('age');
alert("Hello, " + name + "; you are " + age + " years old.");
});
});