Lalchand
Lalchand

Reputation: 7827

value of button using javascript

I have 3 buttons in my form.

All the button actions goes to a same page after clicking it depending upon what button is clicked.

My query is: The name of the buttons are 'add','edit' and 'remove'

When the 'add' button is clicked, using js I need to get the value of that button and similarly for the other two buttons....

Can you please help?

Upvotes: 1

Views: 25158

Answers (4)

yogesh kumar
yogesh kumar

Reputation: 950

There is target property which you can use.It targets the element which caused the event to occur.

button.addEventListener('click',function(e){
     console.log(e.target.value);
});

Upvotes: 1

cHao
cHao

Reputation: 86506

<form>
 <script type="text/javascript">
  function doAction(value)
  {
   // Don't really have anything to set...just show the value
   alert(value);
  }
 </script>
 <input type="button" value="Add" onclick="doAction(this.value)">
 <input type="button" value="Edit" onclick="doAction(this.value)">
 <input type="button" value="Remove" onclick="doAction(this.value)">
</form>

There are other ways that involve not even passing the button's value, but they're not as compatible across browsers (IE uses a slightly different event model).

Of course, if you can get by without doing it in Javascript, and can just pass the clicked button to the server, it gets even easier than that...

<form>
 <input type="submit" name="action" value="Add">
 <input type="submit" name="action" value="Edit">
 <input type="submit" name="action" value="Remove">
</form>

and whichever button you click gets put into the url as action=Add or whatever.

Upvotes: 8

Łukasz W.
Łukasz W.

Reputation: 9755

What about:

var buttonValue = document.getElementById('IdOfYourButton').value

Upvotes: 6

aniri
aniri

Reputation: 1831

have you tried: document.getElementById('button_id').value in the js function that you'll call when the button is clicked?

Upvotes: 1

Related Questions