1

How do I call a user-define function such as this one using the onClick attribute of a input button? More specifically what special steps must I take in JQuery and what would the HTML markup look like? Thanks

function simClick(keyCode) {
            var e = jQuery.Event("keypress");
            e.keyCode = 8;
            $(document).trigger(e);
        }


<input type="button" ID="delBtn" class="calcBtn" value="Del" onclick="???????" />
Matthew Cox
  • 13,566
  • 9
  • 54
  • 72

1 Answers1

2

HTML

<input type="button" ID="delBtn" class="calcBtn" value="Del" />

Javascript in separate file

  // When the DOM is ready
$(function() {
      // Function that is executed w keypress or button click
    doThis = function() {

        // Stuff to do
    }

      // To do when element with ID delBtn is clicked
    $("#delBtn").click(function() {

        // Stuff to do when input is clicked
        doThis();
    });

     // To do when key is pressed
    $(document).keydown(function(event) {

        // Stuff to do when key is pressed
        // Can check which key was pressed here.
        var code = (event.keyCode ? event.keyCode : event.which);
        if(code == 8) { //Enter keycode 

            doThis();
        }
    });
});

There are many ways to attach a handler to when that button is clicked. Take a look at jQuery selectors.

You could also use the attribute equals selector

$("input[value='Del']")...... // For the input with a value of Del

I'm not sure what you quoted JS has to do with the input button, since it looks like you're trying to work with a keypress instead of a click in that function.... But the above jQuery is how you capture a click on that input button.

Take a look at, "Which key was pressed?"

Community
  • 1
  • 1
Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
  • ahhh good question. I'm working on a little project that will detect key presses and execute code ... but i'm also using buttons to allow the less inclined to use a gui. so I basically am trying to reroute a button click to the same code i already have in place for detecting keypresses – Matthew Cox Sep 18 '10 at 03:28
  • @Matthew - Just call the same function with both. - edited answer. – Peter Ajtai Sep 18 '10 at 03:42
  • so could someone help me visualize the structure here... function myMethod() { } $(document).keypress(function (event){ myMethod(); } .. then what would I place here to bind the event handler and call myMethod? Forgive me but it's day two on JQuery and Javascript cominbed lol function myMethod() { } – Matthew Cox Sep 18 '10 at 04:08
  • lol nm. i just extracted the code into a general method then called it in the keypress event and button click event ... newb central lol – Matthew Cox Sep 18 '10 at 04:21