45RPM
45RPM

Reputation: 133

jQuery - operate values from submit buttons

I have a form with several submit buttons. I'm trying to use jQuery so it could take values on "submit" function and operate them.

i'm not good at jQuery ..so for now i only come to this...

<form id="buttons">
    <input type="submit" id="light1" value="OFF" />
    <input type="submit" id="light2" value="ON" />
    <input type="submit" id="light3" value="ON" />
    <input type="submit" id="light4" value="OFF" />
</form>

<script>
$('#buttons').submit(function() {
 $.get("data.php", { light1: "ON"} );
  return false;
});
</script>

So the thing is how can i instead of this

  $.get("data.php", { light1: "ON"} );

some how on submit take the id of button and a value ? So it could be like

 $.get("data.php", { *ID OF A BUTTON*: "*VALUE OF BUTTON*"} );

...and operate it?

Thanks!

P.S the values of buttons are refreshing with php and jQuery, so no worry about this part ;]

Upvotes: 1

Views: 210

Answers (2)

Ram
Ram

Reputation: 144689

$('#buttons input[type="submit"]').on('click', function(e) {
   e.preventDefault();
   var data = {};
   data[this.id] = this.value;
   $.get("data.php", data );
});

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 237865

I would think the easiest solution would be to catch the event on the button elements, rather than on the form.

$('#buttons').on('click', 'input[type="submit"]', function(e) {
     e.preventDefault(); // for safety's sake
     var data = {};
     data[this.id] = this.value;
     $.get("data.php", data);
});

Upvotes: 2

Related Questions