How to exit a text field after clicking outside a cell

I accidentally found this code on the Internet and it solved most of my problem, however there is one thing I want to add to this code, but I don’t know how my question is, how can I exit the text field after the user double-clicked it, or after the user has finished editing it?

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title></title> <script type="text/javascript"> /*<![CDATA[*/ function INPUT(id){ var obj=document.getElementById(id),tds=obj.getElementsByTagName('TD'),z0=0,ip,html; for (;z0<tds.length;z0++){ tds[z0].onmouseup=function(){ AddInput(this); } } } function AddInput(td){ var ip=zxcAddField('INPUT','text',''); ip.value=td.innerHTML; td.innerHTML=''; td.appendChild(ip); td.onmouseup=null; } function zxcAddField(nn,type,nme){ var obj; try { obj=document.createElement('<'+nn+' name="'+(nme||'')+'" '+(type?'type="'+type+'" ':'')+' >'); } catch(error){ obj=document.createElement(nn); if (type){ obj.type=type; } obj.name=nme||''; } return obj; } /*]]>*/ </script> <script type="text/javascript"> /*<![CDATA[*/ function Init(){ INPUT('tst'); } if (window.addEventListener){ window.addEventListener('load',Init, false); } else if (window.attachEvent){ window.attachEvent('onload',Init); } /*]]>*/ </script> </head> <body> <table id="tst" border="1"> <tr width="200"> <td>some html</td> </tr> </table> </body> </html> 
+4
source share
1 answer

First, modify AddInput to set a listener for the blur event, which will fire when something other than this element gets clicked:

 function AddInput(td){ var ip=zxcAddField('INPUT','text',''); ip.value=td.innerHTML; ip.onblur = function () { removeInput(ip); }; td.innerHTML=''; td.appendChild(ip); td.onmouseup=null; } 

Then you can add a new removeInput function that will replace the contents of the <td> when the <input> triggers a blur event:

 function removeInput(input) { var val = input.value; var td = input.parentNode; td.removeChild(td.lastChild); td.innerHTML = val; td.onmouseup = function () { AddInput(td); }; } 

This function also reassigns the mouseup event listener, since it gets null in the AddInput function.

Keep in mind that while this worked for me in Chrome 22, it will probably take a little extra effort to test and fix any cross-browser issues with built-in events and attribute assignments.

If this were my code, I would probably rewrite the "standard" version with addEventListener and getAttribute() / setAttribute() , and then create only the correcting IE path using its equivalents. Or just use jQuery and let it do all the cross-browser stuff for you.

+1
source

Source: https://habr.com/ru/post/1441183/


All Articles