简体   繁体   中英

Insert text after “this” input-element with javascript?

Code:

<input type="text" onkeydown="
  if (event.keyCode == 13) { HERE, ECHO "OK" RIGHT AFTER THIS INPUT ELEMENT }
">

Is this possible to do without putting an ID or name on this element? Or without encasing it in an identifiable div?

To clarify, this should be the result html after the event keycode is pressed:

<input type="text" onkeydown="
  if (event.keyCode == 13) { HERE, ECHO "OK" RIGHT AFTER THIS INPUT ELEMENT }
">OK

If you want to use jQuery you can do the following:

HTML

<input name="ok" type="text" id="showOK" />

JAVASCRIPT

$("#showOK").keypress(function() {
  if (event.keyCode == 13){
     $("<p>OK</p>").insertAfter("#showOK");
  }
});

Without the Use of ID

<input type="text" onkeydown="if (event.keyCode == 13) { $('<p>OK</p>').insertAfter(this);}">

Following your requirements and trying to keep your style, you can use the insertAdjacentHTML DOM Element method to add a text just after the input element.

<input type="text" onkeydown="
  if (event.keyCode == 13) { this.insertAdjacentHTML('afterend', 'OK');}
">

See demo

I used a mixture of answers here. First off i had to create a new var:

var that = this;

Or else javascript could not find "this" somehow.

Then used the jQUery method:

$('<span>OK</span>').insertAfter(that);

Resulting in:

<input type="text" onkeydown="
  if (event.keyCode == 13) { var that = this; $('<span>OK</span>').insertAfter(that); }
">

Ok, first off, don't use inline-js. But to answer your question,

<input type="text" onkeydown="
    if (window.event.keyCode == 13) { this.outerHTML = this.outerHTML + 'Ok'; } "/>

DEMO

<input type="text" onkeydown="ok(this, event)"/>
function ok(el, event) {
    var _ok = document.createElement('span');

    _ok.textContent = 'ok';

    if (event.which == 13) {
        el.parentNode.insertBefore(_ok, el.nextSibling)
    }
}

Try this:

<input type="text" onkeydown="(function(event){
    var input = event.target;
    if(event.keyCode == 13){
      input.outerHTML += 'OK';
    }
  })(window.event);" />

Demo .

Try this:

<input type="text" onkeydown="
if (event.keyCode == 13) { this.parentNode.insertBefore(document.createTextNode('OK'), this.nextElementSibling); }
">

It will add a text node (without creating any span or div) directly after the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM