Reputation:
How can I assign the id of a submit button to a variable using JQuery?
I have the following HTML:
<form id="myForm">
<input id="oknovo" type="submit" value="OK & Novo" />
<input id="okfechar" type="submit" value="OK & Fechar" />
</form>
JS:
var botao;
$(document).ready(function () {
$("#myForm input[type=submit]").click(function (event) {
botao = $(this).attr('id');
alert("id é " + botao);
});
});
You may see the live JSFiddle here
I've already managed to indentify the clicked button wiht the help of this question but the problem now is to assign it to a global variable.
Upvotes: 1
Views: 595
Reputation: 23042
This question does not makes any sense, since code looks like working except syntax errors; on the other hand, you can use hidden fields to keep some data for temporary.
<form id="myForm">
<input id='myGlobalHidden' type='hidden'/>
<input id="oknovo" type="button" value="OK & Novo" />
<input id="okfechar" type="button" value="OK & Fechar" />
</form>
var botao;
$(document).ready(function () {
$("#myForm input[type=button]").click(function (event) {
botao = $(this).attr('id');
//alert("id é " + botao);
$("#myGlobalHidden").val(botao);
// access here
alert($("#myGlobalHidden").val());
});
});
Upvotes: 0
Reputation: 608
Your code is correct, you just need to add the closing parenthesis )
at the end.
$(document).ready(function () {
^ unclosed
Upvotes: 2
Reputation: 1734
You are missing brackets on your fiddle. It should read:
var botao;
$(document).ready(function () {
$("#myForm input[type=submit]").click(function (event) {
botao = $(this).attr('id');
alert("id é " + botao);
});
});
Upvotes: 1
Reputation: 943213
the problem now is to assign it to a global variable.
Either remove the line var botao;
or take it out of the function you are calling onload
(via the JSFiddle configuration on the left).
Upvotes: 2