For a project i need a initial textfield which use the every first letter of a forname and bornnames. So basically the field needs to autoformat the input by user. If i fill in my initials MGJ it needs to be M.G.J. (after every letter he must put in the point).
Be aware;
The webform made with Webform module Drupal, so i only could use css or Javascript.
Are there some easy option for that?
Regards,
Martijn
http://nosir.github.io/cleave.js/ you can use this library to format your input the easy way.
Or you can do it like this in JS
var input = document.querySelector('#initials');
input.addEventListener('focusout', function() {
this.value = this.value.split('').join('.');
})
<input type="text" id="initials" />
all you need to do is to split your string and then join with a dot.
string.split('').join('.');
Oke I allready found the solution my own; i used:
`$( document ).ready(function() {
if ($(".input")[0]){
$(".input").focusout(function() {
var initials = this.value.replace(/\./g,'');
this.value = initials.split('').join('.');
});
}
});
})( jQuery );`
Late answer; I needed the same thing but wasn't happy with the current answers.
document.getElementById('initialsOnly').addEventListener('keyup', function(e) {
if (e.code === 'Backspace') {
this.value = this.value.slice(0, -1);
} else {
const newString = this.value.replace(/[\W\d]/g, '').split('').join('.').toUpperCase();
this.value = newString + (newString.length > 0 ? '.' : '');
}
});
<input id="initialsOnly" type="text" />
Related
I am working with JQuery Filter and I am facing issue while searching string in span.
Following is the Search function which I am using:
function searchAccoms() {
var searchString = $('#searchval').val();
$('span.acc-head').each(function(){
var spanString = $(this).text();
if(spanString.search(searchString) == 1){
console.log('found');
}else{
console.log('Not Found');
}
});
}
HTML:
<input type="text" placeholder="Search" id="searchval" name="searchval">
<img src="images/icon_search.png" class="search-btn" type="submit" onclick="return searchAccoms();">
Scenario: I have following text in SPAN tag:
field
field
extra field
field1
field3
field2
Example SPAN:
<span id="18" class="acc-head"> field1</span>
When I search 'field' in the search box it works fine but when I search 'Field' the first letter in caps 'F' then it is not working. I am looking for %Field% like commend in MySQL.
Is there any other way to do the search?
Just make both strings either lowercase or uppercase to make the search case insensitive:
function searchAccoms() {
var searchString = $('#searchval').val();
$('span.acc-head').each(function(){
var spanString = $(this).text();
if (spanString.toLowerCase().search(searchString.toLowerCase()) == 1) {
console.log('found');
} else {
console.log('Not Found');
}
});
}
Another option would be to construct a regex, something like
var searchString = $('#searchval').val();
var regex = new RegExp(searchString, 'i');
...
if(spanString.search(regex) == 1)
but just making the strings the same case seems a lot easier
I guess if(spanString.match(searchString)) should do the work even if it returns an array .
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript)
Insert space after certain character into javascript string
I am trying to write a script that handles product keys like the ones you see on the back of software and games.
I would like so when the user is inputing their key code the '-' are inserted every 5 characters for 5 sets of characters. Ex(ABCDE-FGHIJ-KLMNO-PQRST-UVWXY). So when the user enters ABCDE as soon as the 'E' is enetered a '-' is inserted immeditly after via jQuery or JavaScript.
Thanks In Advance.
Comment if you have any questions or if I was unclear :)
Form:
<form method="post" action="process.php">
<p>Key: <input name="key" id="key" size="40"></p>
<p><input type="submit"></p>
</form>
You can use http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
});
HTML:
<fieldset id="productkey">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
</fieldset>
JavaScript:
$( '#productkey' ).on( 'keyup', 'input', function () {
if ( this.value.length === 5 ) {
$( this ).next().focus();
}
});
Live demo: http://jsfiddle.net/XXLND/3/show/
You can also enhance the code, so that when the last text-box is filled out, a processing mechanism is activated:
$( '#productkey' ).on( 'keyup', 'input', function () {
var $field = $( this );
if ( $field.val().length === 5 ) {
if ( $field.is( ':last-of-type' ) ) {
$field.blur();
processKey();
} else {
$field.next().focus();
}
}
});
Live demo: http://jsfiddle.net/XXLND/4/show/
Simply because I don't like JQuery :)
function insertSpace(string, part, maxParts) {
"use strict";
var buffer = string.split("-"), step, i;
for (i = 0; i < buffer.length; i += 1) {
step = buffer[i];
if (step.length > part) {
buffer[i] = step.substr(0, part);
buffer[i + 1] = step.substr(part) + (buffer[i + 1] || "");
} else if (step.length < part) {
if (i == buffer.length - 1) {
if (!step) {
buffer.pop();
}
} else {
buffer[i + 1] = step + (buffer[i + 1] || "");
buffer.splice(i, 1);
i -= 1;
}
}
}
buffer.length = Math.min(maxParts, buffer.length);
return buffer.join("-");
}
How about using http://digitalbush.com/projects/masked-input-plugin
With that plugin, the following:
jQuery(function($){
$("#key").mask("99999-99999-99999-99999-99999",{placeholder:" "});
});
or, if your key is all letters use:
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
or, if it's alpha/numeric use:
$("#key").mask("*****-*****-*****-*****-*****",{placeholder:" "});
Here's one approach:
// binds to both the 'keyup' and 'paste' events
$('input:text').on('keyup paste', function(e) {
var that = $(this), // caches the $(this)
val = that.val(), // access the value of the current input
key = e.which, // determines which key was pressed
allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing)
// backspace, delete, tab, shift
if ($.inArray(key, allowed) == -1) {
// if the pressed key is *not* an 'allowed' key
if (val.length == 5) {
// focuses the next element
that.next().focus();
}
else if (val.length > 5) {
// truncates the string, if greater than 5 characters
that.val(val.substring(0, 5));
that.next().focus();
}
}
});
JS Fiddle demo.
The advantage of this approach is that rather than masking or manipulating the entered string, and accounting for multiple edge-cases, you're simply aiding the user by moving the focus at the right point. And, in this case, also allowing the user to refocus the re-edit the previously entered data.
two things:
One the user experience side, I would avoid dynamically adding character in the input field as the user type a code. Depending on the environment you run the risk to interfere with what the user type.
However, the '-' helps user typing the code since this is a reference point for him. So I would suggest to have an input field and to show a pretty version of the code next to it (or make the field invisible and manage the focus of the field yourself).
For the php code, instead of adding a character every 5 characters I would do the opposite and simplify the code by removing all the unnecessary characters.
Something like that
if ( str_replace('-', '', $userInputKey)==str_replace('-', '', $officialKey) {
echo 'Yeah! Valid key!';
}
I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.
I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
newVal += val;
this.value = newVal;
});
http://jsfiddle.net/ssthil/nY2QT/
Since you're using jQuery you can try jquery masked-input-plugin.
There's a jsFiddle for you here where you can see how it works.
The source code for the project on GitHub can be found here.
The implementation is more than simple:
HTML:
<input id="ssn"/>
javascript:
$("#ssn").mask("999-999-999");
UPDATE:
Another good one can be found here.
As far as I can work out, all you really need to do is this:
$('#ssn').keyup(function()
{
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
});
but this will only work when people enter digits, so I'd suggest an introducing an extra check:
$('#ssn').keyup(function(e) {
if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode < 106 && e.keyCode > 95)) {
this.value = this.value.replace(/(\d{3})\-?/g, '$1-');
return true;
}
//remove all chars, except dash and digits
this.value = this.value.replace(/[^\-0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ssn">
A little more on the regex /(\d{3})\-?/g: This replaces group of 3 digits with itself, followed by a dash. The brackets create a back reference to the matched digits, that is used in the replacement string ($1- -> $1 being the back reference).Note that an optional dash is replaced, too, but not included in the back reference. if the input is 123, and the replace pattern would be something like /(\d{3})/g, or /(\d{3}\-?)/g the value would become 123-4, 123--45, 123---456 and so on, doubling the dashes each time.
Warning:
This will give the user some grief, since the arrow keys and such won't work.Luckily, that's an easy fix: Just add the following code at the top of your function:
if (e.keyCode > 36 && e.keyCode < 41)
{
return true;
}
And the arrows work just fine. for other keys (such as delete, backspace, shift etc...) check this page.
For a full example: here's the fiddle
For the formatting XXX-XXX-XXXX here is a simple solution:
if(this.value.trim().length <= 8){
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
}
Here is an example and you not need any framework or library or npm:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}
}
You could also do this if you like:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}else{
this.phone.value = this.phone.value.replace(/(\d{4})\-?/g,'$1');
}
}
Replace this this.phone with your value.
I hope this helps.
I found this question while googling for a way to auto-format phone numbers in Javascript. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.
Problem
I would like my phone number html input field to auto-format (mask) the value as the user types.
Solution
Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.
Formatting a phone number is as easy as:
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
for(i=0;i<2;i++){
if (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
this.value = newVal;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ssn" maxlength="10"/>
You can set input mask on any field in 3 simple steps:
1: First of all call these libraries
http://code.jquery.com/jquery-1.7.2.min.js"
"https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"
2: Create simple form like this :
<form> <input type="text" name="phone" id="phone" /> </form>
3: Then the script code past into your script tag..
$(document).ready(function($) {
$('#phone').mask("99999-9999999-9",{placeholder:""});
});
Is there any way to append a text to input field?
So lets say instead of:
<input type="text" id="val" name="val" value="http://" style="width: 140px;" />
with "http://" already written, have a "http://" added automatically when someone types an address, and if someone types full url "http://www.****.com" the http should not be added so it's not doubled.
Any one has any ideas? I can't use php.
Why not just add the http:// if it is missing?
var input = document.getElementById('val').value;
if (input.search('http://') === -1) {
input = 'http://' + input;
}
edit: if you need to allow https also, change the search to a regex:
if (input.search(/https?:\/\//) === -1) {
http://jsfiddle.net/jbabey/Bt67X/
I strongly suggest using a scripting framework, e.g. jQuery (http://jquery.com) to access the input field.
See here:
http://jsfiddle.net/5BLrU/
Here is the JS code for reference
$(function() {
$("#some-form").submit(function(){
var $val = $("#val");
var url = $val.val();
if (!/^http:\/\/.+/.test(url)) {
$val.val("http://" + url);
}
// remove this to submit the form!
return false;
});
});
The following example assumes the ID of the target element is val.
// Store current element
var elem = document.getElementById('val'),
// Store current value
currentValue = elem.value;
// Prepend something if not present
if (currentValue.match(/^http:\/\//) == false) {
currentValue = 'http://' + currentValue;
}
// Re-assign
elem.value = currentValue;
Append:
document.getElementById('val').value += "http://www.google.co.uk";
Remove Duplicate:`
document.getElementById('val').value.replace("http://http://","http://");
This way, if they did type http:// twice, it would just remove it.
hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]