I want to implement a text input with the following implementations:
Only allow numbers
Limit numbers from 0 - 255
If an 'illegal' character was entered (non numbers, or over or under 255), the input should get disabled, wait a second, then delete the invalid char, and get back to focus.
I got all that implemented thanks to this answer. There's an issue though. If you enter 35 (that's 'legal'), then move the cursor between 3 and 5, then enter 1, which comes out to 315. That becomes 'illegal' because it's more than 255. So the 5 gets deleted. I don't want the 5 to get removed, I want the 1 to get deleted because that was the last one entered.
But if you enter 31, then 5, 5 should get removed. Basically, I want the last number entered to get deleted when an illegal amount gets inserted.
Also, I want the cursor to go to the position of the last removed character, whether it's a number or letter.
Here's the code:
JSFiddle
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
if (checks[0]) {
el.value = el.value.replace(/\D/g, '');
}
if (checks[1]) {
el.value = el.value.slice(0, 2);
};
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keyup(function(e) {
disableInput(this)
$(this).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
You can use selectionStart and selectionEnd to see where the cursor is in the input and then use those values to remove the correct character.
Fiddle: http://jsfiddle.net/o4bz0wr7/3/
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
if (checks[0] || checks[1]) {
el.value = el.value.slice(0, el.selectionStart - 1) + el.value.slice(el.selectionEnd);
}
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keyup(function(e) {
disableInput(this)
$(this).focus();
});
EDIT: You can set the cursor position using setSelectionRange.
Fiddle: http://jsfiddle.net/o4bz0wr7/7/
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
var start = el.selectionStart - 1;
if (checks[0] || checks[1]) {
el.value = el.value.slice(0, start) + el.value.slice(el.selectionEnd);
}
$(el).dequeue("disabled").val(el.value).focus();
el.setSelectionRange(start, start);
}, 1000)
}
}
This should work fine with you, however if there is still any problem add it in comment.
Check it out in action here
var which = null;
function disableInput(el, $which) {
console.log(el.value);
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
console.log(String.fromCharCode($which));
el.value = el.value.replace($which, '');
// el.value = el.value.slice(0,el.value.length - 1);
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keypress(function(e) {
which = String.fromCharCode(e.which);
$(this).focus();
}).keyup(function(){
disableInput(this, which);
})
Related
This is a continuation of This
I used setTimeout() to place cursor on the input fields on pressing the tab, without which the focus goes to a link outside the <div> for some reason I am not aware of.
setTimeout() fixed that issue, but now:
On clicking on submit button the form does nothing but place cursor on the input fields for three or four times then proceeds with submitting.
Here is the submit button functions
$(“#submitbtn”).click(function(e) {
console.log(“click”);
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
startValidation();
});
e.stopPropagation();
e.cancelBubble = true;
});
Here is hover function for Submit button
$(“#submitbtn”).mouseover(function(e) {
console.log(“Hover”);
removeTimeouts();
$(“#submitbtn”).focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
The function removeTimeouts() has all clearTimeout() for all setTimeout() through out the JavaScript file.
But somehow the click function is never works until third or fourth try.
The hover function works on first mouse move though, it prints “Hover” on console, every time the mouse it moves over submit button.
Even after clearing all setTimeout() somehow the focus is moved to input fields instead of proceeding with the console.log() onclick.
Can someone help me understand the issue and help fix the form gets submitted on first click?
Update:
1) This is typed from mobile app, even after re-editing the quote appearing as “” It’s correct in my code just not here.
2) Focus and timeout event is to validate the input fields while moving out of the input field, like if the field is empty, the cursor won’t move to next input field. But just focus is not working, and tab just takes the cursor out of the input fields to a link below it, so time-out helps keeping the cursor the input field.
3) Snippet - This does not replicate the issue as this is by far I can post the code sorry :(
(function ($) {
// Behind the scenes method deals with browser
// idiosyncrasies and such
$.caretTo = function (el, index) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move("character", index);
range.select();
} else if (el.selectionStart != null) {
el.focus();
el.setSelectionRange(index, index);
}
};
// Another behind the scenes that collects the
// current caret position for an element
// TODO: Get working with Opera
$.caretPos = function (el) {
if ("selection" in document) {
var range = el.createTextRange();
try {
range.setEndPoint("EndToStart", document.selection.createRange());
} catch (e) {
// Catch IE failure here, return 0 like
// other browsers
return 0;
}
return range.text.length;
} else if (el.selectionStart != null) {
return el.selectionStart;
}
};
// The following methods are queued under fx for more
// flexibility when combining with $.fn.delay() and
// jQuery effects.
// Set caret to a particular index
$.fn.caret = function (index, offset) {
if (typeof(index) === "undefined") {
return $.caretPos(this.get(0));
}
return this.queue(function (next) {
if (isNaN(index)) {
var i = $(this).val().indexOf(index);
if (offset === true) {
i += index.length;
} else if (typeof(offset) !== "undefined") {
i += offset;
}
$.caretTo(this, i);
} else {
$.caretTo(this, index);
}
next();
});
};
// Set caret to beginning of an element
$.fn.caretToStart = function () {
return this.caret(0);
};
// Set caret to the end of an element
$.fn.caretToEnd = function () {
return this.queue(function (next) {
$.caretTo(this, $(this).val().length);
next();
});
};
}(jQuery));
var allTimeouts = [];
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
}
function removeTimeouts(){
for(var i = 0; i < allTimeouts.length; i++) {
clearTimeout(allTimeouts[i]);
}
}
function focusInNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
//$("#number" + thisID).prop("disabled", false);
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
});
allTimeouts.push(s);
if(preID != 0) {
if($("#number" + preID).val().length <= 0) {
var s = setTimeout(function() {
placeCursor($("#number" + preID));
});
allTimeouts.push(s);
}
}
}
function focusOutNumber (id) {
var thisID = id;
var nextID = id + 1;
var preID = id - 1;
var value = $("#number" + thisID).val();
var regex = new RegExp(/^\d*$/);
var regex1 = new RegExp(/^.*[\+\-\.].*/);
var l = $("#number" + thisID).val().length;
if(!value.match(regex)) {
alert("Just enter numerical digits");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if (l<=0) {
alert("This field cannot be empty");
var s = setTimeout(function() {
placeCursor($("#number" + thisID));
},5000);
allTimeouts.push(s);
} else {
if(value.match(regex)) {
var s = setTimeout(function() {
placeCursor($("#number" + nextID));
}, 100);
allTimeouts.push(s);
}
}
}
}
$(document).ready(function(){
$("#number1").focusin(function(){
focusInNumber(1);
});
$("#number1").focusout(function(){
focusOutNumber(1);
});
$("#number2").focusin(function(){
focusInNumber(2);
});
$("#number2").focusout(function(){
focusOutNumber(2);
});
$("#number3").focusin(function(){
focusInNumber(3);
});
$("#number3").focusout(function(){
focusOutNumber(3);
});
$("#number4").focusin(function(){
focusInNumber(4);
});
$("#number4").focusout(function(){
focusOutNumber(4);
});
$("#submitbtn").click(function(e) {
console.log("click");
e.preventDefault();
var s = setTimeout(function() {
removeTimeouts();
alert("startValidation()");
});
e.stopPropagation();
e.cancelBubble = true;
});
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
});
.SubmitBtn {
width: 100%;
background-color: #cccccc;
}
.Submitbtn:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="reqField" id="number1" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number2" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number3" placeholder="Enter Number only"></input>
<input type="number" class="reqField" id="number4" placeholder="Enter Number only"></input>
<div id="submitbtn" class="SubmitBtn">Submit</div>
After breaking my head and console.log on all the statement to figure out the flow of code, I was able to find that on $("#submitbtn").click() there is some .focusout() is called.
As these .focusout() were necessary for on the go validation on the <input> fields, i tried to add $.(":focus").blur() and it worked along with adding a return false; on placeCursor() function.
The $.(":focus").blur() removes focus from any currently focused element. And this is a live saver for our logic of code.
So the code looks like
$("#submitbtn").mouseover(function(e) {
console.log("Hover");
$.(":focus").blur();
removeTimeouts();
$("#submitbtn").focus();
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
});
....
function placeCursor(id) {
id.focus(function(e) {
e.stopPropagation();
//e.cancelBubble();
id.caretToEnd();
});
id.focus();
return false;
}
Hope this helps someone someday.
Thank you!
I am trying to use typed.js to give example cities in this text input box. My goal is to have it completely stop the animation when it is clicked on. How would I go about this?
This is my attempt at it.
JS:
$(document).ready(function(){
$(function()
{
$("#input_text").typed(
{
strings: ["^2000", "New York City^2000", "Berlin^2000", "London^2000", "Hong Kong^2000", "Chicago^2000", ""],
typeSpeed: 50
});
});
$( "#input_text" ).click(function()
{
$( "#input_text" ).stop();
});
});
I'm pretty new to javascript so could you please tell me how to accomplish my goal?
From the source code:
Start & Stop currently not working
So If you need to stop by hand a trick that I do not suggest you is to remap external the timeout function this plugin use or fork the plugin itself (this is my suggestion).
For manipulating the timeout externally you can do something like:
var _setTimeout;
var _clearTimeout;
var _pauseOn;
_setTimeout = window.setTimeout;
_clearTimeout = window.clearTimeout;
window.setTimeout = function(code, delay) {
return _setTimeout(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearTimeout = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearTimeout(intervalId);
};
function pauseTimer() {
_pauseOn = true;
}
........
$( "#input_text" ).click(function() {
pauseTimer();
});
In the following the snippet.
//-----------------------
// avoid or fork
//
var _setTimeout;
var _clearTimeout;
var _pauseOn;
_setTimeout = window.setTimeout;
_clearTimeout = window.clearTimeout;
window.setTimeout = function(code, delay) {
return _setTimeout(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearTimeout = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearTimeout(intervalId);
};
function pauseTimer() {
_pauseOn = true;
}
//-----------------------
// avoid or fork
//
$(function () {
$("#input_text").typed({
strings: ["^2000", "New York City^2000", "Berlin^2000", "London^2000", "Hong Kong^2000", "Chicago^^2000", ""],
typeSpeed: 50
});
$( "#input_text" ).click(function() {
pauseTimer();
$( "#input_text").val('');
});
});
input{
font-size:3em;
}
.typed-cursor{
opacity: 1;
-webkit-animation: blink 0.7s infinite;
-moz-animation: blink 0.7s infinite;
animation: blink 0.7s infinite;
}
#keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
#-webkit-keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
#-moz-keyframes blink{
0% { opacity:1; }
50% { opacity:0; }
100% { opacity:1; }
}
<script src="//code.jquery.com/jquery-1.11.3.js"></script>
<script>
// The MIT License (MIT)
// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
! function($) {
"use strict";
var Typed = function(el, options) {
// chosen element to manipulate text
this.el = $(el);
// options
this.options = $.extend({}, $.fn.typed.defaults, options);
// attribute to type into
this.isInput = this.el.is('input');
this.attr = this.options.attr;
// show cursor
this.showCursor = this.isInput ? false : this.options.showCursor;
// text content of element
this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text()
// html or plain text
this.contentType = this.options.contentType;
// typing speed
this.typeSpeed = this.options.typeSpeed;
// add a delay before typing starts
this.startDelay = this.options.startDelay;
// backspacing speed
this.backSpeed = this.options.backSpeed;
// amount of time to wait before backspacing
this.backDelay = this.options.backDelay;
// div containing strings
this.stringsElement = this.options.stringsElement;
// input strings of text
this.strings = this.options.strings;
// character number position of current string
this.strPos = 0;
// current array position
this.arrayPos = 0;
// number to stop backspacing on.
// default 0, can change depending on how many chars
// you want to remove at the time
this.stopNum = 0;
// Looping logic
this.loop = this.options.loop;
this.loopCount = this.options.loopCount;
this.curLoop = 0;
// for stopping
this.stop = false;
// custom cursor
this.cursorChar = this.options.cursorChar;
// shuffle the strings
this.shuffle = this.options.shuffle;
// the order of strings
this.sequence = [];
// All systems go!
this.build();
};
Typed.prototype = {
constructor: Typed
,
init: function() {
// begin the loop w/ first current string (global self.strings)
// current string will be passed as an argument each time after this
var self = this;
self.timeout = setTimeout(function() {
for (var i=0;i<self.strings.length;++i) self.sequence[i]=i;
// shuffle the array if true
if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);
// Start typing
self.typewrite(self.strings[self.sequence[self.arrayPos]], self.strPos);
}, self.startDelay);
}
,
build: function() {
var self = this;
// Insert cursor
if (this.showCursor === true) {
this.cursor = $("<span class=\"typed-cursor\">" + this.cursorChar + "</span>");
this.el.after(this.cursor);
}
if (this.stringsElement) {
self.strings = [];
this.stringsElement.hide();
var strings = this.stringsElement.find('p');
$.each(strings, function(key, value){
self.strings.push($(value).html());
});
}
this.init();
}
// pass current string state to each function, types 1 char per call
,
typewrite: function(curString, curStrPos) {
// exit when stopped
if (this.stop === true) {
return;
}
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
var self = this;
// ------------- optional ------------- //
// backpaces a certain string faster
// ------------------------------------ //
// if (self.arrayPos == 1){
// self.backDelay = 50;
// }
// else{ self.backDelay = 500; }
// contain typing function in a timeout humanize'd delay
self.timeout = setTimeout(function() {
// check for an escape character before a pause value
// format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
// single ^ are removed from string
var charPause = 0;
var substr = curString.substr(curStrPos);
if (substr.charAt(0) === '^') {
var skip = 1; // skip atleast 1
if (/^\^\d+/.test(substr)) {
substr = /\d+/.exec(substr)[0];
skip += substr.length;
charPause = parseInt(substr);
}
// strip out the escape character and pause value so they're not printed
curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip);
}
if (self.contentType === 'html') {
// skip over html tags while typing
var curChar = curString.substr(curStrPos).charAt(0)
if (curChar === '<' || curChar === '&') {
var tag = '';
var endTag = '';
if (curChar === '<') {
endTag = '>'
} else {
endTag = ';'
}
while (curString.substr(curStrPos).charAt(0) !== endTag) {
tag += curString.substr(curStrPos).charAt(0);
curStrPos++;
}
curStrPos++;
tag += endTag;
}
}
// timeout for any pause after a character
self.timeout = setTimeout(function() {
if (curStrPos === curString.length) {
// fires callback function
self.options.onStringTyped(self.arrayPos);
// is this the final string
if (self.arrayPos === self.strings.length - 1) {
// animation that occurs on the last typed string
self.options.callback();
self.curLoop++;
// quit if we wont loop back
if (self.loop === false || self.curLoop === self.loopCount)
return;
}
self.timeout = setTimeout(function() {
self.backspace(curString, curStrPos);
}, self.backDelay);
} else {
/* call before functions if applicable */
if (curStrPos === 0)
self.options.preStringTyped(self.arrayPos);
// start typing each new char into existing string
// curString: arg, self.el.html: original text inside element
var nextString = curString.substr(0, curStrPos + 1);
if (self.attr) {
self.el.attr(self.attr, nextString);
} else {
if (self.isInput) {
self.el.val(nextString);
} else if (self.contentType === 'html') {
self.el.html(nextString);
} else {
self.el.text(nextString);
}
}
// add characters one by one
curStrPos++;
// loop the function
self.typewrite(curString, curStrPos);
}
// end of character pause
}, charPause);
// humanized value for typing
}, humanize);
}
,
backspace: function(curString, curStrPos) {
// exit when stopped
if (this.stop === true) {
return;
}
// varying values for setTimeout during typing
// can't be global since number changes each time loop is executed
var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
var self = this;
self.timeout = setTimeout(function() {
// ----- this part is optional ----- //
// check string array position
// on the first string, only delete one word
// the stopNum actually represents the amount of chars to
// keep in the current string. In my case it's 14.
// if (self.arrayPos == 1){
// self.stopNum = 14;
// }
//every other time, delete the whole typed string
// else{
// self.stopNum = 0;
// }
if (self.contentType === 'html') {
// skip over html tags while backspacing
if (curString.substr(curStrPos).charAt(0) === '>') {
var tag = '';
while (curString.substr(curStrPos).charAt(0) !== '<') {
tag -= curString.substr(curStrPos).charAt(0);
curStrPos--;
}
curStrPos--;
tag += '<';
}
}
// ----- continue important stuff ----- //
// replace text with base text + typed characters
var nextString = curString.substr(0, curStrPos);
if (self.attr) {
self.el.attr(self.attr, nextString);
} else {
if (self.isInput) {
self.el.val(nextString);
} else if (self.contentType === 'html') {
self.el.html(nextString);
} else {
self.el.text(nextString);
}
}
// if the number (id of character in current string) is
// less than the stop number, keep going
if (curStrPos > self.stopNum) {
// subtract characters one by one
curStrPos--;
// loop the function
self.backspace(curString, curStrPos);
}
// if the stop number has been reached, increase
// array position to next string
else if (curStrPos <= self.stopNum) {
self.arrayPos++;
if (self.arrayPos === self.strings.length) {
self.arrayPos = 0;
// Shuffle sequence again
if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);
self.init();
} else
self.typewrite(self.strings[self.sequence[self.arrayPos]], curStrPos);
}
// humanized value for typing
}, humanize);
}
/**
* Shuffles the numbers in the given array.
* #param {Array} array
* #returns {Array}
*/
,shuffleArray: function(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
// Start & Stop currently not working
// , stop: function() {
// var self = this;
// self.stop = true;
// clearInterval(self.timeout);
// }
// , start: function() {
// var self = this;
// if(self.stop === false)
// return;
// this.stop = false;
// this.init();
// }
// Reset and rebuild the element
,
reset: function() {
var self = this;
clearInterval(self.timeout);
var id = this.el.attr('id');
this.el.after('<span id="' + id + '"/>')
this.el.remove();
if (typeof this.cursor !== 'undefined') {
this.cursor.remove();
}
// Send the callback
self.options.resetCallback();
}
};
$.fn.typed = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('typed'),
options = typeof option == 'object' && option;
if (!data) $this.data('typed', (data = new Typed(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.typed.defaults = {
strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
stringsElement: null,
// typing speed
typeSpeed: 0,
// time before typing starts
startDelay: 0,
// backspacing speed
backSpeed: 0,
// shuffle the strings
shuffle: false,
// time before backspacing
backDelay: 500,
// loop
loop: false,
// false = infinite
loopCount: false,
// show cursor
showCursor: true,
// character for cursor
cursorChar: "|",
// attribute to type (null == text)
attr: null,
// either html or text
contentType: 'html',
// call when done callback function
callback: function() {},
// starting callback function before each string
preStringTyped: function() {},
//callback for every typed string
onStringTyped: function() {},
// callback for reset
resetCallback: function() {}
};
}(window.jQuery);
</script>
<input id="input_text" type="text" placeholder="" />
you can replace it like
$('#input_text').on('click', function(e){
$(this).data('typed').reset();
$('#input_text').replaceWith('<input type="text" name="q" size="25" id="input_text" value=""/>');
$("#input_text").focus();
});
i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.
I'm trying to display some set values for my stats on the webpage....
The javascript is:
<script src="****/js/waypoints.min.js" type="text/javascript"></script>
<script>
$.fn.waypoint.defaults = {
context: window,
continuous: false,
enabled: true,
horizontal: false,
offset: 0,
triggerOnce: true
}
$('.facts_waypoint').waypoint(function(direction) {
function count($this){
var current = parseInt($this.html(), 10);
if (current >= 1000000) {current = current +493023;}
else if (current >= 10000) {current = current +43749;}
else if (current >= 1000) { current = current + 7369;}
else { if (current >= 100) { current = current + 197;}
else {current = current + 1}
}
/*current = current + 100; Where 1 is increment */
$this.html(++current);
if(current > $this.data('count')){
$this.html($this.data('count'));
} else {
setTimeout(function(){count($this)}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
jQuery(this).data('count', parseInt(jQuery(this).html(), 10));
jQuery(this).html('0');
count(jQuery(this));
});
});
However, it only displays the first numbers before the commas... I.e. 22,256,244 = 22 will be displayed... So I tried using LocalString:
<script>
var number = 22874098;
number.toLocaleString(); // "22,874,098"
</script>
This failed and just kept increasing..... Also no commas were included.
Can anyone shed any light on how I would get the numbers to stop increasing BUT more importantly - show commas?
Cheers for now!
Edit - Just tried this:
<script>
$.fn.waypoint.defaults = {
context: window,
continuous: false,
enabled: true,
horizontal: false,
offset: 0,
triggerOnce: true
}
$('.facts_waypoint').waypoint(function(direction) {
function count($this){
var current = parseInt($this.text().replace(/[^0-9]/g, ''), 10);
if (current >= 1000000) {current = current +493023;}
else if (current >= 10000) {current = current +43749;}
else if (current >= 1000) { current = current + 7369;}
else { if (current >= 100) { current = current + 197;}
else {current = current + 1}
}
/*current = current + 100; Where 1 is increment */
$this.text(++current);
if(current > $this.data('count')){
$this.text($this.data('count'));
} else {
setTimeout(function(){count($this)}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
jQuery(this).data('count', parseInt(jQuery(this).text(), 10));
jQuery(this).text('0');
count(jQuery(this));
});
});
</script>
For the comma issue, you will need to strip out non-numeric characters from the value before doing the parseInt. I suggest using $this.text() as opposed to $this.html() and using a regular expression on the input.
var current = parseInt($this.text().replace(/,/g, ''), 10);
That will replace only the commas from the input with empty strings leaving you the digits and the decimal separator. Since you are only interested in integers, you can take another approach with the regular expression and remove all non-numeric characters.
var current = parseInt($this.text().replace(/[^0-9]/g, ''), 10);
When parsing or formatting the value of the field you need to strip out or add commas and carry the text() or html() call through the whole code path. I went through the code and adjusted a couple of things to make it a bit more readable and separate out the parsing more clearly. Give the following a try:
$('.facts_waypoint').waypoint(function(direction) {
function parse(text) {
return parseInt(text.replace(/[^0-9]/g, ''), 10);
}
function count($this) {
var current = parse($this.text());
if (current >= 1000000) {
current = current + 493023;
} else if (current >= 10000) {
current = current + 43749;
} else if (current >= 1000) {
current = current + 7369;
} else if (current >= 100) {
current = current + 197;
} else {
current = current + 1;
}
$this.text((++current).toLocaleString());
if (current < $this.data('count')) {
setTimeout(function() {
count($this)
}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
var $this = jQuery(this);
$this.data('count', parse($this.text()));
$this.text('0');
count($this);
});
});
I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});