I am working on web application built on Spring Boot and using JavaScript as a frontend technology. So here I am facing a problem on my index page. There are dropdowns on which after clicking there are some options coming from API. The problem is, when my index page loads then if user clicks on dropdown to choose some category then data does not loaded. It is a custom dropdown.
This is an HTML of dropdown:
<div class="col-6">
<label class="sr-only" for="inlineFormInputGroup" style="color: red;"> </label>
<div class="custom-select-div">
<select id="category" name="category">
<option value='0'>Choose your category</option>
</select>
</div>
</div>
Below is my JavaScript code for custom dropdown:
<script>
$(document).ready(function() {
setTimeout(function(){
getcategorylist();
});
setTimeout(function(){
var x, i, j, l, ll, selElmnt, a, b, c;
x = document.getElementsByClassName("custom-select-div");
l = x.length;
for (i = 0; i < l; i++) {
selElmnt = x[i].getElementsByTagName("select")[0];
ll = selElmnt.length;
a = document.createElement("DIV");
a.setAttribute("class", "select-selected");
a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
x[i].appendChild(a);
b = document.createElement("DIV");
b.setAttribute("class", "select-items select-hide");
for (j = 1; j < ll; j++) {
c = document.createElement("DIV");
c.innerHTML = selElmnt.options[j].innerHTML;
c.addEventListener("click", function(e) {
var y, i, k, s, h, sl, yl;
s = this.parentNode.parentNode.getElementsByTagName("select")[0];
sl = s.length;
h = this.parentNode.previousSibling;
for (i = 0; i < sl; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
s.selectedIndex = i;
h.innerHTML = this.innerHTML;
y = this.parentNode.getElementsByClassName("same-as-selected");
yl = y.length;
for (k = 0; k < yl; k++) {
y[k].removeAttribute("class");
}
this.setAttribute("class", "same-as-selected");
break;
}
}
h.click();
});
b.appendChild(c);
}
x[i].appendChild(b);
a.addEventListener("click", function(e) {
e.stopPropagation();
closeAllSelect(this);
this.nextSibling.classList.toggle("select-hide");
this.classList.toggle("select-arrow-active");
});
}
function closeAllSelect(elmnt) {
var x, y, i, xl, yl, arrNo = [];
x = document.getElementsByClassName("select-items");
y = document.getElementsByClassName("select-selected");
xl = x.length;
yl = y.length;
for (i = 0; i < yl; i++) {
if (elmnt == y[i]) {
arrNo.push(i)
} else {
y[i].classList.remove("select-arrow-active");
}
}
for (i = 0; i < xl; i++) {
if (arrNo.indexOf(i)) {
x[i].classList.add("select-hide");
}
}
}
document.addEventListener("click", closeAllSelect);
},500);
});
function getcategorylist(){
var maincategory = document.getElementById('maincategory').value;
$.post("<%=AkApiUrl.getcategorybymaincategory%>",{
maincategory : maincategory,
},
function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
debugger
var list = data.response;
var categorys='';
if(list.length > 0){
for (var i = 0; i < list.length; i++) {
var content = "<option value='"+list[i].categoryid+"'>"+list[i].name+"</option>";
categorys = categorys + content;
}
}
categorys = "<option value='0' style='display: none;'>Choose your category</option>"+categorys;
document.getElementById('category').innerHTML = categorys;
}else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
$("#searchBtn").click(function() {
var maincategoryid = document.getElementById('maincategory').value;
var latitude = document.getElementById("latitude").value;
var longitude = document.getElementById("longitude").value;
var location = document.getElementById("address").value;
var categoryid = document.getElementById("category").value;
var category = $("#category option:selected").text();
var maincategory = "Truck-Trailer";
if(maincategoryid == '1'){
maincategory = "Truck-Trailer";
}else if(maincategoryid == '2'){
maincategory = "Cars";
}else if(maincategoryid == '3'){
maincategory = "RV-Bus";
}else {
maincategory = "Truck-Trailer";
}
if (latitude == "" || latitude == null || longitude == "" || longitude == null || categoryid == 0) {
if (latitude == "" || latitude == null || longitude == "" || longitude == null) {
$("#location").addClass("errorInput");
return false;
} else {
$("#location").removeClass("errorInput");
}
if (categoryid == 0) {
$("#category").addClass("errorInput");
return false;
} else {
$("#category").removeClass("errorInput");
}
}else{
category = category.replaceAll(" & ", "-").replaceAll(" ", "-");
location = location.replaceAll(", ", "-").replaceAll("&", "-").replaceAll(" ", "_");
document.getElementById("listingForm").action = "<%=WebUrl.listing%>/"+maincategory+"/"+category+"/"+location;
document.getElementById("listingForm").submit();
}
});
</script>
Data did not get loaded on first time when DOM loaded after refreshing page from 1-2 times then sometimes data get visible inside the dropdown. So what should I do?
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?
While we adding HTML into the HTML output render has in the DIV. If we added something like following
<div class="test" w3-include-html="template_build/header/header-classic.html"></div>
But the output render has incldued that
<div class="test">MY INCLUDED CONTENT</div>
I want to remove that div class="test" on rendering process on w3data.js.
Can someone help me?
Snippet 1 features a simple function that removes any given attribute from any given element. Snippet 2 is the w3data.js with an extra line at 126:
elmnt.removeAttribute("class");
You may use either one to get the same result
SNIPPET 1
removeAttr(".test", "class");
function removeAttr(target, attribute) {
var target = document.querySelector(target);
target.removeAttribute(attribute);
}
.test { color:red }
<div class="test">THIS CONTENT SHOULD BE BLACK TEXT, NOT RED</div>
SNIPPET 2
/* W3Data ver 1.31 by W3Schools.com */
var w3DataObject = {};
function w3DisplayData(id, data) {
var htmlObj, htmlTemplate, html, arr = [],
a, l, rowClone, x, j, i, ii, cc, repeat, repeatObj, repeatX = "";
htmlObj = document.getElementById(id);
htmlTemplate = w3InitTemplate(id, htmlObj);
html = htmlTemplate.cloneNode(true);
arr = w3GetElementsByAttribute(html, "w3-repeat");
l = arr.length;
for (j = (l - 1); j >= 0; j -= 1) {
cc = arr[j].getAttribute("w3-repeat").split(" ");
if (cc.length == 1) {
repeat = cc[0];
} else {
repeatX = cc[0];
repeat = cc[2];
}
arr[j].removeAttribute("w3-repeat");
repeatObj = data[repeat];
if (repeatObj && typeof repeatObj == "object" && repeatObj.length != "undefined") {
i = 0;
for (x in repeatObj) {
i += 1;
rowClone = arr[j];
rowClone = w3NeedleInHaystack(rowClone, "element", repeatX, repeatObj[x]);
a = rowClone.attributes;
for (ii = 0; ii < a.length; ii += 1) {
a[ii].value = w3NeedleInHaystack(a[ii], "attribute", repeatX, repeatObj[x]).value;
}
(i === repeatObj.length) ? arr[j].parentNode.replaceChild(rowClone, arr[j]): arr[j].parentNode.insertBefore(rowClone, arr[j]);
}
} else {
console.log("w3-repeat must be an array. " + repeat + " is not an array.");
continue;
}
}
html = w3NeedleInHaystack(html, "element");
htmlObj.parentNode.replaceChild(html, htmlObj);
function w3InitTemplate(id, obj) {
var template;
template = obj.cloneNode(true);
if (w3DataObject.hasOwnProperty(id)) {
return w3DataObject[id];
}
w3DataObject[id] = template;
return template;
}
function w3GetElementsByAttribute(x, att) {
var arr = [],
arrCount = -1,
i, l, y = x.getElementsByTagName("*"),
z = att.toUpperCase();
l = y.length;
for (i = -1; i < l; i += 1) {
if (i == -1) {
y[i] = x;
}
if (y[i].getAttribute(z) !== null) {
arrCount += 1;
arr[arrCount] = y[i];
}
}
return arr;
}
function w3NeedleInHaystack(elmnt, typ, repeatX, x) {
var value, rowClone, pos1, haystack, pos2, needle = [],
needleToReplace, i, cc, r;
rowClone = elmnt.cloneNode(true);
pos1 = 0;
while (pos1 > -1) {
haystack = (typ == "attribute") ? rowClone.value : rowClone.innerHTML;
pos1 = haystack.indexOf("{{", pos1);
if (pos1 === -1) {
break;
}
pos2 = haystack.indexOf("}}", pos1 + 1);
needleToReplace = haystack.substring(pos1 + 2, pos2);
needle = needleToReplace.split("||");
value = undefined;
for (i = 0; i < needle.length; i += 1) {
needle[i] = needle[i].replace(/^\s+|\s+$/gm, ''); //trim
//value = ((x && x[needle[i]]) || (data && data[needle[i]]));
if (x) {
value = x[needle[i]];
}
if (value == undefined && data) {
value = data[needle[i]];
}
if (value == undefined) {
cc = needle[i].split(".");
if (cc[0] == repeatX) {
value = x[cc[1]];
}
}
if (value == undefined) {
if (needle[i] == repeatX) {
value = x;
}
}
if (value == undefined) {
if (needle[i].substr(0, 1) == '"') {
value = needle[i].replace(/"/g, "");
} else if (needle[i].substr(0, 1) == "'") {
value = needle[i].replace(/'/g, "");
}
}
if (value != undefined) {
break;
}
}
if (value != undefined) {
r = "{{" + needleToReplace + "}}";
if (typ == "attribute") {
rowClone.value = rowClone.value.replace(r, value);
} else {
w3ReplaceHTML(rowClone, r, value);
}
}
pos1 = pos1 + 1;
}
return rowClone;
}
function w3ReplaceHTML(a, r, result) {
var b, l, i, a, x, j;
if (a.hasAttributes()) {
b = a.attributes;
l = b.length;
for (i = 0; i < l; i += 1) {
if (b[i].value.indexOf(r) > -1) {
b[i].value = b[i].value.replace(r, result);
}
}
}
x = a.getElementsByTagName("*");
l = x.length;
a.innerHTML = a.innerHTML.replace(r, result);
}
}
function w3IncludeHTML() {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("w3-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
elmnt.removeAttribute("w3-include-html");
elmnt.removeAttribute("class"); // Add this expression
w3IncludeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
function w3Http(target, readyfunc, xml, method) {
var httpObj;
if (!method) {
method = "GET";
}
if (window.XMLHttpRequest) {
httpObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpObj) {
if (readyfunc) {
httpObj.onreadystatechange = readyfunc;
}
httpObj.open(method, target, true);
httpObj.send(xml);
}
}
There is a strange behavior with DOMParser. When I use "text/xml" as the parameter I get my object and each time I use a child (like parentNodes), the child is itself a DOM object. However, when I use "text/html" as the parameter, the children are not DOM objects. Why is that and how can I have DOM objects for all the children?
Here is what I do:
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html").getElementsByTagName('p');
console.log(doc[0].childNodes[0]);
My childNode returns the element but not as a DOM object...
Edit:
Here are my recursive functions:
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
pdfContent[vertical][horizontal].push(object);
}
};
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
I made a few assumptions on what the values are and after I Added a few verifications like if(node.attributes.length>0)into your code, it seems to work.
var payment={htmlContent:[['<p>some<em>text</em></p>', '<p>some<span>text<strong>here</strong></span></p>'],['<p>some<s>text</s></p>', '<p>some<span style="color:#FF00FF">text</span></p>']]};
var getParents = function(node, parentNodes){
if(node.nodeName == 'span'){
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else if(node.nodeName == 'p' && node.attributes.length > 0) {
parentNodes.push(node.nodeName);
if(node.attributes.length>0)
parentNodes.push(node.attributes[0].nodeValue);
} else {
parentNodes.push(node.nodeName);
}
if(node.parentNode.nodeName != '#document'){
getParents(node.parentNode, parentNodes);
}
return parentNodes;
};
var parse = function(node, vertical, horizontal, paragraph){
if(node.childNodes.length > 0){
for(var int = 0; int < node.childNodes.length; int++){
parse(node.childNodes[int], vertical, horizontal, paragraph);
}
} else{
var object = {};
var attributes = getParents(node, []);
console.log(attributes);
for(var int = 0; int < attributes.length; int++) {
// right alignment
if(/text-align/i.test(attributes[int])){
object.alignment = attributes[int].split(": ")[1].replace(';','');
} else if (/color/i.test(attributes[int])) {
// color
object.color = attributes[int].split(":")[1];
} else if (attributes[int] == 'em') {
// italic
if (object.italics) {
delete object.bold;
object.bolditalics = true;
} else {
object.italics = true;
}
} else if (attributes[int] == 'strong') {
// bold
if (object.italics) {
delete object.italics;
object.bolditalics = true;
} else {
object.bold = true;
}
} else if (attributes[int] == 'u') {
// underline
object.decoration = 'underline';
} else if (attributes[int] == 's') {
// strike
object.decoration = 'lineThrough';
}
}
object.text = node.textContent;
if(!pdfContent[vertical])pdfContent[vertical]=[];
if(!pdfContent[vertical][horizontal])
pdfContent[vertical][horizontal]=[];
pdfContent[vertical][horizontal].push(object);
}
};
var pdfContent = [];
for(var vertical = 0; vertical < payment.htmlContent.length; vertical++) {
for(var horizontal = 0; horizontal < payment.htmlContent[vertical].length; horizontal++) {
var parser = new DOMParser();
var paragraphs = parser.parseFromString(payment.htmlContent[vertical][horizontal], "text/xml").getElementsByTagName('p');
for (var paragraph = 0; paragraph < paragraphs.length; paragraph++) {
for (var num = 0; num < paragraphs[paragraph].childNodes.length; num++) {
parse(paragraphs[paragraph].childNodes[num], vertical, horizontal, paragraph);
}
}
}
}
for(var i=0; i<pdfContent.length; i++){
for(var j=0; j<pdfContent[i].length; j++){
document.querySelector('#log').textContent+=pdfContent[i][j].toSource();
}
}
<p id="log"></p>
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;
}
});
I have a problem. I'm trying to do a show/hide on the "activationframe" and "equipmentframe" divs based on a radio button selection. I had it working fine but then the client decided to add styled radio buttons to the equation. That has broken my show/hide toggle. How do I incorporate that into the styled radio button JS?
Here is the styled radio buttons script:
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";
document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');
var Custom = {
init: function() {
var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
for(a = 0; a < inputs.length; a++) {
if((inputs[a].type == "radio") && inputs[a].className == "styled") {
span[a] = document.createElement("span");
span[a].className = inputs[a].type;
if(inputs[a].checked == true) {
position = "0 -" + (radioHeight*2) + "px";
span[a].style.backgroundPosition = position;
}
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
inputs[a].onchange = Custom.clear;
if(!inputs[a].getAttribute("disabled")) {
span[a].onmousedown = Custom.pushed;
span[a].onmouseup = Custom.check;
} else {
span[a].className = span[a].className += " disabled";
}
}
}
inputs = document.getElementsByTagName("select");
for(a = 0; a < inputs.length; a++) {
if(inputs[a].className == "styled") {
option = inputs[a].getElementsByTagName("option");
active = option[0].childNodes[0].nodeValue;
textnode = document.createTextNode(active);
for(b = 0; b < option.length; b++) {
if(option[b].selected == true) {
textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
}
}
span[a] = document.createElement("span");
span[a].className = "select";
span[a].id = "select" + inputs[a].name;
span[a].appendChild(textnode);
inputs[a].parentNode.insertBefore(span[a], inputs[a]);
if(!inputs[a].getAttribute("disabled")) {
inputs[a].onchange = Custom.choose;
} else {
inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
}
}
}
document.onmouseup = Custom.clear;
},
pushed: function() {
element = this.nextSibling;
if(element.checked == true && element.type == "radio") {
this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
} else {
this.style.backgroundPosition = "0 -" + radioHeight + "px";
}
},
check: function() {
element = this.nextSibling;
this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
group = this.nextSibling.name;
inputs = document.getElementsByTagName("input");
for(a = 0; a < inputs.length; a++) {
if(inputs[a].name == group && inputs[a] != this.nextSibling) {
inputs[a].previousSibling.style.backgroundPosition = "0 0";
}
element.checked = true;
}
},
clear: function() {
inputs = document.getElementsByTagName("input");
for(var b = 0; b < inputs.length; b++) {
if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
inputs[b].previousSibling.style.backgroundPosition = "0 0";
}
}
},
choose: function() {
option = this.getElementsByTagName("option");
for(d = 0; d < option.length; d++) {
if(option[d].selected == true) {
document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
}
}
}
}
window.onload = Custom.init;
Here is my old script that does the show/hide:
function showhideInstall(installtype) {
if (installtype == "equipmentswap") {
document.getElementById("activationframe").style.display = 'none';
document.getElementById("equipmentframe").style.display = 'block';
} else {
document.getElementById("activationframe").style.display = 'block';
document.getElementById("equipmentframe").style.display = 'none';
}
}
And finally, my HTML:
<div id="activationtoggle">
<form class="radiobuttons">
<input type="radio" name="installtype" value="activation" class="styled" onclick="showhideInstall(this.value);" checked> New Activation
<input type="radio" name="installtype" value="equipmentswap" class="styled" onclick="showhideInstall(this.value);" > Equipment Swap
</form>
</div>
<div id="activationframe">
<div id="activationchecklist">
code here
</div>
<div id="equipmentframe">
<div id="equipmentswap">
<h2>Equipment Swap</h2>
more code here
</div>
Any help would be GREATLY appreciated. I'm middling at JS (at best) and this has proven to be a giant time sink.
Had a friend help me resolve the problem, thanks for the help, everyone.
Here is the JS he supplied me with:
function showhideInstall(installtype) {
if (installtype == "equipmentswap") {
document.getElementById("activationframe").style.display = 'none';
document.getElementById("equipmentframe").style.display = 'block';
} else {
document.getElementById("activationframe").style.display = 'block';
document.getElementById("equipmentframe").style.display = 'none';
}
}
function newactivation( indexNum ) {
var inputs = document.getElementsByTagName("label");
for(a = 0; a < inputs.length; a++) {
if( inputs[a].id == "activation" + indexNum ){
inputs[a].style.color = "#b5b5b5";
}
}
var activechecked = 0;
for (var i = 1; i<= 7; i++) {
if(document.getElementById("activationcheck" + i).checked == true){
activechecked ++;
}else if(document.getElementById("activationnocheck" + i).checked == true){
activechecked ++;
}
}
if (activechecked <= 6) {document.getElementById("next").disabled= true;}
if (activechecked == 7) {document.getElementById("next").disabled= false; document.getElementById("next").style.cursor= "pointer"; }
}
function equipmentswap( indexNum ) {
var inputs = document.getElementsByTagName("label");
for(a = 0; a < inputs.length; a++) {
if( inputs[a].id == "equip" + indexNum ){
inputs[a].style.color = "#b5b5b5";
a=inputs.length + 1;
}
}
var activechecked = 0;
for (var i = 1; i<= 7; i++) {
if(document.getElementById("swapcheck" + i).checked == true){
activechecked ++;
}else if(document.getElementById("swapnocheck" + i).checked == true){
activechecked ++;
}
}
if (activechecked <= 6) {document.getElementById("equipnext").disabled= true;}
if (activechecked == 7) {document.getElementById("equipnext").disabled= false; document.getElementById("next").style.cursor= "pointer"; }
}