I need to be able to add a dash before the last three characters in a text field using either javascript or php. For example, the user enters 1dsb3rs and the input changes to 1dsb-3rs. It doesn't matter if the user sees the change (javascript) or if it happens server-side (PHP) I just need the change to happen.
I have already tried this javascript code, but I can't get it to work:
$("#rid").html(function(i,v){
return v.replace( /^([\w]{4})/, "$1-" );
Here is my textbox code:
<input class="form-control" type="text" id="rid" placeholder="Enter ID" size="15px" maxlength="10" name="rid" required value="<?php echo $rid; ?>">
To do this server-side (assuming data is POST-ed):
if (isset($_POST['rid']))
{
$value = $_POST['rid'];
if (strstr($value, '-') === false)//if no dash is in the $value string
$value = substr($value, 0, -3).'-'.substr($value, -3);//get string minus last 3 chars, add dash, then add last 3 chars
}
Or client-side using JavaScript (using, for example the change event)
document.querySelector('#rid').addEventListener('change', function()
{
if (this.value > 3)
this.value = this.value.replace(/(.{3}$)/, '-$1');
}, false);
This pattern replaces the last 3 chars with a dash, followed by those very same last 3 chars. See the fiddle
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
String.prototype.addDash = function () {
return this.splice( -3, 0, '-' );
};
document.getElementById('myinput').addEventListener('keyup', function (e) {
this.value = this.value.replace(/\-/gi, '');
if (this.value.length >= 4) {
this.value = this.value.addDash();
}
});
Working demo : http://jsfiddle.net/seancannon/2xLFy/2/
You can't use html() method on a form control. You need to use val().
Try:
$("#rid").val(function(i,v){
v.replace( /^([\w]{4})/, "$1-" );
});
jQuery val() API docs
I think this should work for you in javascript.
var addDash = function(str){
var chars = str.split("");
chars.splice(chars.length-3,0,'-');
return chars.join('')
}
call this function with string.
addDash('string');
Output
str-ing
Related
I am having a problem with regular expression in javascript. What i am trying to do is a form register in which i must validate the first name so i decided to go with javascript validation (can you please tell me if going with js is the better option or going with ajax php reg validation?). So I wrote my code by checking some tutorials and reading from google but i am still having a problem. It is not working ! It runs on blur event using jquery so I need your help please to do this.
The pattern i am trying to check is for special characters in the user input
/[\'^£$%&*()}{##~?><>,|=_+]+$/g;
here is my script:
$(document).on('blur','.first_name_input', function() {
var firstNameInput = $(".first_name_input").val();
if (firstNameInput !== '') {
//var exp = /[a-zA-Z0-9-]+$/g;
var exp = /[\'^£$%&*()}{##~?><>,|=_+]+$/g;
//if (firstNameInput.test(/^[\'^£$%&*()}{##~?><>,|=_+-]+$/)) {
//if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
if (firstNameInput.match(exp)) {
var firstnameValidity = "<div class='name_not_valid_div'>× Not allowed characters present!</div>";
$('body').prepend(firstnameValidity);
$(".name_not_valid_div").hide().fadeIn('slow');
if (!errorArray.includes("firstName")){
errorArray.push("firstName");
}
} else {
$(".name_not_valid_div").hide();
if (errorArray.includes("firstName")){
for(var i = errorArray.length - 1; i >= 0; i--) {
if(errorArray[i] === "firstName") {
errorArray.splice(i, 1);
}
}
}
}
}
});
and my html code is :
<tr>
<td class="label">First Name: </td>
<td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
</tr>
1st: use .trim() to avoid left/right whitespaces or even the spaces without any characters $(".first_name_input").val().trim();
2nd: for validation
// if the string has special characters
function string_has_spec_char(str){
var reg = /[~`!##$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
var reg = /\s/g;
return reg.test(str);
}
and use it like
if(string_has_spec_char(firstNameInput) === false){
// the first name doesn't have special characters
}
if(string_has_spaces(firstNameInput) === false){
// the first name doesn't have spaces
}
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);
I am validating user input where it should accept only 6 digits or OB followed by 8 digits only.
It works very fine for digits but when I enter any alphabet (other than O) for first time it shows "undefined" in the input text box. How to overcome this? I have initialize all variables and tried changing regular expression(/[OB0-9]*/) also but nothing is working.
Here is my jsp code with RegEx:
<input type="text" value="<c:out value='${bookingPathView.extraAANumber}'/>" name="businessExtrAA" id="enterPassengerDetailsForm.businessExtrAA" size="17" maxlength="10" pattern="[OB0-9]*" class="forceWidth-phone forceWidth6" />
Here is my Javascript code
var keepBusinessExtraMaxLength = function () {
var input = [];
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").each(function(i) {
input[i]=this.defaultValue;
jQuery(this).data("idx",i);
});
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").on("keyup", function (e) {
var field = jQuery(this);
var val=this.value;
var maxLength=isNaN(jQuery(field).val()) ? Number(jQuery(field).attr("maxlength")) : 6;
var thisIndex=jQuery(field).data("idx");
if (this.validity && this.validity.badInput || jQuery(field).is(":invalid") ) {
this.value = input[jQuery(thisIndex)];
return;
}
if (val.length > maxLength) {
val=val.slice(0, maxLength);
jQuery(field).val(val);
}
input[jQuery(thisIndex)]=val;
});
}
Your Regex seems to be matching only the characters , O, B and other numbers...
To make it match
6 digits or OB followed by 8 digits only
You can use this regex: ^(?:[0-9]{6}|OB[0-9]{8})$
Demonstration: http://www.regexpal.com/?fam=96586
I have a field 12345, I need submit a form automatic when I type the last digit, 5...
How can a do it with javascript?
I saw someone created a jquery result but here is one in plain javascript
<input type="text" onkeyup="submitForm(this.value)">
function submitForm(str){
if(str.length=5){
document.forms["myform"].submit();
}
}
Or this:
$('input[type=text]').on('keyup', function(){
if($(this).val().length == 5){
alert('5 digit!');
//$('#myform').submit();
}
});
$('.input').change(function() {
if ($(this).val().length >= 5) {
$('.Form').submit();
}
});
$('#input').keyup(function(){
var content = new String( $(this).val() );
if( content.length > 4 ){
/* do your stuff here */
}
});
http://jsfiddle.net/3xHsn/
$("#foo").keyup(function(){
var val = $(this).val();
if (val.length == 5 && Number(val)){
$("form").submit();
}
});
This will only submit if the value is 5 digits and is a valid number. An alternative would be to use regex to validate the value as a zipcode.
The regex solution can be found here: http://jsfiddle.net/3xHsn/1/
$("#foo").keyup(function(){
var val = $(this).val();
var regex = /^\d{5}$/;
if (val.match(regex)){
$("form").submit();
}
});
The regex is pretty simple here and only checks that the string is exactly five digits and only five digits.
this solution assumes you have the maxlength attribute set accordingly. it also uses the 'input' event, which in my experience is far more reliable than keypress, keyup, etc.
html:
<form id="theform" action="gfdgf">
<input id="someid" type="text" maxlength="5"/>
</form>
jQuery:
$(document).on('input','#someid',function() {
var that=$(this);
if (that.val().length==that.attr('maxlength')) {
that.closest('form').submit();
}
});
Fiddle