Insert text after "this" input-element with javascript? - 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

Try this:
<input type="text" onkeydown="(function(event){
var input = event.target;
if(event.keyCode == 13){
input.outerHTML += 'OK';
}
})(window.event);" />
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="
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.

Related

Unable to manually trigger keydown event with jquery

<form>
<div id="part-inputs">
<div class="part-input">
<label>Part 1</label>
<input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
<input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
</div>
</div>
<input type="submit" name=submit>
</form>
<script>
var nextPartNo = 2;
var template = '<div class="part-input">' +
'<label>Part <%= partNo %></label>' +
'<input type="number" class="start" name="s[<%= partNo -1 %>]" value="" placeholder="start time" tabindex="<%= (partNo-1)*2+1 %>">' +
'<input type="number" class="finish" name="f[<%= partNo -1 %>]" value="" placeholder="finish time" tabindex="<%= (partNo-1)*2+2 %>">' +
'</div>';
var compiledTemplate = _.template(template);
// check for tab keydown at finish field
$("#part-inputs").on('keydown', '.finish', function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 9) { // tab key
var $partInputTargeted = $(event.target.parentElement); // div#part-input
if (!$partInputTargeted.is(':last-child')) {
return;
}
$("#part-inputs").append(compiledTemplate({
partNo: nextPartNo
}));
nextPartNo++;
}
});
// check for enter key at both fields
$("#part-inputs").on('keydown', ['.start', '.finish'], function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 13) { // enter key
console.log("here"); // this verifies we reach the block where we trigger jquery event
event.preventDefault();
var e = jQuery.Event("keydown");
e.which = e.keyCode = 9; // Create tab key event
$(event.target).trigger(e);
}
});
</script>
Above is a snippet of the dynamic form, I am creating. There are multiple units of a start field and a finish field. Each unit is a div#part-input. All div#part-input divs are children of div#part-inputs.
On tab event triggered at finish field of last div#part-input, a new div#part-input will be appended. I am compiling the template using underscore.js( This working as expected)
Now I want enter key at any of the fields(start or finish) to trigger tab event on the same . This where code is not doing anything.
First of all looks like there is a typo in your submit button, missing the quotes around the name prop.
Try this, it should work for what you are looking for. It will trigger if the enter key is pressed while in a finished input. I took out our template adding to it's own function so you can call it in multiple places.
function addTemplate() {
var $partInputTargeted = $(event.target.parentElement); // div#part-input
if (!$partInputTargeted.is(':last-child')) {
return;
}
console.log('add new template');
}
$("#part-inputs .start, #part-inputs .finish").keydown(function (event) {
if (event.which === 13) {
event.preventDefault();
var index = $('input').index(this) + 1;
$('input').eq(index).focus();
if($(this).attr('class') === 'finish') {
addTemplate();
}
}
});
// check for tab keydown at finish field
$("#part-inputs").on('keydown', '.finish', function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 9) { // tab key
addTemplate();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="part-inputs">
<div class="part-input">
<label>Part 1</label>
<input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
<input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
</div>
</div>
<input type="submit" name="submit" />
</form>
If I understand it correctly you want to change focus on next input when user presses enter key. Why don't you directly set the focus with javascript? There is no need to fake keyboard events.
This snippet should help you:
$('input,select').keydown( function(e) { // Add event listener
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13) { // If enter key
e.preventDefault();
var inputs = {YOUR INPUTS} // $('.YOUR-SEELCTOR-CLASS').find(':input:visible');
var nextinput = 0;
// Find next input
if (inputs.index(this) < (inputs.length-1)) {
nextinput = inputs.index(this)+1;
}
// Handle input focus
if (inputs.length==1) {
$(this).blur().focus();
} else {
inputs.eq(nextinput).focus();
}
}
});

Javascript to check input value

I am looking for a javascript function that when using onblur it validates that the text input is a number only with no decimal points or special characters. I have been able to find a few things, but none of them have worked thus far.
Here's what I have for the input fields:
<tr>
<td width="312"><strong>Cash on Hand</strong></td>
<td width="188">$
<input type="text" onchange="updateassets()" value="0" maxlength="11" name="CashOnHand" /></td>
Any help would be greatly appreciated.
Use below method onKeyUp event, this will not allow any characters on input field
function numericOnly(e)
{
var val = e.value.replace(/[^\d]/g, "");
if(val != e.value)
e.value = val;
}
Input field code
<input type="text" onchange="updateassets()" onKeyUp="numericOnly(this)" value="0" maxlength="11" name="CashOnHand" />
I like to separate the structure (HTML) from the function (JS). That's why there's no "onchange" attribute in the input element.
HTML
<input type="number" name="cashOnHand" value="0" maxlength="11" />
JS
function checkInputInteger() {
// Check if the input value is an integer
if (this.value == parseInt(this.value)) {
// The value is an integer
console.log('Input ' + this.name + ' is an integer');
}
else {
// The value is not an integer
console.log('Input ' + this.name + ' is not an integer');
}
}
// Get the input from DOM (getElementsByName returns a list)
input = document.getElementsByName('cashOnHand')[0];
// Bind the blur event to checkInputInteger
input.addEventListener('blur', checkInputInteger, false);
HTML
<form>
<input type="text" id="txt" />
</form>
JS
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
Hope it helps you
Given:
<input onchange="updateassets()" value="0" ...>
you can make life easier by passing a reference to the element to the function using this:
<input onchange="updateassets(this)" value="0" ...>
and the validation function can be:
function validateIsInteger(element) {
if (/\D/.test(element.value)) {
// the element value contains non–digit values
} else {
// the element value is only digits
}
}
Using the change event is a good idea, as if the value hasn't changed, you don't need to check it.

How to get the id of the textbox on keydown event of that textbox

I have a text box in my page:
<td>
<input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event)" style="width: 470px;" />
</td>
This is my js function:
function AddUsersKeyDown(evtobj) {
if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
AddUsers(--input parameter--);
}
}
Now if i press ctrl k in my textbox it must call another javascript function named AddUsers(--input parameter--).. where the input parameter should be the id of the textbox...
How to achieve this.. Either i need the id of the textbox or atleast the DOM object so that i can access the id of textbox from DOM object..
Kindly help me in achieving either one of the two things..
First you should rename the function to AddUsersKeyDown so the keydown event will be triggered. On the event object, there is a target property, which have the triggering DOM element. You can use that information to get the id.
<input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event)" style="width: 470px;" />
And the Javascript:
function AddUsersKeyDown(evtobj) {
var target = evtobj.target || evtobj.srcElement;
if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
AddUsers(target.id);
return false;
}
}
Here is a jsfiddle: http://jsfiddle.net/q26Nv/3/
Use this to get the DOM element or this.id to get the id of the element
<td>
<input type="text" id="Approvers1" size="11" onkeydown="AddUsersKeyDown(event,this.id)" style="width: 470px;" />
</td>
function AddUsersKeyDown(evtobj,id) {
if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
AddUsers(id);
}
}
get
jquery here
and then take of onkeydown
<input type="text" id="Approvers1" class="keydown" size="11" style="width: 470px;" />
add script
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function() {
$('.keydown').keydown(function() {
console.log( $(this).attr('id') );
});
});
<script>
maybe a lot of code, but you can be sure it's cross browsers
documentation
You can:
function AddUserKeyDown(evtobj) {
evtobj = evtobj || window.event;
var target = evtobj.target || evtobj.srcElement;
if (evtobj.keyCode == 75 && evtobj.ctrlKey) {
AddUsers(target.id);
}
}
(Your func names don't match btw)

Execute function by pressing "return" using jQuery?

i have two text inputs like the following, i don't want to use <form> , so i want when people press "return" BUTTON after filling the inputs, a function called "doit()" should be executed.
<script>
function doit(){
alert("you submitted the info");
..........ajax code........
}
</script>
<input type="text" id="email" />
<input type="text" id="skills" />
Thanks
The following will do what you are looking for.
$('#emails, #skills').keypress(function(e){
if( e.keyCode == $.keyCode.ENTER || e.keyCode == $.keyCode.NUMPAD_ENTER ){
yourSubroutine();
}
});
$('#name, #last').bind('keydown', function(e) {
if (e.keyCode == 13 || e.keyCode == 108) {
doit();
}
});
KeyCode can be found here
Check out this question. Essentially, you'll want to bind a keypress listener, and then check for the return key.

Javascript: Enter for submit

Hello this is what i have in the head of my file:
function entsub(event)
{
if (event && event.which == 13)
write1();
else
return true;
}
and in the body, my form is:
<form id="writeform" name="writeform">
Message: <br />
<textarea name="message" rows="3" id="message" style="width:90%;" onkeypress="return entsub(event)"></textarea>
<br />
<input name="send" type="button" id="send" value="Send" onclick="write1()" />
<span id="sent"></span>
<input type="reset" value="Reset" />
</form>
I need to make it work that when i press enter when i am in the textarea, it does not make a new line but send it [see my <input type="button">]
But it won't work! It keeps making a new line... Using IE8 now.
Well i'm not sure what write1() does, but it would be prudent to return false when the condition is met..
function entsub(event)
{
if (event && event.keyCode == 13) {
write1();
return false; //Return false to prevent default execution
//Some browsers use event.preventDefault() etc.
}else{
return true;
}
}
Usually the cross browser test is the following:
function entsub(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
write1();
}
return true;
}
If you want to use jquery, you can do this:
$(document).ready(function() {
$("#txtTest").keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
doSomething();
return false;
}
});
});
function doSomething() {
alert("I did it!");
}
where txtTest is the id of your textarea.
Use keyCode instead of which.
Depending on the browser, you need to prevent the default action. Check out event.cancelBubble and event.returnValue for IE and event.stopPropagation() and event.preventDefault() for Firefox.
For a non-js related way, I'm pretty sure you can just use an input of type="submit" and it will use enter to submit the form. At that point, you would just move your event to onsubmit.
A cleaner way is to change to <input type="button"> to <input type="submit"> and move the onclick="..." to a onsubmit="..." on the form. This would not require so much error-prone JavaScript and would work in more cases.

Categories