There is a logical error in the code..
we cannot move up or down 2 or more options at a time.Only 1 option at a time can be moved up or down..so how to make 2 or more options move up and down when selected...
function listbox_move(listID, direction) {
var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;
if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;
if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.selectedIndex = selIndex + increment;
}
And I call it as follows
listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option
Thank you in advance.... :)
I know its pretty old question... If it helps..
EDIT :
https://jsfiddle.net/m0f757wh/
<html>
<body>
<script language="javascript" type="text/javascript">
function moveUp()
{
var ddl = document.getElementById('contentlist');
//var size = ddl.length;
//var index = ddl.selectedIndex;
var selectedItems = new Array();
var temp = {innerHTML:null, value:null};
for(var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if(selectedItems.length > 0)
if(selectedItems[0] != 0)
for(var i = 0; i < selectedItems.length; i++)
{
temp.innerHTML = ddl.options[selectedItems[i]].innerHTML;
temp.value = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].innerHTML = ddl.options[selectedItems[i] - 1].innerHTML;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] - 1].value;
ddl.options[selectedItems[i] - 1].innerHTML = temp.innerHTML;
ddl.options[selectedItems[i] - 1].value = temp.value;
ddl.options[selectedItems[i] - 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
}
function moveDown()
{
var ddl = document.getElementById('contentlist');
//var size = ddl.length;
//var index = ddl.selectedIndex;
var selectedItems = new Array();
var temp = {innerHTML:null, value:null};
for(var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if(selectedItems.length > 0)
if(selectedItems[selectedItems.length - 1] != ddl.length - 1)
for(var i = selectedItems.length - 1; i >= 0; i--)
{
temp.innerHTML = ddl.options[selectedItems[i]].innerHTML;
temp.value = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].innerHTML = ddl.options[selectedItems[i] + 1].innerHTML;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] + 1].value;
ddl.options[selectedItems[i] + 1].innerHTML = temp.innerHTML;
ddl.options[selectedItems[i] + 1].value = temp.value;
ddl.options[selectedItems[i] + 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
}
</script>
<select id="contentlist" name="itemId" multiple="multiple">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button id="Up" onclick="moveUp()">Up</button>
<button id="Down" onclick="moveDown()">Down</button>
</body>
</html>
You need to loop through all options and test for which ones are selected and execute the same logic. Here is a working example of how to do it - you should be able to use this:
function listbox_move(listID, direction)
{
var listbox = document.getElementById(listID);
for(var i=0; i<listbox.options.length; i++)
{
var option = listbox.options[i];
if(option.selected == true)
{
var selIndex = i;
if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}
var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;
if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}
var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text
listbox.options[selIndex].selected = false;
listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;
listbox.options[selIndex + increment].selected = true;
}
}
}
There is an issue with dave823's answer, but I can't comment it, so there is my working solution:
You can't use same "for" loop (as you used it) in case of moving items upward and downward. You have to use two different loops for each case - something like this:
for(var i=0; i<listbox.options.length; i++)
for(var i = listbox.options.length - 1; i >= 0; i--)
Here is my (working) solution, based on dave823's answer:
function listbox_move(listBox, direction) {
if (direction == 'up') {
for (var i = 0; i < listBox.options.length; i++) {
moveLbSelectedItemUpDown(lbOutput, i, -1);
}
}
else if (direction == 'down') {
for (var i = listBox.options.length - 1; i >= 0; i--) {
moveLbSelectedItemUpDown(lbOutput, i, 1);
}
}
}
function moveLbSelectedItemUpDown(lb, itemIndex, increment) {
if (-1 == itemIndex) {
alert("Please select an option to move.");
return;
}
if (lb.options[itemIndex].selected == true) {
if ((itemIndex + increment) < 0 ||
(itemIndex + increment) > (lb.options.length - 1)) {
return;
}
var selValue = lb.options[itemIndex].value;
var selText = lb.options[itemIndex].text;
lb.options[itemIndex].value = lb.options[itemIndex + increment].value
lb.options[itemIndex].text = lb.options[itemIndex + increment].text
lb.options[itemIndex].selected = false;
lb.options[itemIndex + increment].value = selValue;
lb.options[itemIndex + increment].text = selText;
lb.options[itemIndex + increment].selected = true;
}
}
This is StackAddict's code with some important revisions to ensure Text and Value attributes are swapped together:
$("#up").bind("click", function () {
var ddl = $("[id*=lstRight]")[0]; // <-- you may not need the [0]... I needed it
var selectedItems = new Array();
for (var i = 0; i < ddl.length; i++)
if (ddl.options[i].selected)
selectedItems.push(i);
if (selectedItems.length > 0)
if (selectedItems[0] != 0)
for (var i = 0; i < selectedItems.length; i++) {
var tempText = ddl.options[selectedItems[i]].text;
var tempValue = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].text = ddl.options[selectedItems[i] - 1].text;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] - 1].value;
ddl.options[selectedItems[i] - 1].text = tempText;
ddl.options[selectedItems[i] - 1].value = tempValue;
ddl.options[selectedItems[i] - 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
});
$("#down").bind("click", function () {
var ddl = $("[id*=lstRight]")[0]; // <-- you may not need the [0]... I needed it
var selectedItems = new Array();
for (var i = 0; i < ddl.length; i++)
if(ddl.options[i].selected)
selectedItems.push(i);
if (selectedItems.length > 0)
if(selectedItems[selectedItems.length - 1] != ddl.length - 1)
for(var i = selectedItems.length - 1; i >= 0; i--)
{
var tempText = ddl.options[selectedItems[i]].text;
var tempValue = ddl.options[selectedItems[i]].value;
ddl.options[selectedItems[i]].text = ddl.options[selectedItems[i] + 1].text;
ddl.options[selectedItems[i]].value = ddl.options[selectedItems[i] + 1].value;
ddl.options[selectedItems[i] + 1].text = tempText;
ddl.options[selectedItems[i] + 1].value = tempValue;
ddl.options[selectedItems[i] + 1].selected = true;
ddl.options[selectedItems[i]].selected = false;
}
});
Related
I'm programming a checkers game for a high school project. I have a weird variable behaviour and I can't figure out why it's happening. Let me show you the code:
var player = 1;
var lastClicked;
var wasClicked = false;
var isEmpty = new Array(8);
for (var i = 0; i < 8; i++) {
isEmpty[i] = new Array(8);
for (var j = 0; j < 8; j++) {
isEmpty[i][j] = true;
}
}
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { CheckIandJForLater(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function CheckIandJForLater(i, j) { // A function which is meant to show the weird behavior, which prevents me from using function I want to use in the event listener
alert("Function i: " + i);
alert("Function j: " + j);
}
function DeployPieces() {
CreateBoard();
var pieceIndex = 1;
for (var i = 0; i < 8; i++) {
if (i < 3) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td1 = document.getElementById("td" + i + j);
var circle1 = document.createElement("span");
circle1.setAttribute("class", "redCircle");
circle1.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle1.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td1.appendChild(circle1);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td2 = document.getElementById("td" + i + j);
var circle2 = document.createElement("span");
circle2.setAttribute("class", "redCircle");
circle2.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle2.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td2.appendChild(circle2);
isEmpty[i][j] = false;
}
}
}
else if (i > 4) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td3 = document.getElementById("td" + i + j);
var circle3 = document.createElement("span");
circle3.setAttribute("class", "whiteCircle");
circle3.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle3.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td3.appendChild(circle3);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td4 = document.getElementById("td" + i + j);
var circle4 = document.createElement("span");
circle4.setAttribute("class", "whiteCircle");
circle4.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle4.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td4.appendChild(circle4);
isEmpty[i][j] = false;
}
}
}
}
}
function AlertToPressOnSquare() {
alert("Player " + player + ", please press on the square to which you would like to move the piece");
if (player == 1)
player = 2;
else if (player == 2)
player = 1;
}
function MoveToSquare(i, j) { //The function I want to use in the td1 event listener
if (wasClicked && isEmpty[i][j]) {
var lastClickedId = lastClicked.getAttribute("id");
var lastClickedLocation = lastClickedId[6] + lastClickedId[7];
var v1 = parseInt(lastClickedId[6], 10);
var v2 = parseInt(lastClickedId[7], 10);
var tdFrom = document.getElementById("td" + lastClickedLocation);
var tdTo = document.getElementById("td" + i.toString() + j.toString());
if (lastClicked.getAttribute("class") == "whiteCircle") {
if (v1 == i - 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
else if (lastClicked.getAttribute("class") == "redCircle") {
if (v1 == i + 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
alert("Player " + player + ", please press on the piece you would like to move");
wasClicked = false;
}
}
So, the weird behavior is as follows: Every time I click on a td in the table and run the CheckIandJForLater function, I get the value 8 for both i and j. They should not get these values, as i and j are supposed to be updated in the for loop. Moreover, they should never reach the value of 8, since both the loops run between 0 and 7.
It's also worth noting that if I put alert(i); and alert(j); regularly, without the CheckIAndJForLater function, their values are printed fine.
I really struglle in finding out how to solve this weird behavior. May someone help me? Thank you.
Why is that behavior happening? Is there a solution?
I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.
This might be very basic problem. I found the similar solution on Stack Overflow for formatting the phone number and I used it for asp:TextBox control, but I want this code to be work for multiple phone number textbox control rather than passing IDs directly. I have five different phone field and all those textbox are asp:TextBox. I want to call the same code from all those filed. (I am looking this solution in JavaScript only)
Here is my JS code:
/*Start of phone number formating */
var n;
var p;
var p1;
function format_phone() {
p = p1.value
if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ") ";
}
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
if (p.length > 3) {
d1 = p.indexOf('(')
d2 = p.indexOf(')')
if (d2 == -1) {
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ") "
p31 = p.substring(5, l30);
pp = p30 + p31;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
if (p.length > 7) {
p11 = p.substring(d1 + 1, d2);
if (p11.length > 4) {
p12 = p11;
l12 = p12.length;
l15 = p.length
p13 = p11.substring(0, 4);
p14 = p11.substring(4, l12);
p15 = p.substring(d2 + 1, l15);
document.getElementById('<%=HomePhone.ClientID%>').value = "";
pp = "(" + p13 + ") " + p14 + p15;
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
l16 = p.length;
p16 = p.substring(d2 + 2, l16);
l17 = p16.length;
if (l17 > 3 && p16.indexOf('-') == -1) {
p17 = p.substring(d2 + 1, d2 + 5);
p18 = p.substring(d2 + 5, l16);
p19 = p.substring(0, d2 + 1);
pp = p19 + p17 + "-" + p18;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
setTimeout(format_phone, 100)
}
function getIt(m) {
n = m.name;
p1 = m;
format_phone()
}
/* End of phone number formating */
and asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onFocus="if(this.value==this.defaultValue)this.value='';" onclick="javascript:getIt(this)"
onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
And I have other similar four textboxes for phone field and I want to use the same formatting logic for all those. What is the best way to use this or any alternative JavaScript code from multiple textbox. Any help would be highly appreciated.
I don't remember where I found this solution but, it might help you out to format the phone fields:
<script type="text/javascript">
//Phone validation
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object) {
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object) {
phonevalue2 = ParseChar(object.value, zChar);
}
function backspacerUP(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 backspacerDOWN(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
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, 8);
p40 = p40 + "-"
p41 = pp.substring(8, 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 <= 5) {
cursorposition = cursorposition + 2
} else if (cursorposition == 6) {
cursorposition = cursorposition + 2
} else if (cursorposition == 7) {
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 < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 12) {
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>
And call this on your asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onkeydown="javascript:backspacerDOWN(this,event);"
onkeyup="javascript:backspacerUP(this,event);" />
And If you want to insert space after ')' you can use the following trick
function markSpace(field) {
if (field.value.includes(")")) {
field.value = field.value.split(')').join(') ');
}
if (field.value.includes(") ")) {
field.value = field.value.replace(/ +/g, ' ');
}
}
and call this as onblur="markSpace(this);" But I personally prefer using JQuery :)
I have to fadeIn and fadeOut the information of the setInterval at the end of the program: I want that after certain amount of time, the information slowly disappear and then reappear after the information slowly. I saw other example of this subject but I didn't find a solution, i don't know how to do it, any suggestion? (Excuse me for my horrible english).
var newsTitle = [];
var newsDate = [];
var pubDate = [];
var newsHours = [];
var newsLenght;
var resultDate = [];
var cDate = 0;
var w = 1;
var newsName = "La Repubblica";
function newsUpdateAll() {
cDate = new Date();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
extractData(xhttp);
}
};
xhttp.open("GET", "http://www.repubblica.it/rss/homepage/rss2.0.xml", true);
xhttp.send();
}
function extractData(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("item");
for (i = 0; i < x.length; i++) {
newsTitle[i] = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
pubDate[i] = x[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
var newnewsDate = new Date(pubDate[i]);
newsDate[i] = ((cDate - newnewsDate)/1000)/60;
}
newsLenght = x.lenght;
newsClassification();
setRules();
document.getElementById("news-title").innerHTML = newsTitle[0];
document.getElementById("news-name").innerHTML = newsName + ", " + newsHours[0];
}
function newsClassification() {
var length = newsDate.length;
for (var i = (length - 1); i >= 0; i--) {
for (var j = (length - i); j > 0; j--) {
if(newsDate[j] < newsDate[j-1]) {
var tmp = newsDate[j];
newsDate[j] = newsDate[j-1];
newsDate[j-1] = tmp;
var tmp2 = newsTitle[j];
newsTitle[j] = newsTitle[j-1];
newsTitle[j-1] = tmp2;
}
}
}
}
function setRules(){
for (i = 0; i < newsDate.length; i++) {
resultDate[i] = Math.round(newsDate[i]);
if (resultDate[i] >= 1440){
newsHours[i] = Math.round((resultDate[i] / 60) / 24);
if (newsHours[i] > 1){
newsHours[i] = newsHours[i] + " giorni fa:";
}else{
newsHours[i] = newsHours[i] + " giorno fa:";
}
}else if (resultDate[i] >= 60){
newsHours[i] = Math.round(resultDate[i] / 60);
if (newsHours[i] > 1){
newsHours[i] = newsHours[i] + " ore fa:";
}else{
newsHours[i] = newsHours[i] + " ora fa:";
}
}else{
newsHours[i] = resultDate[i];
if (newsHours[i] > 1){
newsHours[i] = newsHours[i] + " minuti fa:";
}else{
newsHours[i] = newsHours[i] + " minuto fa:";
}
}
}
}
newsUpdateAll();
setInterval(function (){
if (w > 55){
w = 1;
newsUpdateAll();
}
document.getElementById("news-title").innerHTML = newsTitle[w];
document.getElementById("news-name").innerHTML = newsName + ", " + newsHours[w];
w++;
},20000);
I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));