I want to add space after every 3rd number, but this code doesn't work if the input is type="number". Does someone know how to modify the code to make it work even for type="number"
? Here is my input:
<input type="number" id="phone" autocomplete="off" placeholder="(+420)">
And also here is the script:
<script>
document.getElementById('phone').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim();
});
</script>
Try this:
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
Use in your event:
this.value=insertBlankAfterEveryThreeCharacters(this.value);
document.getElementById('phone').addEventListener('input', function (e) {
this.value=insertBlankAfterEveryThreeCharacters(this.value);
});
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
<input id="phone">
<input type="number"... makes it so you can go up/down one = I assume not an intended result...
Your place holder has parentheses and a plus in it - It is not what you seem to be wanting in the solution...
Related
I want to load the page http://example.com by typing trigger in the <input> text box. I made some modifications over time, and at some point it seemed to work but now it doesn't.
How can I make this work? What are some errors that I am missing?
window.onload = function() {
var input = document.getElementById("idname").focus();
}
$(function() {
var triggerWords = ['trigger'];
$('#indexinput').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
You are registering on keyup two times, following code will work. Dont need to register it with javascript if you are mentioning it inline HTML.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
<script>
window.onload = function() {
var input = document.getElementById("idname").focus();
}
function myFunction(event) {
var triggerWords = ['trigger'];
for (let i = 0; i < triggerWords.length; i++) {
if (event.target.value == triggerWords[i]) {
window.open("http://example.com/", "_self");
break;
}
}
}
</script>
You have the wrong id in the query selector. It says
$('#indexinput') but must be $('#idname').
Consider using the following snippet:
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
console.log('open new page');
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>
Note that the window.open doesn't work in code-snippets, therefore I added the console.log part.
I also removed this unnecessary part:
window.onload = function() {
var input = document.getElementById("idname").focus();
}
There is no need of myFunction and id was incorrect
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() === triggerWords[i]) {
window.open("https://google.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>
I have an input where the user can enter initials. The input has a max length of 3.
I have the following js
personaliseShirt.plInitials = function () {
console.log('pressed');
var inputPL = $('.max-length_3');
$(inputPL).on('keyup', function () {
var max = 3;
console.log(inputPL.val.length);
if (inputPL.val.length > max) {
inputPL.val = inputPL.value.substring(0, max);
}
})
}
My issue is that the first input field seems to stop the user from entering more than 3 characters but if the user has multiple, then after the first input the rest allow for more than 3 :/
HTML for input field
<input onkeyup="this.value = this.value.toUpperCase();" pattern="[A-Za-z]+" maxlength="3" type="text" class="form-control input-block-level defaultY? max-length_3" max="3" value="" placeholder="Enter Player Initials" name="player_2_9_6" id="player_2_9_6">
Any help or suggestions would be great
Thanks in advance!
Your variable inputPL is a JQuery array with multiple elements in it. In your keyup handler, you check for the length of this array, which won't work. Use this instead:
personaliseShirt.plInitials = function () {
console.log('pressed');
var inputPL = $('.max-length_3');
$(inputPL).on('keyup', function () {
var max = 3;
var $thisElem = $(this);
console.log($thisElem.val.length);
if ($thisElem.val.length > max) {
$thisElem.val = $thisElem.value.substring(0, max);
}
})
}
Also please check, if your mix-up of val and value is intended, or if you need to use val() instead.
It's working on firefox and chrome. You can use this function for repeated use.
$('input.testinput').on('keyup', function() {
limitText(this, 3)
});
function limitText(field, maxChar){
var ref = $(field),
val = ref.val();
if ( val.length >= maxChar ){
ref.val(function() {
console.log(val.substr(0, maxChar))
return val.substr(0, maxChar);
});
}
}
Demo
I cannot see where I am going wrong with this. My code is...
function firstC()
{
var x = document.getElementsByClassName("uValue");
for(var i = 0; i < x.length; i++) {
x.value.charAt(0).toUpperCase();
}
}
It is called by...
<td><input type="text" name="firstname" value="(required)" id="firstName" class="uValue" onclick="empty(this.id)" onblur="firstC()" /></td>
The empty() function works correctly by removing the value of the input box if its value is "(required)", but I cannot get the firstC() function to capitalise the first character of any input.
EDIT: I am using getElementsByClassName as there are multiple input boxes which I am trying to allow to use the same function.
You forgot to assign the value back
function firstC()
{
var x = document.getElementsByClassName("uValue");
for(var i = 0; i < x.length; i++) {
x[i].value = x[i].value.charAt(0).toUpperCase() + x[i].value.substr(1);
}
}
You should instead pass the this into your inline JS eventers:
onclick="empty(this)" onblur="firstC(this)"
Example
function empty(el) { // el now refers to the this referrer
el.value="";
}
function firstC(el) {
var val = el.value;
el.value = val.charAt(0).toUpperCase() + val.substr(1);
}
<input type="text" onclick="empty(this)" onblur="firstC(this)" value="(required)" id="firstName" class="uValue" name="firstname">
P.S: don't forget that instead of using empty() and value="(required)" you can simply use the placeholder attribute
placeholder="(required)"
in my process text filed in array i need to get the value via javascript but my code is not working my code following
<input type="text" id="itemid[]" name="itemid[]" class="span12"/>
and javascript code is
function getstock()
{
var itemidarr=document.getElementById('itemid[]');
if(itemidarr!= null)
{
alert(itemidarr.length);
}
}
any other solution for this
The IDs can't contain brackets, these: [], so:
<input type="text" id="itemid1" name="itemname1" class="span12"/>
<input type="text" id="itemid2" name="itemname1" class="span12"/>
<input type="text" id="itemid3" name="itemname1" class="span12"/>
Then you have to loop through the IDs:
function getstock()
{
for(var i=1; i<=3; i++){
var itemidarr=document.getElementById("itemid"+i);
if(itemidarr!= null) alert(itemidarr.length);
}
}
The id attribute here cannot contain [ ].
Put your textboxex in "fieldset tag"
Like:
<fieldset id="field">
//Put you text boxes here<input type='text'>
</fieldset>
Access these by:
document.getElementById("list....").getElementsByTagName("input")[indexoftext];
indexoftext is the text box you wan to choose.
Hope it helps!
you can try something like this below
<input type="text" id="itemid" name="itemid" class="span12"/>
function getstock()
{
var itemidarr = document.getElementsByName('itemid');
for(var i = 0; i < itemidarr.length; i++){
var item=document.getElementsByName('itemid')[i].value;
if(item!= null)
{
alert(item);
}
}
}
You can't make an array to fill in an input text, only for input like radio or checkbox.
Text input only accept a single string.
function getstock() {
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
can u use this code
i got the result
function getstock1()
{
alert("test");
var itemidarr = document.getElementsByName('itemid[]');
for (var i = 0; i < itemidarr.length; i++)
{
alert(itemidarr[i].value);
}
I have a little bit of javascript that counts the amount of words on a box. The javascript looks like this:
<script type="text/javascript">
function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}
x.value=r;
if (r > 60) {
x.value='Please reduce the word count';
}
}
</script>
and the form like this:
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform" onKeyUp="cnt(this,document.brochure.c)"><?php echo $row['freebrochureentryform']; ?></textarea>
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" value="0" size="20" onKeyUp="cnt(document.brochure.freebrochureentryform,this)" />
Basically the bottom input field shows the amount of words in the upper one. But it only does so when you click on the upper box "freebrochureentryform", but i want it to load the amount of words as soon as the page loads not when you click the box. I guess it is to do with
onKeyUp="cnt(document.brochure.freebrochureentryform,this)"
But have no idea what to change it to.
(Btw way Brochure is the name of my form.)
Any help greatly appreciated.
Ian
You can call the cnt() function on window.onload event.
And instead of listening to onkeyup event, you can listen to the more appropriate oninput (or onpropertychange for IE) event:
JSFiddle
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform">Lorem Text</textarea>
<br />
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" id="c" value="0" size="20" />
window.onload=function(){
function cnt(area,output){
var txt=area.value.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ").split(" ");
if(txt.length>10){
output.value="Please delete some word";
}else{
output.value=txt.length;
}
}
var textarea=document.getElementById("freebrochureentryform");
var info=document.getElementById("c");
if("addEventListener" in window){
if("oninput" in textarea){
textarea.addEventListener("input",function(){
cnt(textarea,info);
},false);
}else if("onpropertychange" in textarea){
textarea.addEventListener("propertychange",function(e){
if((e||event).propertyName=="value"){
cnt(textarea,info);
}
},false);
}else{
textarea.addEventListener("change",function(){
cnt(textarea,info);
},false);
}
}else{
textarea.attachEvent("onpropertychange",function(){
if(event.propertyName=="value"){
cnt(textarea,info);
}
});
}
cnt(textarea,info);
};
Some instruction:
var txt=area.value
.replace(/^\s+|\s+$/g,"") means to trim;
.replace(/\s+/g," ") combines series of white spaces (including line feeds) into one (to better split without the need to iterate the splitted array);
.split(" ") split by white space (as you have already done).
oninput is introduced in IE9 but has some buggy behavior, so you may want to try onproperychange first;
putting function cnt() and textarea/info in window.onload makes them "safe" inside the closure. They can't pollute the global namespace, and things in global namespace can not pollute them.
try to call cnt(w,x) on body onload event
onKeyUp triggers only on User Interaction.
If you load the side there is no Event KeyUp
so instead. Trigger it manually.
call cnt(document.brochure.freebrochureentryform,document.brochure.c) on your body manually (or onload)
function countWords(str) {
let arr = str.split(' ');
let count = 0;
if(arr.length > 0){
for (let i = 0; i< arr.length - 1; i++){
let sentence = arr[0];
let bool = true;
for(let j = 0; j < sentence.length - 1; j++){
let charcode = arr[i].charCodeAt(j);
if((charcode > 64 && charcode < 91) || (charcode > 96 && charcode < 123)){
bool = false;
}
}
if(bool == true){
count += 1;
}
}
}
return arr.length - count;
}
//function calling
countWords("he is a good programer, he won 865 competitions, but sometimes he dont.
what do you think? all test-cases should pass. done-done?");