I have a page dynamically created with many input boxes to serve as comments. They are placed side by side with other elements. See photo.
Basic idea is that on blur event (lose focus) or key press enter to update the input box automatically via ajax (no form submit is necessary).
HTML CODE:
1 2 3 |
<input id="input_${error.id}" type="text" value="${error.comment}" onblur="updateComment('${error.id}', '${error.comment}');" onkeydown="processKeyPress(this, event);"/> |
In my case this is a JSP page and ${error.id} = 32, ${error.comment} =”123″;
JavaScript for enter key:
1 2 3 4 5 6 |
function processKeyPress(e, event) { var fnc = $(e).attr('onblur'); if (event.keyCode == 13) { eval(fnc); } } |
JavaScript for persist on blur (inputs are id=32 and oldvalue=”123″):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
function updateComment(id, oldvalue) { var contextPath = "<%=request.getContextPath()%>"; //obtain context path from JSP var input = $('#input_' + id); //my id is "input_32" var value = input.val(); //get the new value if (oldvalue != value) { //compares to detect a change in comment if (value != '') { //don't persist empty strings $.ajax( { type:"POST", url:contextPath + "/admin/error/update.json", data:"id=" + id + "&comment=" + value, success:function (data) { if (data == true) { var blur = input.attr('onblur'); //obtain blur element to update values var n = blur.replace(blur, 'updateComment('' + id + '', '' + value + '');'); //replace blur attr with new value input.attr("onblur", n); //update blur input.val(value); //update value } } } ); } } } |
There is room for improvement, but this functionality serves my purpose