5

I want to Simulate a button click via JavaScript using a button's value, not its id.

Here is the code using the button id

<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">

I've tried getElementByValue('Button') but it didn't work.

4
  • It works just fine for me: jsfiddle.net/pimvdb/R27rQ. Commented Aug 19, 2011 at 12:16
  • @pimvdb That solution still uses the id. Commented Aug 19, 2011 at 12:18
  • @jncraton: I misunderstood the question. Didn't see what 'no't' meant. Commented Aug 19, 2011 at 12:20
  • not sure why you want to do this, but it doesn't work for me in OS X Lion and Chrome. As in, the alert appears but the button click is not animated. Commented Aug 19, 2011 at 12:21

3 Answers 3

4

Here's how I'd do it using jQuery:

http://jsfiddle.net/skilldrick/R27rQ/1/

$('input[type=checkbox]').click(function () {
    $('input[value=Button]').click();
}); 

but as Senad said, IDs are much better-suited for this type of thing.

Sign up to request clarification or add additional context in comments.

Comments

2
<script type="text/javascript">
    function getButtonByValue(value) {
        var els = document.getElementsByTagName('input');

        for (var i = 0, length = els.length; i < length; i++) {
            var el = els[i];

            if (el.type.toLowerCase() == 'button' && el.value.toLowerCase() == value.toLowerCase()) {
                return el;
                break;
            }
        }
    }
</script>    
<input type="checkbox" onClick="getButtonByValue('Button').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">

jsfiddle example

Comments

1
    function clickButton(val)
    {
    var buttons = document.getElementsByTagName('input');
      for(var i = 0; i < buttons.length; i++) 
      {
         if(buttons[i].type == 'button' && buttons[i].value == val) 
         {
              buttons[i].click();
              break; //this will exit for loop, but if you want to click every button with the value button then comment this line
         }
      }
}

this is solution...

HTML

<input type="checkbox" onClick="clickButton('Button');">Check the box to simulate a button click

But its best to find element by its ID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.