jQuery Get element by name and do action on Key "Enter"
I hope you can help me with this开发者_运维知识库. I have an element, a button input that has not an ID but only a name.
I am working on a CMS and I do not want to modify the default code.
I am wondering if there is in jQuery a function that will give me the possibility to get an Element by name instead than by ID.
I want to add an onClick
function to this element, so I need a way to get its name instead of the ID.
The other question is if there is a way in jQuery that I can use to run a function when Enter on the keyboard is pressed on a input text element. Something like onClick
, but when the Enter key is pressed.
Let me know. Thank you!
Yes...
1) You can get the element by name using the attribute equals selector:
$('button[name="foo"]')
where foo
is your element's name.
2) The click handler will automatically be run if you press enter if the element is an anchor (link) element. Otherwise, use keypress
and compare event.which
(the numeric identifier for the key that was pressed) to 13
(which indicates the enter key):
$('button[name="foo"]').keypress(function(event) {
if (event.which === 13) {
// the enter key was pressed
}
});
This is an attribute equality selector.
$('input[name="foo"]').click(function(){});
On the second part, you'll need to add an event handler for keydown.
$('input[name="textfield"]').keydown(function(evt){
if ((evt.keyCode) && (evt.keyCode == 13))
{
// perform enter actions.
}
});
$('input[name="myName"]').click(function() {
//do whatever
});
Get Element by name attribute:
$("[name='elementName']").click(function(){
//perform action
});
Run code when enter is pressed in an input field:
$('input[type="text"]').bind("keypress", function (e) {
if (e.keyCode == 13){
//run enter code
}
});
精彩评论