Check if cursor is end of input text - javascript

What I am trying to do is when I put the email address like test#example.com, test#example.co.uk, etc, and I hit on the space, I want to check that if the cursor is at the end of the input text before I could add HTML in the element.
if (selectionEndofText) {
if (e.which == 32) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
$('#domodal_email_receipt').val('');
}
}
Full code:
$(document).on('keydown', '#domodal_email_receipt', function(e) {
var fullname = $(this).val();
var name = fullname.split(' <');
var selectionEndofText = $(this).val().length;
var name = name[0];
var email = '';
if (fullname.indexOf('<') > -1) {
email = fullname.split('<');
email = email[1].replace('>', '');
}
alert("selectionEndofText................."+selectionEndofText);
//if (!selectionEndofText)
if (e.which == 32) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
$('#domodal_email_receipt').val('');
}
});

In addition to checking space keyword in the if statement, you can also check the caret position with .selectionStart that returns a number. So, if the current position is equal to the length, that means it is in the end of the input.
To clear the input, use a setTimeOut to make it run last. Otherwise, there will be a space inside it.
if (e.which == 32 && selectionEndofText === this.selectionStart) {
$('#oI').append('<div class="vR"><span class="vN" data-hovercard-name="'+name+'" data-hovercard-email="'+email+'" data-hovercard-owner-id="137"><div class="vT">'+name+'</div><div class="vM"></div></span><input name="to" type="hidden" value="<'+name+'>"></div>');
$('.vR').insertBefore('#domodal_email_receipt');
setTimeout(function(){
$('#domodal_email_receipt').val('');
}, 0);
}

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

How to validate texarea by max value using Javascript

I need to validate text area as following code,
my code as follows, here I need set maximum length as 10 and, if user trying to enter more than 10 need to prevent and if it is backspace or delete need to allow for deleting purpose. and also need to show remaining character count in a paragraph. But this code not working well. Its not preventing text input after 10.
<textarea id="txtxasa" class="message-content" onkeyup="Validate(event,this)"></textarea>
<p id="MsgContentRemainingLimit" class="message-character-limit">10 characters remaining</p>
function Validate(e,vald) {
var code;
var txtLength = vald.value.length;
var remainingContent = 10 - txtLength;
$('#MsgContentRemainingLimit').text(remainingContent);
console.log(vald.value.length)
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (txtLength >=10 && (code != 8 || code != 46))
return false;
}
Have you tried adding maxlength="10" to the textarea. I've done it and it works for me.
In Javascript you can try like this
let element = document.getElementById('input-name');
let countElem = document.getElementById('counter').innerHTML;
element.addEventListener('input', function() {
let inputvalue = this.value;
let maxLength = 10;
//disable the input if reached the limit
if (inputvalue.length > maxLength) {
console.log('maximum character limit reached');
this.disabled = true;
}
//count the numbers
let count = parseInt(countElem, 10);
document.getElementById('counter').innerHTML = count - inputvalue.length;
if (inputvalue.length > count) {
document.getElementById('counter').innerHTML = 0;
}
});
<p>
<input placeholder="First Name" id="input-name" name="input">
</p>
<p>remaining characters:</p><span id="counter" style="font-size:25px; font-weight:600;">10</span><br>
In Html5 you can also use the <input maxlength='10'> to limit characters only as a frontend validation. onkeyup in your code will not work if the user copy text and right click and paste them.

Need to limit the comma(,) entered in textbox

I need to place a limit for the number of commas entered in the text area
I tried these links but it dint help
Limit the number of commas in a TextBox
The comma in the textBox
Iam using php. Is it possible to implement php or javascript here.
You should wait for DOMContentLoaded event, and afterwards bind the textarea with a callback for the "input" event:
const MAX_COMMAS = 3;
document.addEventListener("DOMContentLoaded", function(event) {
let textarea = document.getElementById('textbox');
textarea.addEventListener("input", function(event) {
let matchCommas = this.value.match(/,/g);
if (Array.isArray(matchCommas) && matchCommas.length > MAX_COMMAS) {
this.value = this.value.substring(0, this.value.length - 1); // remove the last comma
alert("MAX COMMAS EXCEEDED!");
}
});
});
<textarea id="textbox" cols="40" rows="4"></textarea>
HTML:
<textarea id="textarea" rows="20"></textarea>
JavaScript:
var textarea = document.getElementById('textarea');
var maxCommas = 5;
var filterCommas = function(event) {
var textCommas = this.value.match(/[,]/g);
if(textCommas.length >= maxCommas && event.key === ',') {
event.preventDefault();
return false;
}
}
textarea.onkeydown = filterCommas;
textarea.onkeypress = filterCommas;
textarea.onchange = filterCommas;`
https://jsfiddle.net/xL04qb8c/2/

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Pasting multiple numbers over multiple input fields

I've got a form on my site using 6 input fields. The site visitor simply enters a 6 digit code into these 6 boxes. The thing is that they'll get the 6 digit code and it would be ideal to allow them to simply copy the 6 digit code we send them into these input fields by simply putting pasting into the first input field and having the remaining 5 digits go into the remaining 5 input fields. It would just make it much easier than having to manually enter each digit into each input field.
Here's the code we're currently using, but it can easily be changed to accomplish what is described above:
<input type="text" maxlength="1" class="def-txt-input" name="chars[1]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[2]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[3]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[4]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[5]">
<input type="text" maxlength="1" class="def-txt-input" name="chars[6]">
I saw a posting similar to this here: Pasting of serialnumber over multiple textfields
But it doesn't have the solution I'm looking for. Ideally this could be pulled off using jQuery or plain JavaScript.
Edit
I didn't like the timer solution I used in the paste event and the complexity of just using the input or paste event.
After looking at this for a while I added a solution which uses a hybrid between the 2.
The code seems to do all that is required now.
The Script:
var $inputs = $(".def-txt-input");
var intRegex = /^\d+$/;
// Prevents user from manually entering non-digits.
$inputs.on("input.fromManual", function(){
if(!intRegex.test($(this).val())){
$(this).val("");
}
});
// Prevents pasting non-digits and if value is 6 characters long will parse each character into an individual box.
$inputs.on("paste", function() {
var $this = $(this);
var originalValue = $this.val();
$this.val("");
$this.one("input.fromPaste", function(){
$currentInputBox = $(this);
var pastedValue = $currentInputBox.val();
if (pastedValue.length == 6 && intRegex.test(pastedValue)) {
pasteValues(pastedValue);
}
else {
$this.val(originalValue);
}
$inputs.attr("maxlength", 1);
});
$inputs.attr("maxlength", 6);
});
// Parses the individual digits into the individual boxes.
function pasteValues(element) {
var values = element.split("");
$(values).each(function(index) {
var $inputBox = $('.def-txt-input[name="chars[' + (index + 1) + ']"]');
$inputBox.val(values[index])
});
};​
See DEMO
Here is an example of a jquery plugin that does the same thing as the original answer only generalized.
I went to great lengths to modify the original answer ( http://jsfiddle.net/D7jVR/ ) to a jquery plugin and the source code is here: https://github.com/relipse/jquery-pastehopacross/blob/master/jquery.pastehopacross.js
An example of this on jsfiddle is here:
http://jsfiddle.net/D7jVR/111/
The source as of 4-Apr-2013 is below:
/**
* PasteHopAcross jquery plugin
* Paste across multiple inputs plugin,
* inspired by http://jsfiddle.net/D7jVR/
*/
(function ($) {
jQuery.fn.pastehopacross = function(opts){
if (!opts){ opts = {} }
if (!opts.regexRemove){
opts.regexRemove = false;
}
if (!opts.inputs){
opts.inputs = [];
}
if (opts.inputs.length == 0){
//return
return $(this);
}
if (!opts.first_maxlength){
opts.first_maxlength = $(this).attr('maxlength');
if (!opts.first_maxlength){
return $(this);
}
}
$(this).on('paste', function(){
//remove maxlength attribute
$(this).removeAttr('maxlength');
$(this).one("input.fromPaste", function(){
var $firstBox = $(this);
var pastedValue = $(this).val();
if (opts.regexRemove){
pastedValue = pastedValue.replace(opts.regexRemove, "");
}
var str_pv = pastedValue;
$(opts.inputs).each(function(){
var pv = str_pv.split('');
var maxlength;
if ($firstBox.get(0) == this){
maxlength = opts.first_maxlength;
}else{
maxlength = $(this).attr('maxlength');
}
if (maxlength == undefined){
//paste them all!
maxlength = pv.length;
}
//clear the value
$(this).val('');
var nwval = '';
for (var i = 0; i < maxlength; ++i){
if (typeof(pv[i]) != 'undefined'){
nwval += pv[i];
}
}
$(this).val(nwval);
//remove everything from earlier
str_pv = str_pv.substring(maxlength);
});
//restore maxlength attribute
$(this).attr('maxlength', opts.first_maxlength);
});
});
return $(this);
}
})(jQuery);
This shouldn't be too difficult ... add a handler for the paste event on the first input, and then process per the requirement.
Edit
Actually this is much trickier than I thought, because it seems there's no way to get what text was pasted. You might have to kind of hack this functionality in, using something like this (semi-working)... (see the JSFiddle).
$(document).on("input", "input[name^=chars]", function(e) {
// get the text entered
var text = $(this).val();
// if 6 characters were entered, place one in each of the input textboxes
if (text.length == 6) {
for (i=1 ; i<=text.length ; i++) {
$("input[name^=chars]").eq(i-1).val(text[i-1]);
}
}
// otherwise, make sure a maximum of 1 character can be entered
else if (text.length > 1) {
$(this).val(text[0]);
}
});
HTML
<input id="input-1" maxlength="1" type="number" />
<input id="input-2" maxlength="1" type="number" />
<input id="input-3" maxlength="1" type="number" />
<input id="input-4" maxlength="1" type="number" />
jQuery
$("input").bind("paste", function(e){
var pastedData = e.originalEvent.clipboardData.getData('text');
var num_array = [];
num_array = pastedData.toString(10).replace(/\D/g, '0').split('').map(Number); // creates array of numbers
for(var a = 0; a < 4; a++) { // Since I have 4 input boxes to fill in
var pos = a+1;
event.preventDefault();
$('#input-'+pos).val(num_array[a]);
}
});
You're going to have to right some custom code. You may have to remove the maxlength property and use javascript to enforce the limit of one number per input.
As dbasemane suggests, you can listen for a paste event. You can listen to keyup events too to allow the user to type out numbers without having to switch to the next input.
Here is one possible solution:
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.def-txt-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup paste', handleCharacter)
.on('keydown', handleBackspace);
I have this code set up on jsfiddle, so you can take a look at how it runs: http://jsfiddle.net/hallettj/Kcyna/

Categories

Resources