javascript - Reference the text field that I'm in when I press enter -
javascript/jquery (doesn't work how want to):
function chkkey(event) { if (event.keycode == 13) { $(this).val("value", "wow such code"); }; };
i not want reference text field name because have multiple text fields on page different names use same chkkey function. need reference text field i'm in regardless of name. possible? i'm thinking it's parent/bubbling issue, don't have experience things @ all.
edit: complete html/js:
<!doctype html> <html> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0" /> <title>boxes , lines</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div id="outerdiv"> <input type="button" name="btnnewfield" value="add new field" onclick="appendnewfield()"> <p></p> <div id="maindiv"></div> </div> <script> function chkkey(event) { if (event.keycode == 13) { $(this).val("value", "wow"); }; }; // returns text field object function txtfield(fieldname, fieldval){ var objtxtfield = document.createelement("input"); $(objtxtfield).attr({ type: "text", name: fieldname, value: fieldval, onkeyup: "chkkey(event)" }); return objtxtfield; }; // if there no appended text field, create 1 , give focus function appendnewfield() { if ($("#maindiv").find('[name="apptxtfield"]').length === 0 ) { $(new txtfield("apptxtfield", "")).appendto($("#maindiv")).focus(); }; }; </script> </body> </html>
there 2 errors in code:
- using
val
attr
orprop
, expects 1 parameter - trying add
keyup
event handlerattr
, , should usingon
take @ code below, fixed items above:
function chkkey(event) { if (event.keycode == 13) { $(this).val("wow such code"); }; }; // returns text field object function txtfield(fieldname, fieldval){ var objtxtfield = document.createelement("input"); $(objtxtfield).attr({ type: "text", name: fieldname, value: fieldval }).on('keyup', chkkey); return objtxtfield; }; // if there no appended text field, create 1 , give focus function appendnewfield() { if ($("#maindiv").find('[name="apptxtfield"]').length === 0 ) { $(new txtfield("apptxtfield", "")).appendto($("#maindiv")).focus(); }; }; appendnewfield()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="maindiv"></div>
Comments
Post a Comment