Domanda

I have a text box in my page:

<td>
<input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event)" style="width: 470px;" />
</td>

This is my js function:

function AddUsersKeyDown(evtobj) {

    if (evtobj.keyCode == 75 && evtobj.ctrlKey) {

        AddUsers(--input parameter--);
    }
}

Now if i press ctrl k in my textbox it must call another javascript function named AddUsers(--input parameter--).. where the input parameter should be the id of the textbox...

How to achieve this.. Either i need the id of the textbox or atleast the DOM object so that i can access the id of textbox from DOM object..

Kindly help me in achieving either one of the two things..

È stato utile?

Soluzione 2

Use this to get the DOM element or this.id to get the id of the element

<td>
<input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event,this.id)" style="width: 470px;" />
</td>

function AddUsersKeyDown(evtobj,id) {

    if (evtobj.keyCode == 75 && evtobj.ctrlKey) {

        AddUsers(id);
    }
}

Altri suggerimenti

First you should rename the function to AddUsersKeyDown so the keydown event will be triggered. On the event object, there is a target property, which have the triggering DOM element. You can use that information to get the id.

 <input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event)" style="width: 470px;" />

And the Javascript:

function AddUsersKeyDown(evtobj) {

    var target = evtobj.target || evtobj.srcElement;

    if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
        AddUsers(target.id);

        return false;
    }
}

Here is a jsfiddle: http://jsfiddle.net/q26Nv/3/

get jquery here

and then take of onkeydown

<input type="text" id="Approvers1" class="keydown" size="11" style="width: 470px;" />

add script

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function() {
    $('.keydown').keydown(function() {
       console.log( $(this).attr('id') );
    });
});
<script>

maybe a lot of code, but you can be sure it's cross browsers documentation

You can:

function AddUserKeyDown(evtobj) {
    evtobj = evtobj || window.event;
    var target = evtobj.target || evtobj.srcElement;

    if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
       AddUsers(target.id);
    }
}

(Your func names don't match btw)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top