开发者

Simulate a button click via JavaScript using a button's value, not its id?

I want to Simulate a button cli开发者_如何学运维ck 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.


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.


<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


    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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜