How to get the values of multiple JSON arrays using checkboxes? - javascript

HTML and JS
<div class="form-group form-inline text-center">
<label for="select_category">Select Category</label> 
<select class="custom-select" id="select_category" style="width: 500px;" onchange="listcatcb();">
<option selected></option>
</select>
</div>
<div class="container" id="cats">
<div class="form-check" id="catrbs"> </div>
<button class="btn btn-outline-secondary" onclick="nextcats();">Click Next!</button>
</div>
getallcategory();
function getallcategory() {
var link = 'allcat.json';
$.post(link).done(function (data) {
data2 = JSON.stringify(data);
var obj = jQuery.parseJSON(data2);
for (var i = 0; i < obj.length; i++) {
$("#select_category").append('<option value="' + obj[i].name + '">' + obj[i].name + '</option> ')
}
});
}
function listcatcb() {
selcat = document.getElementById("select_category").value;
var link = 'allcat.json';
$.post(link).done(function (data) {
data2 = JSON.stringify(data);
var obj = jQuery.parseJSON(data2);
for (var i = 0; i < obj.length; i++) {
if (obj[i].name == selcat) {
for (var j = 0; j < obj.length; j++) {
$("#catrbs").append('<input class="form-check-input catcbs" type="checkbox" id="' + obj[i].siblings[
j].name + '" value="' + obj[i].siblings[j].name + '"><label class="form-check-label" for="' +
obj[i].siblings[j].name + '">' +
obj[i].siblings[j].name +
'</label><br/>')
}
}
}
});
}
function nextcats() {
var link = 'allcat.json';
var checkedValue = $('.catcbs:checked').val();;
$.post(link).done(function (data) {
data2 = JSON.stringify(data);
var obj = jQuery.parseJSON(data2);
for (var i = 0; i < obj.length; i++) {
if (obj[i].name == selcat) {
for (var j = 0; j < obj.length; j++) {
if (obj[i].siblings[j].name == checkedValue) {
for (var k = 0; k < obj.length; k++) {
console.log(obj[i].siblings[j].siblings[k].name);
}
}
}
}
}
});
}
allcat.json
[ { "id" : "47"
, "name" : "Women"
, "parent" : "0"
, "status" : "Enabled"
, "itemcount": 44
, "siblings":
[ { "id" : "87"
, "name" : "Personal Care Appliances"
, "parent" : "47"
, "status" : "Enabled"
, "itemcount": 2
, "siblings":
[ { "id" : "88"
, "name" : "Hair Dryers"
, "parent" : "87"
, "status" : "Enabled"
, "itemcount": 2
, "siblings" : []
} ] }
, { "id" : "127"
, "name" : "Jewellary"
, "parent" : "47"
, "status" : "Enabled"
, "itemcount": 41
, "siblings":
[ { "id" : "128"
, "name" : "Artificial Jewellary"
, "parent" : "127"
, "status" : "Enabled"
, "itemcount": 41
, "siblings" : []
} ] } ] } ]
Here in this code if I select the 2 checkbox once at a time means I'm getting the output of only first JSON value...
if I uncheck one means I'm getting its respective values...
I mean for example if I select women from a category then I'm getting 2 checkboxes as 1.personal care appliances and 2.jewellery.
if I select multiple checkboxes once at the time means I'm getting only hair dryers(the value within personal care appliances) but I'm not getting artificial jewellery(value within jewellery)
if I select single at a time means I'm getting appropriate result please help me out with this error...
I've stuck here.

You had made a couple of mistakes in the for loop, please check the updated code snippet.
Here for (var j = 0; j < obj[i].siblings.length; j++) you missed to add siblings.
Here var checkedValue = $('.catcbs:checked').map(function(){
return $(this).val();
}).get();, here you was getting only single value, updated it to get the value in array.
Please go through it and let me know if you have any confusions.
const jsonData =
[
{
"id":"47",
"name":"Women",
"parent":"0",
"status":"Enabled",
"itemcount":44,
"siblings":[
{
"id":"87",
"name":"Personal Care Appliances",
"parent":"47",
"status":"Enabled",
"itemcount":2,
"siblings":[
{
"id":"88",
"name":"Hair Dryers",
"parent":"87",
"status":"Enabled",
"itemcount":2,
"siblings":[
]
}
]
},
{
"id":"127",
"name":"Jewellary",
"parent":"47",
"status":"Enabled",
"itemcount":41,
"siblings":[
{
"id":"128",
"name":"Artificial Jewellary",
"parent":"127",
"status":"Enabled",
"itemcount":41,
"siblings":[
]
}
]
}
]
}
];
function getallcategory() {
var link = jsonData;
for (var i = 0; i < link.length; i++) {
$("#select_category").append('<option value="' + link[i].name + '">' + link[i].name + '</option> ')
}
}
function listcatcb() {
selcat = document.getElementById("select_category").value;
var obj = jsonData;
for (var i = 0; i < obj.length; i++) {
if (obj[i].name == selcat) {
for (var j = 0; j < obj[i].siblings.length; j++) {
$("#catrbs").append('<input class="form-check-input catcbs" type="checkbox" id="' + obj[i].siblings[
j].name + '" value="' + obj[i].siblings[j].name + '"><label class="form-check-label" for="' +
obj[i].siblings[j].name + '">' +
obj[i].siblings[j].name +
'</label><br/>')
}
}
}
}
function nextcats() {
var obj = jsonData;
var checkedValue = $('.catcbs:checked').map(function(){
return $(this).val();
}).get();
var selectedItem='';
for (var i = 0; i < obj.length; i++) {
if (obj[i].name == selcat) {
for (var j = 0; j < obj[i].siblings.length; j++) {
if (checkedValue.indexOf(obj[i].siblings[j].name) != -1) {
for (var k = 0; k < obj.length; k++) {
selectedItem += `<p>${obj[i].siblings[j].siblings[k].name}</p>`;
}
}
}
}
}
$('#selected-item').html(selectedItem)
}
getallcategory();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="form-group form-inline text-center">
<label for="select_category">Select Category</label> 
<select class="custom-select" id="select_category" style="width: 500px;" onchange="listcatcb();">
<option selected></option>
</select>
</div>
<div class="container" id="cats">
<div class="form-check" id="catrbs"> </div>
<button class="btn btn-outline-secondary" onclick="nextcats();">Click Next!</button>
</div>
<div class="container" id="selected-item">
</div>
</div>

Related

Display only three numbers of the total pagination numbers in Javascript

I'm trying to add some pagination numbers in Javascript. I already achieved the pagination, I also can show all the pagination numbers but I would like to show only three numbers from all the numbers. Let my show you what I achieved until now:
var values = [{name : "a"}, {name : "b"}, {name : "c"}, {name : "d"}, {name : "e"}, {name : "f"}, {name : "g"}, {name : "h"}, {name : "i"}, {name : "j"}];
var current_page = 1;
var records_per_page = 6;
if (values.length <= 6) {
btn_prev.style.display = "none";
btn_next.style.display = "none";
}
function prevPage() {
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage() {
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page) {
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("poi-cat-id");
var page_span = document.getElementById("page");
var pageNum = document.getElementById("pageNum");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
var href = getRootWebSitePath();
for (var i = (page - 1) * records_per_page; i < (page * records_per_page) && i < values.length; i++) {
var nametoslug1 = values[i].name;
var slug1 = convertToSlug(nametoslug1);
listing_table.innerHTML += '<div class="event-desc"><p>' + values[i].name + '</p></div>';
}
if (page == 1) {
btn_prev.style.color = "#404141";
} else {
btn_prev.style.visibility = "visible";
btn_prev.style.color = "#0c518a";
}
if (page == numPages()) {
btn_next.style.color = "#404141";
} else {
btn_next.style.visibility = "visible";
btn_next.style.color = "#0c518a";
}
male();
maen();
}
//this is where I add all the numbers of the pagination
var totnum = numPages();
for (var i = 0; i < numPages() + 2; i++) {
// We do not want page 0. You could have started with i = 1 too.
$('#page-num-container').append('' + (i + 1) + '');
}
======EDIT=====
function newPage(){
$('.pageClick').on('click', function (e) {
e.preventDefault();
changePage($(this).index() + 1);
});
} //when I click the number the pages won't change
function numPages() {
return Math.ceil(values.length / records_per_page);
}
window.onload = function () {
changePage(1);
};
and this is my html :
<div>
<ul class="content-full" id="poi-cat-id"></ul>
<div class="pagination-poi-arrows">
<div class="prev">
<img src="~/img/left-arrow-pagination.svg" />
</div>
<div class="page-num-container" id="page-num-container">
</div>
<div class="nex">
<img src="~/img/right-arrow-pagination.svg" />
</div>
</div>
<div class="pagination-poi-arrows" id="pager"></div>
</div>
Can anybody help would be highly appreciated since I've been stuck with this for a while.
If you want to show the adjacent page numbers, then you have to start iterating at i=current_page until i=current_page + 2.
However, it seems that in your code, you start counting at 1 with your pages. I advise you to start at 0.
Now, back to your code. You need to replace the loop with the following (if you're counting from 1):
function updatePagination(page) {
for (var i = page - 1; i < page + 1; i++) {
$('#page-num-container').append('<a href="javascript:pagesNr()"
class="pageClick">' + (i + 1) + '</a>');
}
}
// you need to clear the element before you update it
function clearPagination() {
$('#page-num-container').empty();
}
You would call both of these methods at the end of the changePage() method.

next and previous JSON data with javascript

I' would like to create Next/Previous buttons for json array, but I can't get it to work.
This is the last one I have tried
<div id="text"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<script>
myFunction([
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
var out = "";
var i ;
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
}
</script>
You can convert json data to string or better say html with $.each like below. as you tagged jQuery, here is jQuery approach:
myFunction([{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
]);
function myFunction(arr) {
$.each(arr, function(i, v) {
$('#text').append('<div>' + v.text + '</div>');
});
}
var divs = $('.mydivs>div');
var now = 0;
divs.hide().first().show();
$("button[name=next]").click(function(e) {
divs.eq(now).hide();
now = (now + 1 < divs.length) ? now + 1 : 0;
divs.eq(now).show();
});
$("button[name=prev]").click(function(e) {
divs.eq(now).hide();
now = (now > 0) ? now - 1 : divs.length - 1;
divs.eq(now).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" class="mydivs"></div>
<button name="prev">go to previous div</button>
<button name="next">go to next div</button>
<div id="text">
</div>
<script>
var i = 0;
let arr = [
{
"text": "text0"
},
{
"text": "text1"
},
{
"text": "text2"
},
{
"text": "text3"
}
];
setInterval(function myFunction() {
var out = "";
out = '<p>' + arr[i].text + '</p> <br>';
document.getElementById("text").innerHTML = out;
console.log(out);
if (i < arr.length - 1) {
i += 1;
} else {
i = 0;
}
}, 1000)
</script>

How to use sort function and search function (regexp) together without strange errors?

In this prototype, I have "products" that are each individually stored in a div along with their price. I have added four buttons that sort the divs containing the products in alphabetical order (A-Z AND Z-A) as well as by price (lowest to highest and highest to lowest). These sorting functions work perfectly by themselves. I also have a search bar that acts as a search engine if you like an upon entering each character into the input field, will eliminate the products (div's) by name if they do not contain that letter(s). I have done this using a regular expression. This also worked by itself until I adapted it to try and work in conjunction with the sorting mechanisms.
Problem
I would like to be able to search for "products" using the search functionality to display the correct results regardless of what order the products have been sorted into.
Question
How is it possible to be able to display only the div's that contain the letter(s) searched for in the search bar regardless of the ordering (e.g. Z to A).
I think I ruined the search function itself by adding the index variable but you can't do list.name[i].match(res) can you? There is something wrong with the logic behind the search function. I believe the function that needs serious fixing is the searchProducts function.
The code AFTER I adapted the searchProducts function is below...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="resultsSpan"></div>
<div id="product0" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product1" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product2" style="height:60px; width:60px; background-color:blue;"></div>
<div id="product3" style="height:60px; width:60px; background-color:blue;"></div>
<button onclick="sortprods()">
Sort A-Z
</button>
<button onclick="sortprods2()">
Sort Z-A
</button>
<button onclick="sortprods3()">
Price (low to high)
</button>
<button onclick="sortprods4()">
Price (high to low)
</button>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
</body>
</html>
<script>
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
list.sort(AtoZ);
for (var i = 0; i<list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
function AtoZ(a,b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
function ZtoA(a,b) {
if (a.name < b.name)
return 1;
if (a.name > b.name)
return -1;
return 0;
}
function LowtoHigh(a,b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function HightoLow(a,b) {
if (a.price < b.price)
return 1;
if (a.price > b.price)
return -1;
return 0;
}
function sortprods(){
list.sort(AtoZ);
currentSort = "AtoZ";
for (var i = 0; i < list.length; i++) {
document.getElementById("product" + i).innerHTML = list[i].name + ", " + list[i].price;
}
}
function sortprods2(){
list.sort(ZtoA);
currentSort = "ZtoA";
for (var j = 0; j < list.length; j++) {
document.getElementById("product" + j).innerHTML = list[j].name + ", " + list[j].price;
}
}
function sortprods3(){
currentSort = "LowtoHigh";
list.sort(LowtoHigh);
for (var k = 0; k < list.length; k++) {
document.getElementById("product" + k).innerHTML = list[k].name + ", " + list[k].price;
}
}
function sortprods4(){
currentSort = "HightoLow";
list.sort(HightoLow);
for (var l = 0; l < list.length; l++) {
document.getElementById("product" + l).innerHTML = list[l].name + ", " + list[l].price;
}
}
var input = "";
var index = [];
var currentSort = "AtoZ";
function searchProducts(){
input = document.getElementById("searchbar").value;
if(input == ""){
document.getElementById("product0").style.display = "block";
document.getElementById("product1").style.display = "block";
document.getElementById("product2").style.display = "block";
document.getElementById("product3").style.display = "block";
}else{
switch(currentSort){
case "AtoZ":
list.sort(AtoZ);
for(var a = 0; a < list.length; a++){
document.getElementById("product" + a).innerHTML = list[a].name + ", " + list[a].price;
index.push(list[a].name);
}
index.sort();
break;
case "ZtoA":
list.sort(ZtoA);
for(var b = 0; b < list.length; b++){
document.getElementById("product" + b).innerHTML = list[b].name + ", " + list[b].price;
index.push(list[b].name);
}
index.sort();
index.reverse();
break;
case "LowtoHigh":
list.sort(LowtoHigh);
for(var c = 0; c < list.length; c++){
index.push(list[c].price);
}
index.sort(function(a, b){return a-b});
break;
case "HightoLow":
list.sort(HightoLow);
for(var d = 0; d < list.length; d++){
index.push(list[d].price);
}
index.sort(function(a, b){return b-a});
break;
}
test = input;
re = new RegExp(test, 'gi');
for(var e=0; e<index.length; e++){
if(index[e].match(re)){
document.getElementById("product"+e).style.display = "block";
}else{
document.getElementById("product"+e).style.display = "none";
}
}
}
}
</script>
The code before I adapted the searchProducts function (THAT WORKED PERFECTLY BEFORE ADAPTION) is...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<input type="text" id="searchbar" onkeyup="searchProducts()"/>
<div id="demo"></div>
<div id="demo2">
<div id="product1" style="background-color:red; height:100px; width:100px; float:left">chocolate<br /><button onClick="grow()" id="button1">Show Info</button></div>
<div id="product2" style="background-color:blue; height:100px; width:100px; float:left">Mint</div>
<div id="product3" style="background-color:green; height:100px; width:100px; float:left">Caramel</div>
</div>
</body>
</html>
<script>
var index = ["Chocolate", "Mint", "Caramel"];
var input = "";
var currentLog = [];
function searchProducts(){
currentLog = [];
input = document.getElementById("searchbar").value;
/*function searchStringInArray(str, strArray){
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)){
var temp = strArray.slice(j, (j + 1));
currentLog.push(temp);
console.log(j);
}
}
document.getElementById("demo").innerHTML = currentLog.join("<br />");
if(currentLog.length < 1){
document.getElementById("demo").innerHTML = "No results were found.";
}
}*/
test = input;
re = new RegExp(test, 'gi');
/*if(!index[0].match(re)){
document.getElementById("product1").style.display = "none";
}
if(!index[1].match(re)){
document.getElementById("product2").style.display = "none";
}
if(!index[2].match(re)){
document.getElementById("product3").style.display = "none";
}*/
for(var e=0; e<index.length; e++){
if(!index[e].match(re)){
document.getElementById("product"+(e+1)).style.display = "none";
}else{
document.getElementById("product"+(e+1)).style.display = "block";
}
}
if(document.getElementById("product1").style.display == "none" && document.getElementById("product2").style.display == "none" && document.getElementById("product3").style.display == "none"){
document.getElementById("demo").innerHTML = "no results";
}else{
document.getElementById("demo").innerHTML = "";
}
/*searchStringInArray(input, index);*/
}
function grow(){
if(document.getElementById('product1').style.height == "200px"){
document.getElementById('product1').style.height = '100px';
document.getElementById('button1').innerHTML = "Show Info";
}else{
document.getElementById('product1').style.height = "200px";
document.getElementById('button1').innerHTML = "Hide Info";
}
}
</script>
The issue is that when you sort your list when a filter was applied earlier, you only move the data, not the visibility of the containers of those data.
Instead you could re-execute the regex matching, every time you display the content according to the current sort order. That way you are sure the right data are visible at all times.
You have a lot of duplication in your code, with several places where you have the same loop, or code that only differs in one aspect. You should always try to "Don't Repeat Yourself" (DRY).
I would suggest to have one function for displaying content only. You could pass it the sort function to apply. Note that this means the HTML also changes where you have specified the event handlers. There are many other such simplifications, which are too many to mention all.
Check this snippet:
var list = [
{name: "Apple", price: 31},
{name: "Banana", price: 22},
{name: "Orange", price: 46},
{name: "Strawberry", price:76}
];
var currentRegex = /./; // any character matches
var currentSort = AtoZ;
// Call the function we have for applying the initial sort order and filter
searchProducts(document.getElementById('searchbar').value);
// Shorter ways to compare:
function AtoZ(a,b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }
function ZtoA(a,b) { return AtoZ(b,a) }
function LowtoHigh(a,b) { return a.price - b.price }
function HightoLow(a,b) { return b.price - a.price }
// One function for all sort orders: pass sort order as function
function sortprods(sorter) {
var showCount = 0;
currentSort = sorter;
list.sort(currentSort);
for (var i = 0; i < list.length; i++) {
var product = document.getElementById("product" + i);
// use textContent, not innerHTML
product.textContent = list[i].name + ", " + list[i].price;
var show = !!list[i].name.match(currentRegex);
product.style.display = show ? "" : "none";
showCount += show;
}
document.getElementById('resultsSpan').textContent =
showCount ? '' : 'no results';
}
function searchProducts(input){
// Argument is value of input
// No need to `switch` on currentSort. Can do this with generic code.
// Deal with empty input by using all-matching `.` regexp.
// `g` not needed.
currentRegex = new RegExp(input.length ? input : '.', 'i');
sortprods(currentSort);
}
<div id="resultsSpan"></div>
<div id="product0" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product1" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product2" style="height:45px; width:60px; background-color:lightblue;"></div>
<div id="product3" style="height:45px; width:60px; background-color:lightblue;"></div>
<button onclick="sortprods(AtoZ)">Sort A-Z</button>
<button onclick="sortprods(ZtoA)">Sort Z-A</button>
<button onclick="sortprods(LowtoHigh)">Price (low to high)</button>
<button onclick="sortprods(HightoLow)">Price (high to low)</button>
<input type="text" id="searchbar" onkeyup="searchProducts(this.value)"/>
About the ternary operator:
You asked in comments about the ternary operator:
product.style.display = list[i].name.match(currentRegex) ? "" : "none";
The above is equivalent to this:
var temp;
if (list[i].name.match(currentRegex)) {
temp = "";
} else {
temp = "none";
}
product.style.display = temp;
... except that no temp variable is created of course.
The other occurrence:
currentRegex = new RegExp(input.length ? input : '.', 'i');
... is equivalent to:
var temp;
if (input.length) { // if length is defined and not 0
temp = input;
} else {
temp = ".";
}
currentRegex = new RegExp(temp, 'i');

How to select quantity of individual cartItems in KnockoutJS

Hello im fairly new to knock out and im trying to have my array cartItems auto select their quantity from a drop down. Here is my code:
VIEW
<div data-bind="foreach: cartItems">
<h3 data-bind="text: fullname"></h3>
<p data-bind="text: sku"></p>
<select data-bind="quantityDropdown: number"></select>
</div>
VIEWMODEL
var number = 50;
ko.bindingHandlers.quantityDropdown = {
update: function (element) {
for (var i = 1; i < number + 1; i++) {
var selectedQty = "";
for (var x = 0; x < self.cartItems().length; x++) {
var itemqty = parseFloat(self.cartItems()[x].qty, 10);
if (i === itemqty) {
selectedQty = " selected='selected'";
}
}
// Add each option element to the select here
$(element).append("<option value='" + i + "' " + selectedQty + " class='quantity'>" + i + "</option>");
}
}
};
Now i put two items in the cart and the drop down appears. But the "selected" number is the same for both items in the cart? I know its because its not item specific. but I'm not sure how to make it item specific in Knockoutjs.
Working example:
http://jsfiddle.net/GSvnh/5085/
view :
<div data-bind="foreach: CartItems">
<h3 data-bind="text: FullName"></h3>
<p data-bind="text: Sku"></p>
<select name="qty" class="form-control" data-bind="foreach: QuantityDropdown ,value:SelectedQuantity">
<option data-bind="value: Value,text:Name"></option>
</select>
</div>
VM:
$(function () {
var MainViewModel = function () {
var self = this;
self.CartItems = ko.observableArray([]);
//For example you get below array of objects as response
var response = [{ fullname: "ABC", sku: "1234567789", qty: 12 },
{ fullname: "AAA", sku: "2323227789", qty: 20 },
{ fullname: "BBB", sku: "2311227789", qty: 33 }
];
//you map your response and for each item you create a new CartItemViewModel
self.CartItems($.map(response, function (item) {
return new CartItemViewModel(item);
}));
}
var CartItemViewModel = function (data) {
var self = this;
var number = 50;
self.FullName = ko.observable(data.fullname);
self.Sku = ko.observable(data.sku);
self.QuantityDropdown = ko.observableArray();
for (var i = 1; i < number + 1; i++) {
self.QuantityDropdown.push({ Value: i, Name: i });
}
self.SelectedQuantity = ko.observable(parseFloat(data.qty, 10));
self.SelectedQuantity.subscribe(function (newValue) {
alert("selected Qty : "+ newValue);
})
}
ko.applyBindings(new MainViewModel());
})

User inputs information into text box which makes allows user to select multiple words and creates different Titles based on the selections

I am gaining user input from four different areas and I want to take those options and convert them to an array which will loop through and display different variations of the words selected. The problem I am having is that the array will not cycle through the variables when passed through it unless they are already pre-defined.
<!DOCTYPE html>
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<h2>Example</h2>
<p>When you type into Core Words you want to put words that cannot change such as: Logitech
</br> For Word Combinations you want to use words such as: Brand New or Power Adaptor
</br> For Swapped Words you might want to use: Gaming instead of Performance or vice versa
</br> For Synonyms you want to use words that mean the same thing such as for = 4 or at = #</p>
<h3>Core Words</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCore"/>
<button id="addCore">Insert</button>
<label for="coreContain">Select as many as you like:</label>
<select id="coreContain" name="coreContain" multiple></select>
<button id="checkCore" onclick="checkCore()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCore").click(function()
{
$("#coreContain").append('<option value="' + $("#newCore").val() + '">' + $("#newCore").val() + '</option>');
});
});
$('#coreContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var coreOptions = new Array();
$('form').submit(
function()
{
$('#coreContain > option:selected').each(
function(i)
{
coreOptions[i] = $(this).val();
});
//window.alert(coreOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs Word Combinations -->
<h3>Word Combinations</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCombo"/>
<button id="addCombo">Insert</button>
<label for="comboContain">Select as many as you like:</label>
<select id="comboContain" name="comboContain" multiple></select>
<button id="checkCombo" onclick="checkWordCombo()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCombo").click(function()
{
$("#comboContain").append('<option value="' + $("#newCombo").val() + '">' + $("#newCombo").val() + '</option>');
});
});
$('#comboContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var comboOptions = new Array();
$('form').submit(
function()
{
$('#comboContain > option:selected').each(
function(i)
{
comboOptions[i] = $(this).val();
});
//window.alert(comboOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can swap -->
<h3>Words that can be Swapped</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSwap"/>
<button id="addSwap">Insert</button>
<label for="swapContain">Select as many as you like:</label>
<select id="swapContain" name="comboSwap" multiple></select>
<button id="checkSwap" onclick="checkSwap()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSwap").click(function()
{
$("#swapContain").append('<option value="' + $("#newSwap").val() + '">' + $("#newSwap").val() + '</option>');
});
});
$('#swapContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var swapOptions = new Array();
$('form').submit(
function()
{
$('#swapContain > option:selected').each(
function(i)
{
swapOptions[i] = $(this).val();
});
//window.alert(swapOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can be use as Synonyms -->
<h3>Words that can be used as Synonyms</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSyn"/>
<button id="addSyn">Insert</button>
<label for="synContain">Select as many as you like:</label>
<select id="synContain" name="comboSyn" multiple></select>
<button id="checkSyn" onclick="checkSyn()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSyn").click(function()
{
$("#synContain").append('<option value="' + $("#newSyn").val() + '">' + $("#newSyn").val() + '</option>');
});
});
$('#synContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var synOptions = new Array();
$('form').submit(
function()
{
$('#synContain > option:selected').each(
function(i)
{
synOptions[i] = $(this).val();
});
//window.alert(synOptions);
return false;
});
</script>
</fieldset>
</form>
<button onclick="generate_title()">Generate Titles</button>
<button onclick="displayList()">Click Me</button>
<script>
function displayList()
{
alert(coreOptions+ " " +comboOptions +" " +swapOptions+ " " +synOptions);
}
</script>
<div id="display"></div>
</body>
</html>
External Javascript
var check = ["Facebook", "MySpace", "Twitter"];
//document.getElementById("coreOptions");
//var checkX = check.splice(" ");
var checkY = document.getElementById("swapOptions");
var input_keywords =
[
[check, check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 24;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(input_keywords);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}

Categories

Resources