0

I want to send the ID of an element to the function to know what button pressed it.

<input type="submit" id="foo" onclick="function(abcxyz)" value="abc" />
<input type="submit" id="foo" onclick="function(xyz)" value="x" />

function(str){
    if(str == abcxyz){
        //do this.
    }
    else if(str == xyz){
        //do that.
    }
}

or if it's possible, its okay that the value abc or x will be send to the function. so str = abc or str = x.

Robin van Baalen
  • 3,632
  • 2
  • 21
  • 35
  • The rule is, ID of an element should be unique in that page. – KBN Feb 12 '13 at 18:18
  • sorry for that, I just copy and paste the input and added new value. my mistake. And yes your right, it must be unique because its an ID. – user2045458 Feb 12 '13 at 18:45

4 Answers4

1

If I have understood your problem correctly...

  1. You are missing a function name
  2. The two inputs have the same id
  3. using submit for type doesn't make sense in your case
  4. The values of the inputs aren't needed for this task

    <input type="button" id="foo1" onclick="button_click('1')" />
    <input type="button" id="foo2" onclick="button_click('2')" />`
    
    function button_click(str){
        if(str == '1'){
            alert('Button with id foo1 was pressed');
        }
        else if(str == '2'){
            alert('Button with id foo2 was pressed');
        }
    }
    
alu
  • 759
  • 7
  • 20
0

You can use the answer that you'll find here.

Basically write

<input type="submit" onclick="yourFunction(this.id)" id="abc" value="Button abc" />
Community
  • 1
  • 1
Phil Bozak
  • 2,792
  • 1
  • 19
  • 27
0

Your function needs a name:

Try:

<script type="text/javascript">
    function whichButton(str){
        if(str == 'abc'){
            alert('abc was clicked');
        }
        else if(str == 'x'){
            alert('str was clicked');
        }
    }
</script>
<input type="submit" id="foo" onclick="whichButton(this.value);" value="abc" />
<input type="submit" id="foo1" onclick="whichButton(this.value);" value="x" />
SeanWM
  • 16,789
  • 7
  • 51
  • 83
0

As a solution to your problem please refer the code snippet mentioned below

E.g

  <input type="submit" id="foo" onclick="function(this.value)" value="abc" />
  <input type="submit" id="foo" onclick="function(this.value)" value="x" />

In above code snippet this object will refer to event source i.e submit button

Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26