Get value on keydown or input - javascript

I have a textbox and I want to get the value of the key pressed. I use jQuery to allow the user to insert only numbers and letters even if copy/paste is used.
I'd like to get the letter or the number the user pressed.
$("#Nombre").on("keydown", function(event) {
var regexp = /[^A-Za-z0-9]+/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
} else {
var Valor = $(this).val(); //get the value of keypressed here
}
});
$("#Nombre").on("input", function() {
var regexp = /[^A-Za-z0-9]+/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
} else {
var Valor = $(this).val(); //get the value of keypressed here
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="Nombre" Maxlength=43 name="txtNombre" required>

On keydown you can use String​.from​Char​Code() to get the character from event.keyCode. On input event you can get the last character from the value:
$("#Nombre").on("keydown", function(event) {
var regexp = /[^A-Za-z0-9]+/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
}
else{
var Valor = String.fromCharCode(event.keyCode)
console.log(Valor);
}
});
$("#Nombre").on("input", function() {
var regexp = /[^A-Za-z0-9]+/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
}
else{
var val = $(this).val();
var Valor = val[val.length -1];
console.log(Valor);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" id="Nombre" Maxlength=43 name="txtNombre" required>

Related

Javascript change value but inside onchange event listener not firing

I wrote a simple script to count words while typing in form
My question is why by changing the value of the word_count field when typing;
The EventListener of word_count is not fired
document.getElementById('subject').addEventListener('change', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
}, false);
document.getElementById('subject').addEventListener('keypress', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
}, false);
document.getElementById('word_count').addEventListener('change', function() {
alert('change fired');
}, false);
<form>
<div> <label for="story">string:</label>
<textarea id="subject" name="subject"></textarea>
</div>
<div> <label for="story">count:</label>
<input id="word_count">
</div>
</form>
try this(see console for result):
var old_count;
document.getElementById('subject').addEventListener('change', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
if(!old_count)old_count=words
else{
if(old_count!=words){
old_count=words
document.getElementById('word_count').dispatchEvent(new Event('change'));
}
}
// Dispatch/Trigger/Fire the event
document.getElementById('word_count').dispatchEvent(new Event('change'));
}, false);
document.getElementById('subject').addEventListener('keypress', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
if(!old_count)old_count=words
else{
if(old_count!=words){
old_count=words
document.getElementById('word_count').dispatchEvent(new Event('change'));
}
}
}, false);
document.getElementById('word_count').addEventListener('change', function() {
console.log('change fired:'+ old_count);
}, false);
<form>
<div> <label for="story">string:</label>
<textarea id="subject" name="subject"></textarea>
</div>
<div> <label for="story">count:</label>
<input id="word_count">
</div>
</form>
You could dispatch a change event on your input. Please check the example (https://codepen.io/alekskorovin/pen/dyVyepg):
document.getElementById('subject').addEventListener('change', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
}, false);
document.getElementById('subject').addEventListener('keypress', function() {
var string = this.value
string = string.replace(/\s+/g, " ");
var words = string.split(/\s+/).length;
document.getElementById('word_count').value = words;
const event = new Event('change'); document.getElementById('word_count').dispatchEvent(event);
}, false);
document.getElementById('word_count').addEventListener('change', function() {
alert('change fired');
}, false);
<form>
<div> <label for="story">string:</label>
<textarea id="subject" name="subject"></textarea>
</div>
<div> <label for="story">count:</label>
<input id="word_count">
</div>
</form>

Store text from dynamically created textareas in localStorage

Problem - I have 2 buttons addNew and submitText. I have created a javascript function for each of these two buttons. The addNewcreates textareas with unique ids (note0, note1...). The submitText is supposed to submit the text from all the dynamically created textareas in localStorage in the (key, value) format (notesList0, data), (notesList1, data) and so on. The code is as follows -
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
} , false);
});
The addNew works but submitText only saves value of the first textarea. Where am I going wrong?
I guess it's because of flag staying "false" after the first loop:
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
flag = true;
}
} , false);
});
Use the following for the submit function to make it work for dynamically created elements:
$(document).on("click", "#submitText", function(){
// Do stuff
})
Make sure the ID is only used once on the page. Otherwise switch to class definition.
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
for(counter=0; counter<=note_id; counter++) {
var flag=true;
var textData = $("#note"+counter).val();
if(textData != undefined && textData != '') {
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
}
} , false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="addNew">Add new</span>
<span id="submitText">Submit</span>
<div id="textFields"></div>
In case you get error when executing the code, check this link:
Failed to read the 'localStorage' property from 'Window'

remove character from input field while user is typing (keyup)

I'm looking for a js or jq way to remove # character while user is typing on a field.
I tried this:
$( function() {
$( ".remove-sharp" ).on( "keyup", function( event ) {
console.log( 'test' );
$( this ).val().replace( /\#/, "" );
} )
} );
I can see the "test" being printed in console but this has no effect on the characters in the field; it doesn't remove #. How to achieve this ?
The issue is because you're not setting the value of the input, only getting it and making the replacement and doing nothing with the resulting string. Try this:
$(function() {
$(".remove-sharp").on("keyup", function(event) {
var value = $(this).val();
if (value.indexOf('#') != -1) {
$(this).val(value.replace(/\#/g, ""));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="remove-sharp" />
function validateCustomerName(){
var validatedName = "";
var restrictedCharactersArray = ["0","1","2","3","4","5","6","7","8","9","~","`","!","#","#","$","%","^","&","*","(",")","-","_",
"+","=","{","}","[","]",":",";","'","<",">",",",".","?","/","/\/","|"];
var customerName = document.getElementById("customerName").value;
var numberValidation = (/^[a-zA-Z_ ]+$/g).test(customerName);
if(!numberValidation){
validatedName = "";
var customerNameArray = customerName.split("");
for(var i=0;i<restrictedCharactersArray.length;i++){
var restrictedCharacter = restrictedCharactersArray[i];
if(customerNameArray.indexOf(restrictedCharacter) !== -1){
for(var j=0; j<customerNameArray.length; j++){
var customerNameCharacter = customerNameArray[j];
if(customerNameCharacter !== restrictedCharacter){
validatedName = validatedName+customerNameCharacter;
}
}
}
}
document.getElementById("customerName").value = validatedName;
}
}
<input type="text" id="customerName" onKeyUp="validateCustomerName();" />

Disallow special characters in textbox validation

I have javascript code where the validation does not allow more than 20 characters in text box. But, I also want to disallow in special characters in the validation; how can this be accomplished.
Here is my current validation code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js">
/script>
<script type='text/javascript'>
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var len = desc.length;
if (desc.length >= 10)
{
this.value = this.value.substring(0, 10);
} $('#spntxt').text(10 - len + ' Characters Left');
});
}); </script>
try bellow script this will not allow special charter # $ % ^ & * ( )
function validate() {
var element = document.getElementById('input-field');
element.value = element.value.replace(/[^a-zA-Z0-9#]+/, '');
};
<input type="text" id="input-field" onkeyup="validate();"/>
I just use your codes and modify:
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var lastChar = desc.slice(-1);
var spc = !((lastChar.charCodeAt()>=48&&lastChar.charCodeAt()<=57)||(lastChar.charCodeAt()>=65&&lastChar.charCodeAt()<=90)||(lastChar.charCodeAt()>=97&&lastChar.charCodeAt()<=122));
if (desc.length >= 10 || spc)
{
this.value = this.value.substring(0, desc.length-1);
} $('#spntxt').text(10 - len + ' Characters Left');
});
});
You must use the keypress event
<input type="text" onkeypress="return isValidCharacter(event)" />
and define the javascript event, the validation can do it with regular expressions
function isValidCharacter(e) {
var key;
document.all ? key = e.keyCode : key = e.which;
var pressedCharacter = String.fromCharCode(e)
var regExp = /^[a-zA-ZÁÉÍÓÚáéñíóú ]*$/;
return regExp.test(pressedCharacter); }
If the method returns true the character will be printed
For Input Length, use Html5 Max Length Property
$(function(){
$('#QI4562040').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
$('#spntxt').text(10 - input_val.length + ' Characters Left');
});
});
<input type='text' name='' id='QI4562040' maxlength='10'/>
<div id='spntxt'></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources