1

HTML:

<form id="myForm" >
     <input id="oknovo" type="submit" value="OK & Novo" />
     <input id="okfechar" type="submit" value="OK & Fechar" />
</form>

JS:

$("#myForm").submit(function(event){
    var botao=$("input[type=submit][clicked=true]").id;
    alert(botao);
});

How do I identify which of the buttons was clicked to submit the form?

I've also checked this

And tried this:

var botao=$("input[type=submit][clicked=true]").val();

But I always get "undefined".

Community
  • 1
  • 1
  • 1
    $("input[type=submit][clicked=true]").attr('id'); – Rishi Php Feb 18 '14 at 12:43
  • Same result, you may see a live example here:http://jsfiddle.net/nuno/3fJ3r/ –  Feb 18 '14 at 12:45
  • If you are willing to submit the form to be handled in php, you can check it in php very simple. Therefore you would have to give the submitButtons each a name and can then check theire value in php... – Martin Feb 18 '14 at 12:56
  • @Martin I also want the browser to dismiss or reload the form for new input –  Feb 18 '14 at 12:59
  • Ok then you have to use one of the answers to catch the click with js. By the way if you are using jQuery why not take the id by normal $(...).attr('id'); function?! – Martin Feb 18 '14 at 13:03

3 Answers3

1

Try this:

var buttonID;

$("#myForm input[type=submit]").on('click', function() {
    buttonID = $(this).attr('id');
});

Update:

I've updated your code and added a little example here. Seems to work ok now.

Artem Gordinsky
  • 616
  • 6
  • 21
  • Thanks for defining buttonID outside the function ;-D –  Feb 18 '14 at 12:58
  • No matter where I define the variable, I can't get it to work.. http://jsfiddle.net/nuno/3fJ3r/4/ –  Feb 18 '14 at 14:28
0

Try this:

$("input[type=submit]").click(function(event){
    alert($(this).attr('id'));
});

A form is submitted, when you click the input type="submit"

Here is the Fiddle

Linga
  • 10,379
  • 10
  • 52
  • 104
  • It seems to be working (http://jsfiddle.net/nuno/3fJ3r/1/). This will also submit the form, right? :-D –  Feb 18 '14 at 12:51
  • 1
    if you are just wanting the id you could use `this.id` and it would be better for performance – Pete Feb 18 '14 at 12:57
0

You can use .prop() to get the id of clicked element

Try this:

$("input[type=submit]").click(function(event){
    alert($(this).prop('id'));
});
nrsharma
  • 2,532
  • 3
  • 20
  • 36