Javascript Phone number auto convert is not working - javascript

I have some javascript code like below
function mask(eventVal,val){
var len = val.value.length;
var key = whichKey(eventVal);
if(key>47 && key<58)
{
if( len==0 )val.value=val.value+'('
else if( len==4 )val.value=val.value+') '
else if(len==9 )val.value=val.value+'-'
else val.value=val.value;
}
else{
val.value = val.value.replace(/[^0-9-]/,'')
val.value = val.value.replace('--','-')
}
}
function whichKey(eventVal) {
var code;
if (!eventVal) var eventVal = window.event;
if (eventVal.keyCode) code = eventVal.keyCode;
else if (eventVal.which) code = eventVal.which;
return code;
}
HTML
<input type="text" name="PhoneNumber" id="PhoneNumber" value="" onkeydown="mask(event,this)"/>
It is working fine when I am typing phone number like 1234567890 is automatically converting into (123) 456-7890 when I am trying to remove value like remove 0 from the end then formatting is getting ruined completely. like 123) 456-789 and even it is getting ruined when I am click any other place. Can Any one help me to fix it?

check this script..
<script language="javascript">
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 14;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object){
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object){
phonevalue2 = ParseChar(object.value, zChar);
}
function up(object,e) {
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber1(object)
if(keycode >= 48){
ValidatePhone(object)
}
}
function down(object,e) {
if(e){
e = e
} else {
e = window.event
}
if(e.which){
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber2(object)
}
function GetCursorPosition(){
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i=0; i<t1.length; i++)
{
if (t1.substring(i,1) != t2.substring(i,1)) {
if(!bool) {
cursorposition=i
window.status=cursorposition
bool=true
}
}
}
}
function ValidatePhone(object){
var p = phonevalue1
p = p.replace(/[^\d]*/gi,"")
if (p.length < 3) {
object.value=p
} else if(p.length==3){
pp=p;
d4=p.indexOf('(')
d5=p.indexOf(')')
if(d4==-1){
pp="("+pp;
}
if(d5==-1){
pp=pp+")";
}
object.value = pp;
} else if(p.length>3 && p.length < 7){
p ="(" + p;
l30=p.length;
p30=p.substring(0,4);
p30=p30+") "
p31=p.substring(4,l30);
pp=p30+p31;
object.value = pp;
} else if(p.length >= 7){
p ="(" + p;
l30=p.length;
p30=p.substring(0,4);
p30=p30+") "
p31=p.substring(4,l30);
pp=p30+p31;
l40 = pp.length;
p40 = pp.substring(0,9);
p40 = p40 + "-"
p41 = pp.substring(9,l40);
ppp = p40 + p41;
object.value = ppp.substring(0, maxphonelength);
}
GetCursorPosition()
if(cursorposition >= 0){
if (cursorposition == 0) {
cursorposition = 2
} else if (cursorposition <= 2) {
cursorposition = cursorposition + 1
} else if (cursorposition <= 4) {
cursorposition = cursorposition + 3
} else if (cursorposition == 5) {
cursorposition = cursorposition + 3
} else if (cursorposition == 6) {
cursorposition = cursorposition + 3
} else if (cursorposition == 7) {
cursorposition = cursorposition + 4
} else if (cursorposition == 8) {
cursorposition = cursorposition + 4
e1=object.value.indexOf(')')
e2=object.value.indexOf('-')
if (e1>-1 && e2>-1){
if (e2-e1 == 4) {
cursorposition = cursorposition - 1
}
}
} else if (cursorposition == 9) {
cursorposition = cursorposition + 4
} else if (cursorposition < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition == 12) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 13) {
cursorposition = cursorposition
}
var txtRange = object.createTextRange();
txtRange.moveStart( "character", cursorposition);
txtRange.moveEnd( "character", cursorposition - object.value.length);
txtRange.select();
}
}
function ParseChar(sStr, sChar)
{
if (sChar.length == null)
{
zChar = new Array(sChar);
}
else zChar = sChar;
for (i=0; i<zChar.length; i++)
{
sNewStr = "";
var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);
while (iEnd != -1)
{
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
sStr = sNewStr;
}
return sNewStr;
}
</script>
HTML:
<input type="text" name="txtInput" onkeydown="javascript:down(this,event);" onkeyup="javascript:up(this,event);">

You can try this code to replace your last digit
<script type="text/javascript">
function fnc()
{
str=document.getElementById("atext").value;
x=(str.match(pattern));
if(x!="")
{str=str.replace(/[0-9]$/g,'')}
alert(str);
}
</script>
<body>
<input type="text" id="atext">
<input type="button" onClick="fnc()">
</body>

Related

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

jQuery & Javascript to Highlight and Crossout HTML Content

Highlight and Crossout values i am storing to database so, we can remain next time in questions I just want to be worked highlight and crossout in html using jquery same way or another way.
I am trying this code and sometimes it generates problem while calling jQuery functions it generates double output while when we do highlight questions and crossout on html content sometimes highlight and crossout also not working with selecting using Ctrl+A or select all with my code.
Click Here For Output
HTML:
<style>
.highlight{background:yellow;}
.crossout{text-decoration: line-through;}
</style>
<input type="button" onClick="return false;" id="btn_highlight" unselectable="on" value="highlight" class="unselectable" alt="highlight" width="36" height="38">
<input type="button" onClick="return false;" id="btn_crossout" unselectable="on" value="crossout" class="unselectable" alt="crossout" width="36" height="38" />
<input name="highlight" id="highlight" type="text" value=""/>
<input name="crossout" id="crossout" type="text" value=""/>
<div class="highlight_area">
<div id="high" class="question_area">
<div class="question_stem">
<p>A 47-year-old male with chronic kidney disease and peptic ulcer disease presents to the emergency room with chest pain. The patient states the pain increases with breathing and radiates to his back but improves with leaning forward. He states that he recently had a viral upper respiratory infection that left him with a cough for the past 3 weeks. An echocardiogram is ordered which appears normal. EKG shows diffuse ST segment elevations with PR depression. What is the most appropriate treatment at this time?</p>
</div>
<br>
</div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer11" value="1"><label for="answer11">A. NSAID only</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer22" value="2"><label for="answer22">B. Colchicine only</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer33" value="3"><label for="answer33">C. NSAIDS and colchicine</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer44" value="4"><label for="answer44">D. Corticosteroids</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer55" value="5"><label for="answer55">E. Dialysis</label></div>
<input type="hidden" name="data[Answer][correct]" value="2" id="AnswerCorrect">
</div>
JQUERY:
$(document).on('click', '#btn_highlight', function() {
select('#highlight');
apply('highlight');
});
$(document).on('click', '#btn_crossout', function() {
select('#crossout');
apply('crossout');
});
function select(id) {
function append(id, begin, end) {
// console.log('Add: ' + begin + ' to ' + end);
var highlights = $(id).val().trim().split(',');
var start = -1;
var done = -1;
var duplicate = -1;
var inside = -1;
var out = [];
var previous = 99999999;
var on = false;
for (x in highlights) {
var mark = highlights[x];
if (!mark) continue;
// console.log('Check: ' + mark + ' Start: ' + start + ' End: ' + done);
if (duplicate == mark) {
// console.log('Repeated mark');
out.push(mark);
}
if (done >= 0) {
out.push(mark);
continue;
} else if (start < 0) {
if (end < mark) {
// console.log('Prepend new');
out.push(begin);
out.push(end);
out.push(mark);
start = mark;
done = end;
} else if (end == mark || begin < mark) {
if (!on && end <= mark) {
// console.log('Prepend consecutive');
out.push(begin);
out.push(end);
out.push(mark);
done = mark;
} else if (on) {
// console.log('Start inside');
inside = begin
} else {
// console.log('Start new');
out.push(begin);
}
start = begin;
} else if (begin == mark) {
// console.log('Start overlapped');
duplicate = mark;
start = mark;
} else {
// console.log('Skip one');
out.push(mark);
}
}
if (done < 0 && start >= 0) {
if (end == mark) {
if (inside >= 0) {
// console.log('End overlapped from inside');
out.push(inside);
on = !on;
} else if (duplicate < 0) {
// console.log('End overlapped from outside');
out.push(end);
}
done = mark;
} else if (end > previous && end < mark) {
if (!on || duplicate >= 0) {
// console.log('End new');
out.push(end);
}
out.push(mark);
done = mark;
}
}
on = !on;
// console.log(out);
previous = mark;
}
if (done < 0) {
if (duplicate >= 0 && begin == mark) {
out.push(begin);
out.push(begin);
out.push(end);
} else {
if (start < 0) {
out.push(begin);
} else if (duplicate >= 0) {
// console.log('End from duplicate');
out.push(duplicate);
}
out.push(end);
}
}
$(id).val(out.toString().trim(','));
// console.log(id + ': ' + $(id).val());
if (out.length % 2 != 0) {
console.log('Error!');
}
}
var temp = '#temp';
function getIndex(elem, offset) {
var parent = $(elem).parents('.highlight_area');
elem.nodeValue = temp + elem.nodeValue;
var text = parent.text();
var add = text.indexOf(temp);
offset = offset + add;
elem.nodeValue = elem.nodeValue.substr(temp.length);
return offset;
}
function getIndex2(elem, offset) {
var parent = elem.parents('.highlight_area');
elem.text(temp + elem.text());
var text = parent.text();
var add = text.indexOf(temp);
offset = offset + add;
elem.text(elem.text().substr(temp.length));
return offset;
}
function getElem(node) {
if (node.is('.highlight,.crossout')) {
node = node.parent();
}
return node;
}
var highlight = window.getSelection();
// console.log(highlight);
var base = highlight.focusNode;
var anchor = highlight.anchorNode;
var baseOffset = highlight.focusOffset;
var anchorOffset = highlight.anchorOffset;
if (!highlight.rangeCount || !$(base).parents('.highlight_area').length || !$(anchor).parents('.highlight_area').length) {
// console.log(highlight.rangeCount + ' ; ' + $(base).parents('.highlight_area').length + ' ; ' + $(anchor).parents('.highlight_area').length);
return;
}
baseOffset = getIndex(base, baseOffset);
anchorOffset = getIndex(anchor, anchorOffset);
var stem = $('.highlight_area');
var baseIndex = getElem($(base.parentElement)).index();
var anchorIndex = getElem($(anchor.parentElement)).index();
var start = Math.min(baseOffset, anchorOffset);
var end = Math.max(baseOffset, anchorOffset);
// console.log('Offset: ' + start + ' to ' + end);
// console.log('Indexes: ' + baseIndex + ' v ' + anchorIndex);
if (baseIndex == anchorIndex) {
append(id, start, end);
} else {
var children = stem.find(':not(.highlight,.crossout)');
var startIndex = Math.min(baseIndex, anchorIndex);
var endIndex = Math.max(baseIndex, anchorIndex);
var child = $(children[startIndex]);
var text = child.text();
var textStart = getIndex2(child, text.length);
append(id, start, textStart);
for (var i = startIndex + 1; i < endIndex; i++) {
child = $(children[i]);
text = child.text();
if (!text.trim().length) continue;
append(id, textStart, textStart + text.length);
textStart = textStart + text.length;
}
var child = $(children[endIndex]);
var textStart = getIndex2(child, 0);
append(id, textStart, end);
}
}
function apply() {
var highlights = $('#highlight').val().split(',');
var crossouts = $('#crossout').val().split(',');
var marks = {};
for (x in highlights) {
if (typeof marks[highlights[x]] != 'undefined') {
// 2 consecutive highlights
marks[highlights[x]] = 4;
} else {
marks[highlights[x]] = 1;
}
}
for (x in crossouts) {
if (typeof marks[crossouts[x]] == 'undefined') {
marks[crossouts[x]] = 2;
} else {
if (marks[crossouts[x]] == 4) {
// 2 highlights and a crossout
marks[crossouts[x]] = 6;
} else if (marks[crossouts[x]] == 2) {
// 2 consecutive crossouts
marks[crossouts[x]] = 5;
} else if (marks[crossouts[x]] == 6) {
// 2 consecutive highlights and crossouts
marks[crossouts[x]] = 7;
} else if (marks[crossouts[x]] == 3) {
// 2 consecutive crossouts and highlight
marks[crossouts[x]] = 8;
} else {
// highlight and crossout
marks[crossouts[x]] = 3;
}
}
}
var stem = $('.highlight_area');
var children = stem.find(':not(.highlight,.crossout)');
var childIndex = 0;
var child = $(children[childIndex]);
var text = child.text().replace(/(<([^>]+)>)/ig, "");
var high = false;
var cross = false;
var previousMark = 0;
var passedChars = 0;
var mode = 0;
var string = '';
var nextEdge = 0;
stem.empty();
child.empty();
var first = true;
var maxLoop = 10;
for (x in marks) {
if (x == '') continue;
// console.log('Mark: ' + x);
nextEdge = 1 * passedChars + 1 * text.length;
// console.log('Next edge: ' + nextEdge);
var loopCount = 0;
while (x > nextEdge && loopCount++ < maxLoop) {
string = text.substr(previousMark - passedChars);
stem.append(child.append(string));
passedChars = 1 * passedChars + 1 * text.length;
previousMark = passedChars;
// move on to next
childIndex = childIndex + 1;
child = $(children[childIndex]);
text = child.text();
child.empty();
nextEdge = 1 * text.length + 1 * passedChars;
// console.log('Next edge : ' + nextEdge);
}
// console.log('Select: ' + previousMark + ' to ' + x);
string = text.substr(previousMark - passedChars, x - previousMark);
// console.log(string);
var type = '';
if (high) {
type = type + ' highlight';
}
if (cross) {
type = type + ' crossout';
}
if (type) {
var span = $('<span></span>').addClass(type);
span.text(string);
child.append(span);
} else {
child.append(string);
}
previousMark = x;
if (marks[x] == 1) {
high = !high;
} else if (marks[x] == 2) {
cross = !cross;
} else if (marks[x] == 3) {
high = !high;
cross = !cross;
} else if (marks[x] == 4) {
high = true;
} else if (marks[x] == 5) {
cross = true;
} else if (marks[x] == 6) {
high = true;
cross = !cross;
} else if (marks[x] == 7) {
high = true;
cross = true;
} else if (marks[x] == 8) {
high = !high;
cross = true;
}
}
string = text.substr(previousMark - passedChars);
stem.append(child.append(string));
childIndex = childIndex + 1;
while (childIndex < children.length) {
child = $(children[childIndex]);
child.find('.highlight,.crossout').each(function(i, e) {
child.html(child.html().replace($(e).outerHtml(), $(e).text()));
});
stem.append(child);
childIndex = childIndex + 1;
}
}
apply();
Click Here For Output

Highlight & Crossout issues in HTML Content using jQuery & Javascript

I have problem while calling jquery functions it generates double output while when we do highlight questions and crossout on html content sometimes highlight and crossout also not working with selecting using Ctrl+A or select all.
highlight and crossout values i am storing to database so, we can remain next time in questions.
I am trying and just needs to works it well.
Click Here For Output
HTML Code
<style>
.highlight{background:yellow;}
.crossout{text-decoration: line-through;}
</style>
<input type="button" onClick="return false;" id="btn_highlight" unselectable="on" value="highlight" class="unselectable" alt="highlight" width="36" height="38">
<input type="button" onClick="return false;" id="btn_crossout" unselectable="on" value="crossout" class="unselectable" alt="crossout" width="36" height="38" />
<input name="highlight" id="highlight" type="text" value=""/>
<input name="crossout" id="crossout" type="text" value=""/>
<div class="highlight_area">
<div id="high" class="question_area">
<div class="question_stem">
<p>A 47-year-old male with chronic kidney disease and peptic ulcer disease presents to the emergency room with chest pain. The patient states the pain increases with breathing and radiates to his back but improves with leaning forward. He states that he recently had a viral upper respiratory infection that left him with a cough for the past 3 weeks. An echocardiogram is ordered which appears normal. EKG shows diffuse ST segment elevations with PR depression. What is the most appropriate treatment at this time?</p>
</div>
<br>
</div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer11" value="1"><label for="answer11">A. NSAID only</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer22" value="2"><label for="answer22">B. Colchicine only</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer33" value="3"><label for="answer33">C. NSAIDS and colchicine</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer44" value="4"><label for="answer44">D. Corticosteroids</label></div>
<div class="input radio"><input type="radio" name="data[Answer][answer]" id="answer55" value="5"><label for="answer55">E. Dialysis</label></div>
<input type="hidden" name="data[Answer][correct]" value="2" id="AnswerCorrect">
</div>
jQuery Code
$(document).on('click', '#btn_highlight', function() {
select('#highlight');
apply('highlight');
});
$(document).on('click', '#btn_crossout', function() {
select('#crossout');
apply('crossout');
});
function select(id) {
function append(id, begin, end) {
// console.log('Add: ' + begin + ' to ' + end);
var highlights = $(id).val().trim().split(',');
var start = -1;
var done = -1;
var duplicate = -1;
var inside = -1;
var out = [];
var previous = 99999999;
var on = false;
for (x in highlights) {
var mark = highlights[x];
if (!mark) continue;
// console.log('Check: ' + mark + ' Start: ' + start + ' End: ' + done);
if (duplicate == mark) {
// console.log('Repeated mark');
out.push(mark);
}
if (done >= 0) {
out.push(mark);
continue;
} else if (start < 0) {
if (end < mark) {
// console.log('Prepend new');
out.push(begin);
out.push(end);
out.push(mark);
start = mark;
done = end;
} else if (end == mark || begin < mark) {
if (!on && end <= mark) {
// console.log('Prepend consecutive');
out.push(begin);
out.push(end);
out.push(mark);
done = mark;
} else if (on) {
// console.log('Start inside');
inside = begin
} else {
// console.log('Start new');
out.push(begin);
}
start = begin;
} else if (begin == mark) {
// console.log('Start overlapped');
duplicate = mark;
start = mark;
} else {
// console.log('Skip one');
out.push(mark);
}
}
if (done < 0 && start >= 0) {
if (end == mark) {
if (inside >= 0) {
// console.log('End overlapped from inside');
out.push(inside);
on = !on;
} else if (duplicate < 0) {
// console.log('End overlapped from outside');
out.push(end);
}
done = mark;
} else if (end > previous && end < mark) {
if (!on || duplicate >= 0) {
// console.log('End new');
out.push(end);
}
out.push(mark);
done = mark;
}
}
on = !on;
// console.log(out);
previous = mark;
}
if (done < 0) {
if (duplicate >= 0 && begin == mark) {
out.push(begin);
out.push(begin);
out.push(end);
} else {
if (start < 0) {
out.push(begin);
} else if (duplicate >= 0) {
// console.log('End from duplicate');
out.push(duplicate);
}
out.push(end);
}
}
$(id).val(out.toString().trim(','));
// console.log(id + ': ' + $(id).val());
if (out.length % 2 != 0) {
console.log('Error!');
}
}
var temp = '#temp';
function getIndex(elem, offset) {
var parent = $(elem).parents('.highlight_area');
elem.nodeValue = temp + elem.nodeValue;
var text = parent.text();
var add = text.indexOf(temp);
offset = offset + add;
elem.nodeValue = elem.nodeValue.substr(temp.length);
return offset;
}
function getIndex2(elem, offset) {
var parent = elem.parents('.highlight_area');
elem.text(temp + elem.text());
var text = parent.text();
var add = text.indexOf(temp);
offset = offset + add;
elem.text(elem.text().substr(temp.length));
return offset;
}
function getElem(node) {
if (node.is('.highlight,.crossout')) {
node = node.parent();
}
return node;
}
var highlight = window.getSelection();
// console.log(highlight);
var base = highlight.focusNode;
var anchor = highlight.anchorNode;
var baseOffset = highlight.focusOffset;
var anchorOffset = highlight.anchorOffset;
if (!highlight.rangeCount || !$(base).parents('.highlight_area').length || !$(anchor).parents('.highlight_area').length) {
// console.log(highlight.rangeCount + ' ; ' + $(base).parents('.highlight_area').length + ' ; ' + $(anchor).parents('.highlight_area').length);
return;
}
baseOffset = getIndex(base, baseOffset);
anchorOffset = getIndex(anchor, anchorOffset);
var stem = $('.highlight_area');
var baseIndex = getElem($(base.parentElement)).index();
var anchorIndex = getElem($(anchor.parentElement)).index();
var start = Math.min(baseOffset, anchorOffset);
var end = Math.max(baseOffset, anchorOffset);
// console.log('Offset: ' + start + ' to ' + end);
// console.log('Indexes: ' + baseIndex + ' v ' + anchorIndex);
if (baseIndex == anchorIndex) {
append(id, start, end);
} else {
var children = stem.find(':not(.highlight,.crossout)');
var startIndex = Math.min(baseIndex, anchorIndex);
var endIndex = Math.max(baseIndex, anchorIndex);
var child = $(children[startIndex]);
var text = child.text();
var textStart = getIndex2(child, text.length);
append(id, start, textStart);
for (var i = startIndex + 1; i < endIndex; i++) {
child = $(children[i]);
text = child.text();
if (!text.trim().length) continue;
append(id, textStart, textStart + text.length);
textStart = textStart + text.length;
}
var child = $(children[endIndex]);
var textStart = getIndex2(child, 0);
append(id, textStart, end);
}
}
function apply() {
var highlights = $('#highlight').val().split(',');
var crossouts = $('#crossout').val().split(',');
var marks = {};
for (x in highlights) {
if (typeof marks[highlights[x]] != 'undefined') {
// 2 consecutive highlights
marks[highlights[x]] = 4;
} else {
marks[highlights[x]] = 1;
}
}
for (x in crossouts) {
if (typeof marks[crossouts[x]] == 'undefined') {
marks[crossouts[x]] = 2;
} else {
if (marks[crossouts[x]] == 4) {
// 2 highlights and a crossout
marks[crossouts[x]] = 6;
} else if (marks[crossouts[x]] == 2) {
// 2 consecutive crossouts
marks[crossouts[x]] = 5;
} else if (marks[crossouts[x]] == 6) {
// 2 consecutive highlights and crossouts
marks[crossouts[x]] = 7;
} else if (marks[crossouts[x]] == 3) {
// 2 consecutive crossouts and highlight
marks[crossouts[x]] = 8;
} else {
// highlight and crossout
marks[crossouts[x]] = 3;
}
}
}
var stem = $('.highlight_area');
var children = stem.find(':not(.highlight,.crossout)');
var childIndex = 0;
var child = $(children[childIndex]);
var text = child.text().replace(/(<([^>]+)>)/ig, "");
var high = false;
var cross = false;
var previousMark = 0;
var passedChars = 0;
var mode = 0;
var string = '';
var nextEdge = 0;
stem.empty();
child.empty();
var first = true;
var maxLoop = 10;
for (x in marks) {
if (x == '') continue;
// console.log('Mark: ' + x);
nextEdge = 1 * passedChars + 1 * text.length;
// console.log('Next edge: ' + nextEdge);
var loopCount = 0;
while (x > nextEdge && loopCount++ < maxLoop) {
string = text.substr(previousMark - passedChars);
stem.append(child.append(string));
passedChars = 1 * passedChars + 1 * text.length;
previousMark = passedChars;
// move on to next
childIndex = childIndex + 1;
child = $(children[childIndex]);
text = child.text();
child.empty();
nextEdge = 1 * text.length + 1 * passedChars;
// console.log('Next edge : ' + nextEdge);
}
// console.log('Select: ' + previousMark + ' to ' + x);
string = text.substr(previousMark - passedChars, x - previousMark);
// console.log(string);
var type = '';
if (high) {
type = type + ' highlight';
}
if (cross) {
type = type + ' crossout';
}
if (type) {
var span = $('<span></span>').addClass(type);
span.text(string);
child.append(span);
} else {
child.append(string);
}
previousMark = x;
if (marks[x] == 1) {
high = !high;
} else if (marks[x] == 2) {
cross = !cross;
} else if (marks[x] == 3) {
high = !high;
cross = !cross;
} else if (marks[x] == 4) {
high = true;
} else if (marks[x] == 5) {
cross = true;
} else if (marks[x] == 6) {
high = true;
cross = !cross;
} else if (marks[x] == 7) {
high = true;
cross = true;
} else if (marks[x] == 8) {
high = !high;
cross = true;
}
}
string = text.substr(previousMark - passedChars);
stem.append(child.append(string));
childIndex = childIndex + 1;
while (childIndex < children.length) {
child = $(children[childIndex]);
child.find('.highlight,.crossout').each(function(i, e) {
child.html(child.html().replace($(e).outerHtml(), $(e).text()));
});
stem.append(child);
childIndex = childIndex + 1;
}
}
apply();

Synchronous input update with selected digit in HTML/JavaScript

I'm trying to implement a customised input that can use left or right arrow key to select the digit and use up/down arrow key to increment/decrement the digit. Here's the code in jsfiddle: http://jsfiddle.net/uk5t3z4d/48/. However, I have two problems:
I cannot add digit using the number pad, the input always stays at X.XX
When I use another function I wrote (parseLocalFloat which is commented out), the output stops displaying anything, and I cannot use the left and right key to select the digit etc.
How can I overcome these two issues? Please shed a light on me, thanks!
HTML
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
JavaScript
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
//var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var before = $(this).val().substring(0,curPos);
var after = $(this).val().substring(curPos+1);
var cur = Number($(this).val().substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $(this).val().length) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
if(!gotCode) {
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
as for the "get number keys to work":
as stated you need to add the keys you want to support:
if(e.keyCode >= 48 && e.keyCode <= 57) {
var num = e.keyCode - 48; // 0=48; 9=59
$(this).val(before + '' + num + '' + after);
gotCode = true;
e.preventDefault(); // otherwise a new number is added as well
}
(this needs to come before the if (!gotCode) ... )
as for the customFloat: the the response from Moishe
For #1:
if(!gotCode) {
e.preventDefault();
return false;
}
ensures that if gotCode is false the default event (which in this case is the default keydown event) will not occur.
gotCode only seems to be true if keyCode is equal to 37, 38, 39, or 40 (the arrow keys). You are essentially preventing the other keys (like number keys) from having any effect on the textBox.
You probably would like to enable the number keys (when shift or caps aren't on) and number pad keys.
Additionally, you may want to check that the cur is a number (and not .) before attempting to increment or decrement its value.
You could do:
var isNumberKey = (
( e.keyCode >= 48 //is more than or equal to 0 key
&& e.keyCode <= 57 //is less than or equal to 9 key
&& !e.shiftKey) //shift key or cap key not on
|| ( e.keyCode >= 96 //more than or equal to 0 key in number pad
&& e.keyCode <= 105)); //less than or equal to 9 key in number pad
if(!gotCode && !isNumberKey) { //not arrow key or number key
console.log(e);
e.preventDefault();
return false;
}
For #2:
var inputBox = parseLocalFloat(document.getElementByID('in').value);
is setting inputBox to whatever parseLocalFloat returns which happens to be a number.
This is problematic because you then attempt to attach a keyUp event to that number instead of the inputBox:
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
You may want to instead call parseLocalFloat on the number and set the out textBox's value to that:
var inputBox = document.getElementById('in');
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
// var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var $thisVal = $(this).val();
var before = $thisVal.substring(0,curPos);
var after = $thisVal.substring(curPos+1);
var cur = Number($thisVal.substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $thisVal.length && !isNaN(cur)) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
var isNumberKey = ((e.keyCode >= 48 && e.keyCode <= 57 && [16, 20].indexOf(e.keyCode) == -1 && !e.shiftKey) || (e.keyCode >= 96 && e.keyCode <= 105));
if(!gotCode && !isNumberKey) {
console.log(e);
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>

How to use AJAX or JSON in this code?

I am creating a website application that allows users to select a seat, if it is not already reserved, and reserve it.
I have created a very round about way of getting the seats that are previously reserved using iFrames, however that was temporarily, now I need to make it secure and "proper javascript code" using proper practices. I have no clue what AJAX (or JSON) is, nor how to add it to this code, but it needs to get the file "seatsReserved"+this.id(that is the date)+"Que.html" and compare the string of previously reserved seats to see which class to make the element. If this is horrible, or if any of the other things could work better, I am open to criticism to everything. Thank you all!
Here is the javascript code:
A little side note, all of the if statements are due to different amount of seats in each row
<script>
var i = " 0 ";
var counter = 0;
var leng=0;
document.getElementById("Show1").addEventListener("click", changeDay);
document.getElementById("Show2").addEventListener("click", changeDay);
document.getElementById("Show3").addEventListener("click", changeDay);
function changeDay() {
var iFrame = document.getElementById("seatList");
iFrame.src = "seatsReserved" + this.id + "Que.html";
document.getElementById('date').innerHTML = this.id;
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.removeEventListener("click", selectedSeat);
}
else {
document.getElementById(let +k).className = "openseat";
document.getElementById(let +k).removeEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
}
function loadChanges() {
var iFrame = document.getElementById("seatList");
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
var leng = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.addEventListener("click", selectedSeat);
seat.className = "openseat";
}
else {
document.getElementById(let +k).className = "notAvailible";
document.getElementById(let +k).addEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
i = " 0 ";
counter = 0;
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
document.getElementById("seatnums").innerHTML = counter;
}
i = document.getElementById("seatString").innerHTML;
counter = document.getElementById("seatnums").innerHTML;
function selectedSeat() {
var w = this.id;
var l = (" " + w);
var b = (" " + w + " ");
if (counter < 5) {
if (i.indexOf(b) <= 0) {
this.className = "closedseat";
i = i + b;
i = i.replace(" 0 ", " ");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter + 1;
document.getElementById("seatnums").innerHTML = counter;
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
function doNothing() {
}
var rannum = Math.random() * 1000;
document.getElementById('getConfirmation').value = rannum;
</script>

Categories

Resources