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();" />
Related
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.fromCharCode() 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>
I want to write a script that would resize labels length if its longer than 30 characters, but can't find the reason why it stays the same.
jsfiddle:
http://jsfiddle.net/rokas_m/9g3bcamz/10/
HTML:
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
jQuery:
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
$( 'label' ).innerHTML = string;
console.log(string);
}
}
);
You can use .text() set the value by passing a callback function as its argument which will be called for each label, like
$('label').text(function(i, text) {
return text.length > 30 ? text.substr(0, 17) + '...' : text;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
Or
$('label').each(function() {
var string = $(this).text();
var ilgis = string.length; //reuse the variable
if (ilgis > 30) {
string = string.substr(0, 17) + '...';
$(this).html(string);//$(...) returns a jQuery object so don't have `innerHTML` property, also you need to target the current `label` not all of them
//or just
//this.innerHTML = string
console.log(string);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>labelislabelislabelislabelislabelislabelislabelis</label><Br/>
<label>kitaskitaskitaskitaskitaskitaskitaskitaskitaskitaskitas</label><br/>
<label>asdfasdfsadfasdfsdfdsftaskitaskitaskitas</label><br/>
<label>siaip</label><br />
<label>siaip</label><br />
<label>siaip</label><br />
Replace this $( 'label' ).innerHTML = string; with $(this).html(string);.
Here's the modified code:
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
$(this).html(string);
}
}
);
Refer this
$('label').each( function(){
var string = $(this).text();
var ilgis = $(this).text().length;
if (ilgis > 30){
var string = string.substr(0,17)+'...';
jQuery(this).html(string);
console.log(string);
}
}
);
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.
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>
I have textarea. Now, I want to do that once you write "#q + number#" ( e.g. #q1# ), it will create new input field.
For example if you write: "Hello my name is #q1# and my favorite food is #q2#". It will open two input fields.
And when you delete one of those #q + number#, it will delete the same field that was intended to the #q#
For example: if you write "Hello my name is #q1# and my favorite food is #q2#, and the input fields look like that:
<input type="text" q="1" />
<input type="text" q="2" />
and next that I delete the #q1# it supposed to look like that:
and don't delete the value of q="2" input.
How can I do that in jQuery/JavaScript?
Take a look at this quick fiddle http://jsfiddle.net/NgxvP/1/
Here you have something to start playing with
<html>
<head>
<style>
#inputField { position:relative;
width: 200px;
height: 200px;
background-color: #cda;
}
</style>
<script src="jquery-1.7.1.min.js"></script>
<script>
// in_array function provided by phpjs.org
function in_array (needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
return true;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
return true;
}
}
}
return false;
}
var addedFields = new Array();
function checkFields(input, charCode)
{
var text = (charCode) ? input.value + String.fromCharCode(charCode) : input.value;
var pattern = /#q[0-9]#/g;
var matches = text.match(pattern);
if (!matches) { matches = new Array(); }
if (addedFields.length>0 && addedFields.length != matches.length)
{
for (var index in addedFields)
{
if (!in_array('#q'+ index +'#', matches))
{
$('#q'+index).remove();
delete addedFields[index];
}
}
}
if (matches)
{
for (var i=0; i<matches.length; i++)
{
var code = matches[i];
var index = code.match(/[0-9]/)[0];
if ( $('#q'+index).length == 0 )
{
addFields(index);
}
}
}
}
function addFields(i)
{
addedFields[i] = true;
var fields = '';
for (var index in addedFields)
{
fields += '<input type="text" q="'+ index +'" id="q'+ index +'" />';
}
$('#inputField').html(fields);
}
</script>
</head>
<body>
<div id="formID">
<form>
<textarea onkeypress="checkFields(this, event.charCode); return true;" onkeyup="checkFields(this); return true;"></textarea>
<div id="inputField"></div>
</form>
</div>
</body>
</html>
EDITED: to avoid appending unordered input text fields, but showing them always ordered by their index, as commented in dfsq answer
I created a jsfiddle for your convenience http://jsfiddle.net/2HA5s/