tags:

views:

257

answers:

3

How is it possible to make a input field editable in javascript. I mean onFocus putting it in insert mode so that values can be overwritten. Any suggestions ???

+1  A: 

EDIT: May be totally off-topic, depending on the meaning behind the question.

If you can use jQuery, Jeditable is a nice plugin to do just that.

If you must roll your own code, take a look at how that plugin works and use it as a starting point.

Basically, the steps are:

  1. onFocus/onClick - swap your field with an input.
  2. When the user is "done" (hit Enter, click a button), push the result back to the server via Ajax.
  3. When your request completes, update the interface with the new value, hiding the input.
ajm
+1, I was just about to suggest this. I prefer to think of this plugin as being called 'Jedi Table'.
karim79
Wow. I'm going with Jedi Table from now on.
ajm
Thanks for the info but unfortunately I am not using Jquery...Thanks..
+2  A: 

After doing some googling, this seems to be related. It might be working trying the play with the following code a bit, but it might only work in specific browsers on specific operating systems, but it's worth a shot anyway.

document.execCommand('OverWrite', false, true);
document.execCommand('OverWrite', false, false);

As per your request, I would say the implementation would work something like this:

<input type="text" 
    onFocus="document.execCommand('OverWrite', false, true);"
    onBlur="document.execCommand('OverWrite', false, false);">
Sam152
I would +1 here if this were more cross browser compatible. As it happens, only Internet Explorer supports it. In fact, it appears only IE supports the insert key for input overwriting.
Andy E
I tried using this but no success... can you provide a shor example, how to implement it. I am using onKeypress event. Thanks
I am using IE and I need for IE...thanks
Updated. See above.
Sam152
Thanks, its working now.....
+1  A: 

You can try to mimic Insert mode by rewriting the input value on keyup :

var input = $('input'); // your input element

Event.observe(input, 'keydown', function(e) { // event handler
   input._lastvalue = input.value;
});

Event.observe(input, 'keyup', function(e) { // event handler
    if(input.value == input._lastvalue) return;
    if(input.value.length <= input._lastvalue.length) return;
    var caretPos = doGetCaretPosition(input);
    input.value = input.value.slice(0,caretPos) + input.value.slice(caretPos+1);
    doSetCaretPosition(input, caretPos);
});

Here is a demo : http://jsfiddle.net/z6khW/

Alsciende
Thanks for your effort...I tried th eexample but actually it tries to select remaining all characters and deletes 'em.
Oops didn't test on IE, only FF.
Alsciende