So I have this code
let data.message = "message https://www.google.com/images/branding/googlelogo/2x/googlelogo_light_color_272x92dp.png"
$('<div/>').text(data.message).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<img src="$1">$1</a> ')
Idk why its not working it splits the line on my thing cause its a chat app but it splits the http s:// for some reason heres the code to go to next line:
function getName(name) {
let newName = name;
// offsets i to match the current string
let offset = 0;
for (let i = 1; i < name.length; i += 1) {
if (i % 35 === 0) {
if(newName.charAt(i) === ' ') {
// Your own code with the offset
newName = newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
} else {
// looking back in the string until there is a space or the string "ends"
while(newName.charAt(i - offset) !== ' ' && offset <= 35) {
offset++;
}
// Only set newName if a space was found in the last 35
if(i - offset > 0) {
newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`;
}
}
}
}
return newName;
}
Related
I want to enter a "/" when user enters MM(2 digit) so it will be like MM/YYYY.
I have done similar for credit card number input which insert a space after 4 digit on keypress.
let ccNumber = e.target.value.split(" ").join("");
if (ccNumber.length > 0) {
ccNumber = ccNumber.match(new RegExp('.{1,4}', 'g')).join(" ");
}
e.target.value = ccNumber;
Fiddle
This works with
Regular keyboard input
Copy/Cut/Paste
Selected text
Adding the /
Because you're programmatically adding the / character, you have to update the cursor position whenever that affects the new input value. This can be more than one character if the user is pasting something. Most of the code complexity revolves around this issue.
There are a lot of comments in the code explaining the various situations that come up because of the /.
Full Code
var date = document.getElementById('date');
date.addEventListener('keypress', updateInput);
date.addEventListener('change', updateInput);
date.addEventListener('paste', updateInput);
date.addEventListener('keydown', removeText);
date.addEventListener('cut', removeText);
function updateInput(event) {
event.preventDefault();
var string = getString(event);
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
var sanitizedString = string.replace(/[^0-9]+/g, '');
// Do nothing if nothing is added after sanitization
if (sanitizedString.length === 0) {
return;
}
// Only paste numbers that will fit
var valLength = date.value.replace(/[^0-9]+/g, '').length;
var availableSpace = 6 - valLength + selectionLength;
// If `/` is selected it should not count as available space
if (selectionStart <= 2 && selectionEnd >= 3) {
availableSpace -= 1;
}
// Remove numbers that don't fit
if (sanitizedString.length > availableSpace) {
sanitizedString = sanitizedString.substring(0, availableSpace);
}
var newCursorPosition = selectionEnd + sanitizedString.length - selectionLength;
// Add one to cursor position if a `/` gets inserted
if (selectionStart <= 2 && newCursorPosition >= 2) {
newCursorPosition += 1;
}
// Previous input value before current cursor position
var valueStart = date.value.substring(0, this.selectionStart);
// Previous input value after current cursor position
var valueEnd = date.value.substring(this.selectionEnd, date.value.length);
var proposedValue = valueStart + sanitizedString + valueEnd;
// Remove anything that's not a number
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(newCursorPosition, newCursorPosition);
}
function removeText(event) {
if (event.key === 'Backspace' || event.type === 'cut') {
event.preventDefault();
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
// If pressing backspace with no selected text
if (selectionLength === 0 && event.type !== 'cut') {
selectionStart -= 1;
// Remove number from before `/` if attempting to delete `/`
if (selectionStart === 2) {
selectionStart -= 1;
}
}
var valueStart = date.value.substring(0, selectionStart);
var valueEnd = date.value.substring(selectionEnd, date.value.length);
// Account for added `/`
if (selectionStart === 2) {
selectionStart += 1;
}
var proposedValue = valueStart + valueEnd;
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(selectionStart, selectionStart);
}
}
function getString(event) {
if (event.type === 'paste') {
var clipboardData = event.clipboardData || window.clipboardData;
return clipboardData.getData('Text');
} else {
return String.fromCharCode(event.which);
}
}
function format(sanitized) {
var newValue;
var month = sanitized.substring(0, 2);
if (sanitized.length < 2) {
newValue = month;
} else {
var year = sanitized.substring(2, 6);
newValue = month + '/' + year;
}
date.value = newValue;
}
<input id="date" type="text" maxlength="7">
Try:
var date = document.getElementById('date');
date.addEventListener('keypress', function (event) {
var char = String.fromCharCode(event.which),
offset = date.selectionStart;
console.log(offset)
if (/\d/.test(char) && offset < 7) {
if (offset === 2) {
offset += 1;
}
date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1);
date.selectionStart = date.selectionEnd = offset + 1;
}
if (!event.keyCode) {
event.preventDefault();
}
});
<input id="date" type="text" value="mm/yyyy" maxlength="6" size="6">
function keypress(elem) { // get Input
if (typeof elem == 'string') {
if (document.getElementById(elem)) elem = document.getElementById(elem);
if (typeof elem == 'string') elem = document.getElementsByName(elem).item(0);
}
const el = elem; //handle error if not found input
el.maxLength = 19;
el.addEventListener('keypress', function (e) {
const t = e.keyCode || e.which
if (t == 8 || (t > 47 && t < 58)) { // limit numeric characters and backspace
if (t != 8) {
if (el.value.length == 2) el.value += '/';
if (el.value.length == 5) el.value += '/';
if (el.value.length == 10) el.value += ' ';
if (el.value.length == 13) el.value += ':';
if (el.value.length == 16) el.value += ':';
}
} else {
e.preventDefault();
}
});}
I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);
I have a form that I'm using to calculate some numbers, and the final 3 input fields on the form are disabled because they show the results of the calculator.
I'm using the following javascript/jquery to add commas to the user editable fields which works great but I can't seem to find a way to add commas to the "results" fields:
$('input.seperator').change(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
This is what I'm using the populate the fields, basically the fields show the results in dollars, so I'm trying to add a comma every 3 numbers:
$('#incorrect-payment').val(fieldK);
$('#correcting-payment').val(fieldL);
$('#total-cost').val(fieldM);
I think you'd want to use a function like this:
function FormatCurrency(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var i = parseFloat(amount);
if (isNaN(i)) { i = 0.00; }
var minus = false;
if (i < 0) { minus = true; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (showDecimals) {
if (s.indexOf('.') < 0) { s += '.00'; }
if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
}
//s = minus + s;
s = '$' + FormatCommas(s, showDecimals);
if (minus)
s = "(" + s + ")";
return s;
}
function FormatCommas(amount, showDecimals) {
if (showDecimals == null)
showDecimals = true;
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) { return ''; }
var minus = '';
if (i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if (!showDecimals) {
amount = n;
}
else {
if (d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
}
amount = minus + amount;
return amount;
}
May be you might want to trigger change event manually through javascript for your three read-only input fields. Using jquery trigger . I am not sure but it seems like a bad idea to have a read-only input field if no user can change these values. Usually having read-only input fields is good if a user with some security can edit those and some cannot.
I have a div element with text and, possibly, other children tags inside it (imgs, spans, etc). I need the following - when user clicks somewhere within a div on a text, the child tag has to be inserted exactly in that position inside the text. Absolute positioning is not an option - I need to modify innerHTML of the div.
For instance, if the div is
<div>some text, more text</div>
And user clicks right after "more", my div should be modified as follows
<div>some text, more<span>new tag</span> text</div>
You could wrap each word/character in a span and then append the new tag after that one. LetteringJS (http://letteringjs.com/) can help you with that.
If you'd use inputs, you could use jCaret (http://www.examplet.org/jquery/caret.php) which looks quite fancy, judging from the examples.
As #LePhil suggested, I wrapped each word in a span. In the following example, the text is inserted after the word on which the mouse is clicked:
http://jsfiddle.net/LXZKA/2/
function parseHTML(str) {
var result = '';
function processText(text, i) {
if (text && text !== ' ') {
result += '<span data-begin-index=' + (i - text.length) + ' data-end-index=' + (i - 1) + '>' + text + '</span>';
}
}
function processTag(tag) {
result += tag;
}
var withinTag = false, withinText = false, text = '', tag = '';
for (var i = 0; i < str.length; i++) {
var ch = str.charAt(i);
if (ch === '<') {
withinText = false;
withinTag = true;
processText(text, i);
text = '';
tag = '<';
} else if (ch === '>') {
withinTag = false;
withinText = false;
processTag(tag + '>');
tag = '';
text = '';
} else if (ch === ' ' || ch == '\xA0') {
if (withinTag) {
tag += ch;
} else {
if (!text.replace(/\s+/g,'')) {
text += ch;
} else {
processText(text + ch, i + 1);
text = '';
}
}
} else {
if (withinTag) {
tag += ch;
} else {
text += ch;
}
}
}
processText(text, str.length);
return result;
}
function findNode(node, x, y) {
if (node.attributes['data-begin-index']) {
if (x >= node.offsetLeft && x <= node.offsetLeft + node.offsetWidth &&
y >= node.offsetTop && y <= node.offsetTop + node.offsetHeight)
{
return node;
}
} else {
for (var i = 0; i < node.childNodes.length; i++) {
var result = findNode(node.childNodes[i], x, y);
if (result) {
return result;
}
}
}
}
function clicked(e, node) {
console.log('clicked mouse');
var x = e.x - 100;
var y = e.y - 100;
console.log(x + ', ' + y);
var node = findNode(node, x, y);
if (node) {
var beginIndex = parseInt(node.getAttribute('data-begin-index'));
var endIndex = parseInt(node.getAttribute('data-end-index'));
newHTML = html.substring(0, endIndex + 1) + 'XXXXX ' + html.substring(endIndex + 1);
} else {
newHTML = html + 'XXXXX ';
}
document.getElementById('mydiv').innerHTML = parseHTML(html = newHTML);
}
document.getElementById('mydiv').innerHTML = parseHTML(html);
My pager works except for the last page that you click on. So if my last page is 11 that has been clicked the pager stops working when going backwards. If you click a page and then click another it works fine except for the last page. here it is on jsFiddle (its been updated and working now
Javascript:
$(document).ready(function () {
var pageIndex = 1;
function pagerControl(pageIndex, pageCount, step) {
var result = "";
if (pageCount > 1) {
var startPoint = Math.floor((pageIndex / step)) * step;
if ((pageIndex % step) == 0) {
startPoint -= step;
}
if (pageIndex < pageCount) {
result += 'Next';
}
else {
result += '<span>Next<span>';
}
//alert(startPoint);
for (var i = startPoint + 1; i <= pageCount && i <= (startPoint + step + 1); i++) {
if (i != pageIndex) {
result += '' + i + '';
}
else {
result += '<span>' + i + '</span>';
}
}
if (pageIndex > 1) {
result += 'Prev';
} else {
result += '<span>Prev</span>';
}
}
$('#pager').html(result);
$('#pager > a').click(function (e) {
reload($(e.target).attr('rel'));
e.preventDefault();
});
}
function reload(page) {
pagerControl(page, 11, 4);
}
pagerControl(1, 11, 4);
});
jsFiddle
Try this ' $('#pager a').click ' while binding click event with links instead of present ' $('#pager > a').click '.
It's working on my side. I know this isn't an elaborated answer but a quick correction.
.. :)
Sometimes we complicate things too much. How about abolish the "if" statement ... for most cases?
var pageIndex = 1;
function pagerControl(pageIndex, pageCount, step) {
var result = '';
if (pageCount > 1) {
pageIndex = (pageIndex > pageCount) ? pageCount : pageIndex;
var startPoint = Math.floor((pageIndex / step)) * step;
var endPoint = pageCount;
startPoint = (startPoint < 1) ? 1 : startPoint;
endPoint = ((startPoint + step) > pageCount) ? pageCount : (startPoint + step -1);
result = 'PREV ';
for (var i=startPoint;i<(endPoint+1);i++)
result += '' + i + '';
result += ' NEXT';
}
$('#pager').html(result);
$('#pager > a').click(function (e) {
reload(parseInt($(e.target).attr('rel')));
e.preventDefault();
});
}
function reload(page) {
pagerControl(page, 11, 4);
}
pagerControl(1, 11, 4);