I want to replace the numbers in the HTML menu li link class"scrollTo" (created by JavaScript) to individual text rather than the 01, 02, 03, 04 numbers
function createSliderPagination(container){
var wrapper = $('<ol class="slot-navigation"></ol>');
container.children('.slot-slider').find('li').each(function(index){
var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'),
dot = $('').appendTo(dotWrapper);
dotWrapper.appendTo(wrapper);
var dotText = (index+1 < 10) ? '0' + (index+1): index+1;
dot.text(dotText);
});
wrapper.appendTo(container);
return wrapper.children('li');
}
Html code created is this that the JavaScript is creating
<ol class="slot-navigation">
<li>01</li>
<li class="selected">02</li>
<li>03</li>
<li>04</li>
<li>05</li>
</ol>
You can add an array which contains the texts you want to use instead of the numbers , as an example :
function createSliderPagination(container){
const links = ['first title','second title','third title','fourth title','fifth title'] // An array that contain the texts you want to use
var wrapper = $('<ol class="slot-navigation"></ol>');
container.children('.slot-slider').find('li').each(function(index){
var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'),
dot = $('').appendTo(dotWrapper);
dotWrapper.appendTo(wrapper);
var dotText = links[index]
dot.text(dotText);
});
wrapper.appendTo(container);
return wrapper.children('li');
}
You could use a switch statement to evaluate index :
function createSliderPagination(container) {
var wrapper = $('<ol class="slot-navigation"></ol>');
container.children('.slot-slider').find('li').each(function(index) {
var dotWrapper = (index == 0) ? $('<li class="selected"></li>') : $('<li></li>'),
dot = $('').appendTo(dotWrapper);
dotWrapper.appendTo(wrapper);
var dotText;
switch(index) {
case 0:
dotText = "Home";
break;
case 1 :
dotText = "Our services";
break;
case 2 :
dotText = "Third item";
break;
case 3 :
dotText = "Fourth item";
break;
default :
dotText = "Default";
break;
}
dot.text(dotText);
});
wrapper.appendTo(container);
return wrapper.children('li');
}
Related
I have a text file which contains list of dates and respective events, which looks as follows,
txt:
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
At first, I am using a simple split function to split the contents of the text file,
var text=xmlhttp.responseText;
var amber=text.split(':');
In the amber array each date and events are stored simultaneously, what I need to do is access the dates alone and split the day, month and year, I tried using the following code
var stwo="";
for (var i = 0; i < amber.length; i += 2) {
stwo = amber[i].split('-');
}
but when I try to access the contents of stwo[] it shows "undefined", I've also tried declaring stwo like this
stwo=[" "," "];
because I thought stwo wasn't defined as an array, what have I done wrong? Is there any other way I can split the dates?
here is my complete code.,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<title>SAPUI5 EVENT CALENDAR</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap" data-sap-ui-libs="sap.m,sap.ui.layout,sap.me"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-theme="sap_bluecrystal"></script>
<script>
jQuery.sap.require("sap.me.Calendar");
jQuery.sap.require("sap.m.RadioButton");
calendar = new sap.me.Calendar({
firstDayOffset : 1
});
var xmlhttp,text;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET','C:/Users/Manimaran/Desktop/project/nn.txt',false);
xmlhttp.send();
var text=xmlhttp.responseText;
var amber=text.split(':');
for (var t = 0; t < amber.length; t+=2)
{
calendar.toggleDatesType([amber[t]],sap.me.CalendarEventType.Type07,
true);
//document.write(a[i+1]+"<br>");
}
calendar.toggleDatesType([ "2017/05/15" ],
sap.me.CalendarEventType.Type07,
true);
var msgLabel = new sap.m.Label({
width : "100%"
});
calendar.attachTapOnDate(function(oEvent) {
/* date=oEvent.getParameters().date;
msgLabel.setText(date)*/
});
calendar.attachChangeCurrentDate(function(oEvent) {
var stwo=[" "," "];
for (var i=0;i<amber.length;i+=2)
{
stwo=amber[i].split('-');
}
/*for (var j=1;j<stwo.length;j+=3)
{
switch(stwo[j]){
case '01' : stwo[j]="Jan";
break;
case '02' : stwo[j]="Feb";
break;
case '03' : stwo[j]="Mar";
break;
case '04' : stwo[j]="Apr";
break;
case '05' : stwo[j]="May";
break;
case '06' : stwo[j]="Jun";
break;
case '07' : stwo[j]="Jul";
break;
case '08' : stwo[j]="Aug";
break;
case '09' : stwo[j]="Sep";
break;
case '10' : stwo[j]="Oct";
break;
case '11' : stwo[j]="Nov";
break;
case '12' : stwo[j]="Dec";
break;
default:"gokka makka";
}
}*/
var comp=oEvent.getParameters().currentDate;
var tmp=comp.split(' ');
if(tmp[1]==tmp[1]){
msgLabel.setText(stwo);
alert(stwo[1]);
}else{
alert('error');
}
});
var unselectBtn = new sap.m.Button({
text : "unselect all",
press : function() {
var aDates = calendar.getSelectedDates();
calendar.unselectAllDates();
msgLabel.setText("unselected " + aDates.length + " dates");
alert(text);
}
});
var app = new sap.m.App();
var page = new sap.m.Page({
headerContent : unselectBtn,
content : [ calendar, new sap.m.Label({
width : "100%",
text : "Messages log"
}), msgLabel]
});
// Colgate: weeks start on sunday, and show 2 months
calendar.setSingleRow(false);
calendar.setMonthsToDisplay(1);
// calendar.setWeeksPerRow(1);
calendar.setMonthsPerRow(1);
calendar.setFirstDayOffset(0);
app.addPage(page);
app.placeAt('content');
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
<p id="display"></p>
</body>
</html>
You are just assigning the value to stwo every time..
So all the split values before the last one will be lost.
Also the last string in the split(':') would be empty because after the last : there is nothing in the give string.
So finally nothing will be assigned to stwo.
Check this snippet
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo;
console.log(amber);
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "") {
stwo = amber[i].split('-');
}
}
console.log(stwo);
If you can see, even if check for empty strings.. Only the last date will be split and added to the variable stwo.
To store each split value you can use an Array within an Array (MultiDimesional array)
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo = new Array();
console.log(amber);
var j = 0;
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "" && amber[i].indexOf('-') > 1) {
stwo[j] = amber[i].split('-');
j++;
}
}
console.log(stwo);
You parse through each log line like so:
// ES6
const txt = `
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
`
const amber = txt.trim().split('\n');
const logDates = amber.map(line => line.split(':')[0]);
const logDatesSplitted = logDates.map(logDate => logDate.split('-'));
console.log(logDatesSplitted);
// ES5: Fast Splitting by colon
var amber_ = txt.trim().split(':');
var logDates_ = [];
for(var i = 0; i < amber_.length; i += 2) {
if(amber_[i] == "") continue; // filter out last empty log record;
var logDate = amber_[i].trim().split('-');
logDates_.push(logDate);
}
console.log(logDates_);
Checkout this
var test = '2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:';
test = test.replace(/:+$/g,"");
var test1 = test.split(':');
var test2 = [];
for (var i = 0; i < test1.length; i += 2) {
test2.push(test1[i].split('-'));
//console.log(test2);
}
console.log(test2);
I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />
//id define
var id = function (name) {
return{
element : document.getElementById(name),
html : function (data) {
var ids = this.element;
if (data != undefined) {ids.innerHTML=data;}
else{return ids.innerHTML;}},
val : function (data) {
var ids = this.element;
if (data != undefined) {ids.value=data;}
else{return ids.value;}},
hide : function () {this.element.style.display="none";},
show : function () {this.element.style.display="block";},
clsremove : function (data) {this.element.classList.remove(data);},
clsadd : function (data) {this.element.classList.add(data);},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
//class define
var cls = function (name) {
return{
element : document.getElementsByClassName(name),
html : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].innerHTML=data;}
else{return ids[i].innerHTML;}}},
val : function (data) {
var ids = this.element;
for (var i=0; i<ids.length; i++) {
if (data != undefined) {ids[i].value=data;}
else{return ids[i].value;}}},
hide : function () { var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="none";}},
show : function () {var ids = this.element;for (var i=0; i<ids.length; i++) {ids[i].style.display="block";}},
tex : function (data) { var latex = data.replace(/\^/g, "");
var latex_form = latex.replace(/([a-z])(\d+)/g,
function myFunction(tot,c1,c2) {var tag=(c1 =='^'?'sup':'sup');return c1+'<'+tag+'>'+c2+'</'+tag+'>';});
this.element.innerHTML= latex_form;
}
}
}
<!DOCTYPE html>
<html>
<head>
<script src="jfile/myquery.js"></script>
<script src="steps.js"></script>
</head>
<body>
<input id="myInput" type="text" value="20x+5k-10p-y=0">
<button onclick="checkFruit()">Check Fruit</button>
<p id="equ1"></p>
<p id="equ2"></p>
<p id="equ3"></p>
<p id="equ4"></p>
<p id="equ5"></p>
<p id="equ1p"></p>
<p id="equ2p"></p>
<p id="equ3p"></p>
<p id="equ4p"></p>
<p id="equ5p"></p>
<p id="xoneans1"></p>
<p id="xoneans2"></p>
<p id="xoneans3"></p>
<p id="xoneans4"></p>
<p id="xoneans5"></p>
<p id="xoneans6"></p>
<p id="xoneans7"></p>
<p id="xoneans8"></p>
<p id="xoneans9"></p>
<p id="xoneans10"></p>
<script>
function checkFruit() {
var reg =/([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var equation = id("myInput").val();
var spli= reg.exec(equation);
alert(spli);
var text;
var y= document.getElementById("myInput").value;
switch(y) {
case "20x+5k-10p-y=0":
ans = "First add both side for -20";
ans1= "Both side added by 10p";
ans2= "Next both side added by y";
ans3= "Divide by both side 5";
ans4= "Solution for k value";
document.getElementById("equ1").innerHTML = ans;
document.getElementById("equ2").innerHTML = ans1;
document.getElementById("equ3").innerHTML = ans2;
document.getElementById("equ4").innerHTML = ans3;
document.getElementById("equ5").innerHTML = ans4;
break;
case "20x+5k-10p-y=0p":
ans5p = "First add both side for -20";
ans6p= "Both side added by -5k";
ans7p= "Next both side added by y";
ans8p= "Divide by both side -10";
ans9p= "Solution for p value";
document.getElementById("equ1p").innerHTML = ans5p;
document.getElementById("equ2p").innerHTML = ans6p;
document.getElementById("equ3p").innerHTML = ans7p;
document.getElementById("equ4p").innerHTML = ans8p;
document.getElementById("equ5p").innerHTML = ans9p;
break;
case "20x+5k-10p-y=0x":
xone1 = "First add both side for -5";
xtwo2= "Both side added by 10p";
xthr3= "Next both side added by y";
xfour4= "Divide by both side 20";
xfive5= "Solution for x value";
document.getElementById("xoneans1").innerHTML = xone1;
document.getElementById("xoneans2").innerHTML = xtwo2;
document.getElementById("xoneans3").innerHTML = xthr3;
document.getElementById("xoneans4").innerHTML = xfour4;
document.getElementById("xoneans5").innerHTML = xfive5;
break;
case "20x+5k-10p-y=0y":
xone6 = "First add both side for -20";
xtwo7= "Both side added by -5k";
xthr8= "Next both side added by 10p";
xfour9= "Divide by both side -1";
xfive10= "Solution for y value";
document.getElementById("xoneans6").innerHTML = xone6;
document.getElementById("xoneans7").innerHTML = xtwo7;
document.getElementById("xoneans8").innerHTML = xthr8;
document.getElementById("xoneans9").innerHTML = xfour9;
document.getElementById("xoneans10").innerHTML = xfive10;
break;
// add the default keyword here
}
}
</script>
<p id="super"></p>
</body>
</html>
I have some code in the linear equation steps. How can I allow the user to open the drop-down list, and select a single letter, for which my code will then show the corresponding algorithm steps?
For example, I would like to display the menu
[x
y
z
p]
from that button, the user selects x, and my code should display the steps listed in the switch case for x.
I have created a list of items that contains information such as a taskname (i.e. take out the garbage), who must do the task, and what day of the week the task needs to be done by. All this information is gathered through text inputs in the html, then displayed as a list item using JavaScript.
Im wondering if there is a simple way to sort my list by the day of the week the task needs to be done. I was thinking perhaps i should add numerical value of 1-7 to strings containing days of the week. (for instance one that contains monday would have a value of 1, ones that have sunday have a value of 7). Then i could sort these numerically.
If anyone could show me how to do this with JavaScript (not jQuery), or an easier way, that would be greatly appreciated. (The more comments in the code the better).
Thanks
//links html elements to corresponding javascript variable names
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function(taskText, personText, dayText){
var self = this;
self.name="taskName";
self.listItem;
self.init = function(){
//create html elements
self.listItem = document.createElement("li");
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + " ";
//create text box and have it display information from the previous inputed person
var text2 = document.createElement("text");
text2.innerText = personText + " ";
//create text box and have it display information from the previous inputed day of the week
var text3 = document.createElement("text");
text3.innerText = dayText + " ";
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(text2);
self.listItem.appendChild(text3);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild (self.listItem);
}
self.deleteMe = function(){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function (){
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
There is an in-built javascript function that helps in getting the day of the week.
//Calling the date function
var date = new Date();
//Getting the day of the week
var day_of_week = date.getDay();
date.getDay() returns a value from 0 to 6 for sunday to saturday respectively
//A function to get the day of the week
function dayOfTheWeek()
{
var date = new Date();
var day_of_week = date.getDay();
switch (day_of_week)
{
case 0: return "sunday"
case 1: return "monday"
case 2: return "tuesday"
case 3: return "wednessday"
case 4: return "thursday"
case 5: return "friday"
default: return "saturday"
}
}
//Calling the function
var day_of_week_in_string = dayOfTheWeek();
(javascript)
//define your task objects as an array (outside of TaskObject)
var tasks = [];
//retrieve a number rather than a text value
var dayInput = document.getElementById('dayInput').selectedIndex
var newTask = ...
//add this task object to the Task array
tasks.push(newTask)
//now you can sort the array:
tasks.sort(function(a, b){return a.dayInput-b.dayInput});
(html)
<select id="dayInput">
<option value="0">Monday</option>
<option value="1">Tuesday</option>
<option value="2">Wednesday</option>
<option value="3">Thursday</option>
<!-- etc.. -->
</select>
Here is my solution to your problem. When a new li is created, you store a hidden attribute called "data-day-text" and attach it to the li. When you sort, you remove the ul from the DOM (for performance gains), sort the lis according to the data-day-text, then re-attach the lis and the ul.
http://jsfiddle.net/g3et9abh/3/
html:
<div id="allTasksContainer">
<ul id="allTasks"></ul>
</div>
<p>task:
<input type="text" id="taskInput" />
</p>
<p>person:
<input type="text" id="personInput" />
</p>
<p>day:
<input type="text" id="dayInput" />
</p>
<button id="addBtn">add</button>
<button id="sortBtn">sort</button>
javascript:
//links html elements to corresponding javascript variable names
var allTasksContainer = document.getElementById('allTasksContainer');
var allTasks = document.getElementById('allTasks');
var taskInput = document.getElementById('taskInput');
var personInput = document.getElementById('personInput');
var dayInput = document.getElementById('dayInput');
var addBtn = document.getElementById('addBtn');
var sortBtn = document.getElementById('sortBtn');
//Create Task List based on input put in text fields
var TaskObject = function (taskText, personText, dayText) {
var self = this;
self.name = "taskName";
self.listItem;
self.init = function () {
//create html elements
self.listItem = document.createElement("li");
self.listItem.dataset.dayText = dayText;
//create text box and have it display information from the previous inputed task
var text = document.createElement("text");
text.innerText = taskText + ' ' + personText + ' ' + dayText;
//create delete button and functionality
var deleteBtn = document.createElement("button");
deleteBtn.innerHTML = "delete";
deleteBtn.onclick = self.deleteMe;
// combine html elements
self.listItem.appendChild(text);
self.listItem.appendChild(deleteBtn);
allTasks.appendChild(self.listItem);
}
self.deleteMe = function () {
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
addBtn.onclick = function () {
var newTask = new TaskObject(taskInput.value, personInput.value, dayInput.value)
newTask.init();
}
sortBtn.onclick = function () {
allTasksContainer.removeChild(allTasks);
var nodes = [].slice.call(allTasks.getElementsByTagName('li'), 0);
[].sort.call(nodes, function (a, b) {
return b.dataset.dayText < a.dataset.dayText ? 1 : b.dataset.dayText > a.dataset.dayText ? -1 : 0;
});
while (allTasks.firstChild) {
allTasks.removeChild(allTasks.firstChild);
}
nodes.forEach(function (node) {
allTasks.appendChild(node);
});
allTasksContainer.appendChild(allTasks);
}
This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.
It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
Existing Code:
JS
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var text_edited = text.replace(/_/g, " ");
var currentHtml = $(".dropdown_box span").html();
var positionLocation = currentHtml.indexOf(text_edited);
var numberChecked = $('input[name="color[]"]:checked').length;
if (positionLocation < 1) {
if (numberChecked <= 3) {
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text_edited);
} else {
$(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
}
} else {
(currentHtmlRevised = currentHtml.replace(text_edited, ""));
$(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml));
}
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>
Easiest to just replace the entire content each time. Also use the change event instead of the click event.
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box span");
if (checked.length > 3) {
span.html("" + checked.length + " selected");
}
else {
span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
}
});
Example: http://jsfiddle.net/bman654/FCVjj/
try this:
$('.cbx').change(function(){
var cbx = $('.cbx:checked');
var str = '';
if (cbx.length<=3 && cbx.length!=0){
for (var i=0;i<cbx.length;i++){
if (i>0) str += ', ';
str += cbx[i].value;
}
} else if (cbx.length==0){
str = 'Colors';
} else {
str = cbx.length;
}
$('.dropdown_box span').html(str);
});