I hate manually typing steps numbers. So I was trying to write a small function to find some text and replace it with generated step numbers.
And I can't use the ol/li tags because I have multiple groups on the page. So I need to add an "a", "b", etc after the number.
My HTML:
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
This is my jquery (but it doesn't replace the ---- to a step number).
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
$(this).find(":contains('----')").each(function(){
$(this).text("("+counter+val+") ");
counter++;
});
});
});
So eventually, I want the webpage to finish like this:
(1a) My first step
(2a) This is another
(3a) And another
(1b) second group
(2b) second group 2
For each of the groupings, get the inner html and split it by newline
If it starts with '----', replace it with an incrementing line number, and append the v value.
Put the html back into the grouping.
$('.grouping').each(function(index, grouping){
var lines = grouping.innerHTML.trim().split("\n");
var lineNumber = 0;
var v = grouping.getAttribute('v');
lines.forEach(function(line, index){
if (line.startsWith('----')) {
lines[index] = '('+ (++lineNumber) + v +') '+ line.slice(4);
}
});
grouping.innerHTML = lines.join('\n');
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
I should not have a line number.
----And another
</span>
<br/>
<span class="grouping" v="b">
I also should not have a line number.
----second group
----second group 2
</span>
You can use split to split the text at '----' and concat with the values (added brs for lisibility so I used html instead of text):
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var arr = $(this).html().split('----');
if(arr.length > 1){
var str = arr[0], i, l = arr.length;
for(i = 1; i < l; i++){
str += '(' + i + val + ') ' + arr[i];
}
$(this).html(str);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step<br>
----This is another<br>
----And another<br>
</span>
<br/>
<span class="grouping" v="b">
----second group<br>
----second group 2<br>
</span>
.find() will not work. You should get text of the element and split() it and then change it using map() and replace() and reset text()
$(function(){
$(".grouping").each(function(){
var val=$(this).attr("v");
var counter=1;
let lines = $(this).text().split('\n');
lines = lines.map(ln => {
if(ln.includes('----')){
ln = ln.replace('----',`(${counter}${val})`)
counter++;
}
return ln;
})
lines = lines.filter(ln => ln !== '');
$(this).text(lines.join('\n'));
});
});
.grouping { white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="grouping" v="a">
----My first step
----This is another
----And another
</span>
<br/>
<span class="grouping" v="b">
----second group
----second group 2
</span>
First, I suggest wraping those groups into some kind of tag. for example, span:
<span class="grouping" v="a">
<span class="grouping-item">My first step</span>
</span>
And so on, it will be easier and faster to target those elements.
Then create one function to search through those new tags
$(function(){
// This will create those numbers
function createNumbers(el) {
const mainGroup = el.attr("v");
const children = el.children(".grouping-item");
let i = 1;
children.each(function(){
const currentText = $(this).text();
$(this).text( '('+i+mainGroup+')' + currentText );
i++;
});
}
$(".grouping").each(function(){
createNumbers($(this));
});
});
Code description:
Clicking the button (id=a1) will add text input brackets (e.g. 3 clicks will give 3 text input). I am trying to get the values from all the text inputs and show it on the page,however, my code only prints out the value from the first text input. How can I get it to print all the values from all the text inputs?
// add textbox function onclick
var a1 = 0;
var x = [];
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' id='a1' value=''/><br />";
a1 += 1;
}
//Adds inout into list var x
function pushData()
{
//get value from input text
var inputText = document.getElementById('a1').value;
//append data to the array
x.push(inputText);
var pval = x;
document.getElementById('pText').innerHTML = pval;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>
I have made a couple of improvements to your code, that you can see in the code snippet below.
The essential changes you need to make would be,
Use a class selector instead of ID selector. When you invoke document.getElementById it returns one element having the provided ID. Instead you want all the textboxes that were dynamically created. So you can add a CSS class to the input at the time of creation (class='magnitude-input') and afterwards use it to get all inputs (document.getElementsByClassName('magnitude-input')).
Once you get a list of inputs, you can iterate over them and collect their values into an array (x in your case). Note that x should be definied within the function pushData, otherwise it will retain values previously added to it.
Also, the variable a1 seems unnecessary after that. So you can remove it.
// add textbox function onclick
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' class='magnitude-input' value=''/><br />";
}
//Adds inout into list var x
function pushData() {
var x = [];
//get value from input text
var inputs = document.getElementsByClassName('magnitude-input');
for(var i = 0; i < inputs.length; i++) {
var inputText = inputs[i].value;
//append data to the array
x.push(inputText);
}
document.getElementById('pText').innerHTML = x;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>
I am having a hard time figuring out how to create a drag and drop feature in my app that will accept a draggable item and decide whether it is the correct answer and if it is correct it will display a message saying success!
My app displays two images both images are portions of a pizza pie and then it will display 8 draggable numbers that you have to choose from and drag them into a droppable box which will check if its correct. So i start with ...
PizzaImageOne[1]="http://s23.postimg.org/6yojml8vb/Pizza_One.png"
PizzaImageOne[2]="http://s13.postimg.org/5d8zxnb2b/pizzatwo.png"
this happens 8 times so each number of the array represents how many slices it holds
then i call var whichImage = Math.round(Math.random()*(p-1)); i store a random # into the variable whichImage which holds the number of pizza slices because each array # correlates with the pizza slices image which i will use to generate random pizzas by doing this
document.write('<img src="'+theImages[whichImage]+'">');
I do that all over again with a new array
PizzaImageTwo[1]="http://s23.postimg.org/6yojml8vb/Pizza_One.png"
PizzaImageTwo[2]="http://s13.postimg.org/5d8zxnb2b/pizzatwo.png"
same exact thing but with new variables so the random call can be different than the first one
var whichImage2 = Math.round(Math.random()*(p-1))
then i have
<script>
$(function() {
$( "#draggable1" ).draggable();
});
</script>
I do that 8 times so #draggable1, #draggable2, draggable3, ... all the way to 8
i then made an array and saved them into each array like this 8 times each draggable function represents numbers from 1 to 8 because we are adding pizza pies like fractions
<script>
var theimagestwo = new Array();
Draggablenumber[1] = $("#draggable1");
DraggableNumber[2] = $("#draggable2");
I do this until i fill up 8 draggable numbers in each array
So the logic is MyAnswer = WhichImage + WhichImage2 Then i have to check if DraggableNumber[MyAnswer] is dropped then i have the right answer...
How would i go about creating this feature??
Following your comment, this will be an easy task, you only need to follow these steps:
Create two random numbers contained in the slices array
Calculate the sum of these values
When you drop the number compare if this number is equal to the sum
of the slices
Here you have an example code:
HTML
<div id="slices">
</div>
<div id="options">
<div data-index="1">1</div>
<div data-index="2">2</div>
<div data-index="3">3</div>
<div data-index="4">4</div>
<div data-index="5">5</div>
<div data-index="6">6</div>
<div data-index="7">7</div>
<div data-index="8">8</div>
</div>
<div id="area">
drop area
</div>
jQuery UI
//---Vars
var slices = $("#slices");
var options = $("#options");
var area = $("#area");
var selected;
var result;
//---Array of images
var pizzas = [
{image: "http://s23.postimg.org/6yojml8vb/Pizza_One.png", value: 1},
{image: "http://s13.postimg.org/5d8zxnb2b/pizzatwo.png", value: 2},
{image: "http://s12.postimg.org/xfsxldqyx/pizzathree.png", value: 3},
{image: "http://s14.postimg.org/d6tdq0865/pizzafour.png", value: 4}
];
var total = pizzas.length;
//---Make boxes dragables
options.find("div").draggable();
//---When the boxes are dropped
area.droppable({
drop: function(event, ui){
if( Number( ui.draggable.attr("data-index") ) == result ){
alert("correct");
}else{
alert("incorrect");
}
}
});
//---Insert random pizza slices
function insertPizzas(){
selected = [];
result = 0;
//---Generate aleatory pieces
var rand
while(selected.length < 2){
//---Random value
rand = Math.floor( Math.random() * total );
//---Sum result
result += pizzas[rand].value;
selected.push( rand );
}
//---Clear the slices
slices.html("");
//---Add the new slices
selected.forEach(function(number){
var img = $("<img/>");
img.attr("src", pizzas[number].image);
slices.append(img);
});
}
insertPizzas();
jsfiddle
I'm working on a program that lets you add items to the shopping cart, change the quantity of a certain item in the cart, and computes the subtotal, taxes, shipping cost, and total dynamically.
Right now I'm running into the problem where all of my totals computed are 0.
Here is where I believe I most likely made an error, I'll provide the whole code at the bottom of the page.
//Used to dynamically change subtotal,tax,shipping, and total when quantity is adjusted
$("#selected-list").on('change', '.quantity', calculateTotalPrice);
function calculateTotalPrice(){
var subtotal = calculateSubtotal();
var tax = calculateTax();
var shipping = calculateShipping();
var total = calculateTotal();
$('#subtotal').html(subtotal.toFixed(2));
$('#tax').html(tax.toFixed(2));
$('#shipping').html(shipping.toFixed(2));
$('#total').html(total.toFixed(2));
}
function calculateSubtotal(){
var subtotal = 0;
var quantity = 1;
for(var i = 0; i < cart.lengh; i++){
quantity = parseInt($(this).val());
var productPrice = parseInt(item_list[cart[i]].price);
subtotal += parseInt(productPrice * quantity);
}
return subtotal;
}
function calculateTax(){
var taxAmount = 0;
var taxes = .06;
var subtotal = calculateSubtotal();
taxAmount = parseInt(subtotal * taxes);
return taxAmount;
}
function calculateShipping(){
var shippingAmount = 0;
var shippingPerc = .02;
var subtotal = calculateSubtotal();
shippingAmount = parseInt(subtotal * shippingPerc);
return shippingAmount;
}
function calculateTotal(){
var totalCost = 0;
var subtotal = calculateSubtotal();
var taxes = calculateTax();
var shippingCost = calculateShipping();
totalCost = parseInt(subtotal + taxes + shippingCost);
return totalCost;
}
I've been messing around with it for a while, and what's interesting is if I put an alert right after my for loop in calculateSubtotal() this way:
alert(subtotal)
alert(item_list[cart[0]].price)
The subtotal will always print to be 0, and the item_list[cart[0]].price will always print out the correct price of the item in the cart. This confuses me because I made the default value of quantity to be 1, and if it's getting the price correctly then it shouldn't even be able to equal 0.
Here is the rest of my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<meta charset="utf-8">
<!-- Set the viewport so this responsive site displays correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>UWW Semester Planner </title>
<!-- Include bootstrap CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<style type="text/css">
.courselist { cursor: pointer;}
.t-head { color: #fff; background-color: #333366; font-size: 20px; line- height: 20px; }
#top-box, #footer { background-color: #330066; color: #fff; text-align: center;}
#content {border: 1px solid #330099;}
</style>
<script>
$(function(){
/* The following function defines a constructor for creating an array of objects with four properties.
The keyword "this" refers to the instance of the object
*/
function Item(type,title,description,price){
this.type = type;
this.title = title;
this.description = description;
this.price = price;
}
//create an array to store items
var item_list = [];
var cart = []; //store index of elements in the shopping cart
//add items
//add baseballgear items
item_list.push(new Item('baseballgear','Louisville Slugger', 'The finest craftsmanship and finest materials ensure stepping to the plate with the Louisville Slugger® M9 Maple M110 Bat will allow you to swing what the pros swing.', 79.99 ));
item_list.push(new Item('baseballgear','Marucci Bat', 'Named for one of the most lethal hitters in the game, the Marucci® CUTCH22 Pro Model Baseball Bat features the same cut and finish swung by MLB® center fielder, Andrew McCutchen. The "Cutch" features a large, powerful, balanced barrel with a sleek cherry red and grey finish to deliver maximum performance at the plate. This adult wooden bat is also handcrafted and bone-rubbed to ensure superior quality and surface hardness.', 139.99));
item_list.push(new Item('baseballgear', 'Rawlings Glove', "Unrivaled quality season after season, the Rawlings® 11.25'' Pro Preferred® Series Glove returns to provide elite craftsmanship and superior performance for elite middle infielders.",349.99));
item_list.push(new Item('baseballgear', 'Wilson Glove', "Enhance your field performance with unrivaled dependability with the Wilson® 11.5 A2000™ Series Glove. Made with Pro Stock® leather for long-lasting performance, this glove's construction is preferred by professionals for its top-notch quality. Dri-Lex® technology in the wrist lining transfers moisture away from the skin to keep you cool and dry. The advanced design has been improved upon by the Wilson&Reg; Advisory Staff.",249.99 ));
item_list.push(new Item('baseballgear', 'Easton Baseball Helmet', 'Give your favorite player maximum protection at the plate with the Easton® Junior Z5 Elite Baseball Helmet. The ABS shell withstands impact and disperses energy away from the head, with a stylish Digi-Camo design. Featuring dual density foam liner for advanced comfort, this helmet boasts BioDri™ padded inner liner to wick moisture away from the skin to keep them cool and dry. Wrapped ear pads provide enhanced coverage around the head.', 54.99));
item_list.push(new Item('baseballgear', 'Rawlings Batting Gloves', 'Get the most out of your batting gloves this season with the Rawlings® Adult Workhorse 950 Batting Gloves. These gloves feature an Oiltac® leather palm pad to provide better grip and softness. Equipped with a Dura-Plus™ pad for added protection in the palm, the Dynamic Fit System™ provides greater comfort, flex, and feel during every play. The adjustable wrist closure is reinforced to provide a more secure fit', 34.99));
//add soccergear items
item_list.push(new Item('soccergear', 'Nike Ordem Soccer Ball', 'Hit the back of the net with the The Nike® Ordem 3 PL Soccer Ball. The Ordem 3 is the official match ball of the English Premier League for the 2015-2016 season. This FIFA® approved ball features Aerowtrac grooves and a micro-textured casing for accurate flight. The carbon latex bladder and fuse-welded construction allow for an exceptional touch while the vivid visual Power Graphics allow you to track the ball so you can react quickly.', 150.00));
item_list.push(new Item('soccergear', 'Wilson Shinguard', 'Maximize your protection for practice or game day with the Wilson® NCAA® Forte ll Soccer Shinguard. This high impact shinguard is constructed of a removable inner shell for adjustable protection to diffuse impact during elite-level play. Its Lycra® sleeve contains power band enhancements for added compression and blood circulation. Focus on your game with the Wilson® NCAA® Forte ll Soccer Shinguard.', 24.99 ));
item_list.push(new Item('soccergear', 'Adidas Goalie Gloves', 'Protect the goal line with intensity when you sport the adidas® Ace Zones Pro Soccer Goalie Gloves. Evo Zone Technology delivers superior catching and control so you can dominate the game from the net. The negative cut ensures a snug feel while seamless touch features deliver breathability through the latex and foam construction. A stretch-strap wraps your hand to complete the gloves with a comfortable fit.', 114.99));
item_list.push(new Item('soccergear', 'Storelli Exoshield Goalie Jersey', 'Block kicks to the net with maximum mobility in the Storelli® Exoshield GK Adult Goalie Gladiator Jersey. This jersey withstands impact between the posts with polyurethane foam protection at the elbows. For increased comfort, the compression material wicks moisture away to keep the skin cool and dry. Dive and defend without distraction in the lightweight Storelli® Exoshield GK Adult Goalie Gladiator Jersey.', 64.99));
item_list.push(new Item('soccergear', 'Storelli BodyShield Slider Shorts', "Enjoy superior protection with the classic fit of the Storelli® sliders. Lightweight foam padding delivers high-performance protection to keep you safe from impact, swelling and cuts, while the unique design lets you freely move while the pads stay in place. Stay safe on the field with the antimicrobial technology and lightweight padding of the Storelli® Men's Slider Shorts.", 59.99));
item_list.push(new Item('soccergear', 'Adidas Estadio Teamp Backpack', 'Transport your gear to and from the field in style with the adidas® Estadio Team Backpack II. Built with soccer in mind, this backpack is constructed with multiple compartments to conveniently organize and store all of your gear. LoadSpring™ technology adds comfort to the shoulder straps so you can carry more equipment. FreshPAK™ shoe compartment keeps gear fresh throughout the season.', 55.00));
//add videogames
item_list.push(new Item('videogames', 'Star Wars Battlefront', 'Visit classic planets from the original Star Wars™ trilogy, detailed with an unprecedented amount of realism and sense of authenticity that will transport you to a galaxy far, far away', 59.99));
item_list.push(new Item('videogames', 'Just Cause 3', "The Mediterranean republic of Medici is suffering under the brutal control of General Di Ravello, a dictator with an insatiable appetite for power. Enter Rico Rodriguez, a man on a mission to destroy the general's ambitions by any means necessary. With more than 400 square miles of complete freedom from sky to seabed, and a huge arsenal of weaponry, gadgets and vehicles, prepare to unleash chaos in the most creative and explosive ways you can imagine.", 59.99));
item_list.push(new Item('videogames', 'Call of Duty Black Ops III', 'Call of Duty: black Ops III is the ultimate 3-games-in-1 experience. The Campaign you must navigate the hot spots of a new Cold War to find your missing brothers. Multiplayer features a new momentum-based chained movement system, allowing players to fluidly move through the environment with finesse. No Treyarch title would be complete without its signature Zombies offering "Shadows of Evil" has its own distinct storyline right out of the box.', 59.99));
item_list.push(new Item('videogames', 'Fallout 4', 'The epic storylines, adrenaline-pumping action and explosive thrills are back. The Fallout franchise returns with Fallout 4. Grab your controller and get ready to dive back into the enveloping storyline of this legendary series.', 59.99));
item_list.push(new Item('videogames', 'Halo 5: Guardians', 'A mysterious and unstoppable force threatens the galaxy, the Master Chief is missing and his loyalty questioned. Experience the most dramatic Halo story to date in a 4-player cooperative epic that spans three worlds. Challenge friends and rivals in new multiplayer modes: Warzone, massive 24-player battles, and Arena, pure 4-vs-4 competitive combat.*', 59.99));
item_list.push(new Item('videogames', "Assassin's Creed Syndicate", "WELCOME TO THE FAMILY — London, 1868. The Industrial Revolution fattens the purses of the privileged while the working class struggles to survive — until two Assassins rise to lead the world's first organized crime family. Conquer the streets of London. Bring the ruling class to their knees. Make history in a visceral adventure unlike any game you've played before.", 59.99));
// display item list
displayAll();
$('#category').on('change', function(){
// read the selected category using 'value' attribute
var category = $(this).val();
if (category == '0')
displayAll(); // display all items
else
displaySelectedItems(category); // display selected items
// Check all the selected items in the cart
checkCartElements();
});
function checkCartElements(){
$('.addme').each(function(){ // do something with each checkbox
// read its index
var index = $(this).data('index');
// check if the item with a selected index is in the cart
var check = inCart(index); // returns true/false
if(check == true){
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
}
function inCart(index){
for (var i=0; i<cart.length; i++){
if (cart[i] == index)
return true;
}
return false;
}
function displaySelectedItems(category){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
*/
for (var i=0; i<item_list.length; i++){
// display only selected items
if (item_list[i].type == category){
itemInfo += createItemData(item_list[i], i);
}
// add each item to the table
$('#item-list').html(itemInfo);
}
}
function displayAll(){
var itemInfo = '';
/* display data:
use a for loop to go through each element in the item_list array
Each element is an object.
*/
for (var i=0; i<item_list.length; i++){
// use each item to create HTML content
itemInfo += createItemData(item_list[i], i);
// add each item to the table
$('#item-list').html(itemInfo);
}
}
function createItemData(item, index){
/* Use the data-attribute to add the index of each element of the array so that each checkbox can be mapped to
the corresponding item. Then we can directly use the array of item objects to prepare a suitable
HTML structure and add to the shopping cart.
*/
var trow = "<tr class='itemlist data-index='" +index+ "' >";
trow += "<td class=item-title'><input type='checkbox' class='addme' data-index='"+ index +"' > "+item.title + "</td>";
trow += "<td class='item-description'>"+item.description + "</td>";
trow += "<td class='price'>"+item.price + "</td></tr>";
return trow;
}
$('#item-list').on('click', '.addme', function(){
/* Whenever a item is selected by clicking on any of the checkboxes, perform the following: */
// 1. Read the item index using data- attribute
var index = $(this).data('index');
// 2. If the checkbox is checked then add the item to the cart. Else, remove it from the cart
if ($(this).prop('checked')){
cart.push(index);
} else {
removeItemFromCart(index);
}
// 3. Update the cart list and total credits
displayCartItems();
// update price
calculateTotalPrice();
});
$('#selected-list').on('click', '.delete-item', function(){
var index = $(this).val();
removeItemFromCart(index);
calculateTotalPrice();
checkCartElements();
});
$("#selected-list").on('change', '.quantity', calculateTotalPrice);
function calculateTotalPrice(){
var subtotal = calculateSubtotal();
var tax = calculateTax();
var shipping = calculateShipping();
var total = calculateTotal();
$('#subtotal').html(subtotal.toFixed(2));
$('#tax').html(tax.toFixed(2));
$('#shipping').html(shipping.toFixed(2));
$('#total').html(total.toFixed(2));
}
function calculateSubtotal(){
var subtotal = 0;
var quantity = 1;
for(var i = 0; i < cart.lengh; i++){
quantity = parseInt($(this).val());
var productPrice = parseInt(item_list[cart[i]].price);
subtotal += parseInt(productPrice * quantity);
}
alert(quantity);
return subtotal;
}
function calculateTax(){
var taxAmount = 0;
var taxes = .06;
var subtotal = calculateSubtotal();
taxAmount = parseInt(subtotal * taxes);
return taxAmount;
}
function calculateShipping(){
var shippingAmount = 0;
var shippingPerc = .02;
var subtotal = calculateSubtotal();
shippingAmount = parseInt(subtotal * shippingPerc);
return shippingAmount;
}
function calculateTotal(){
var totalCost = 0;
var subtotal = calculateSubtotal();
var taxes = calculateTax();
var shippingCost = calculateShipping();
totalCost = parseInt(subtotal + taxes + shippingCost);
return totalCost;
}
function removeItemFromCart(index){
// identify and remove the index from the cart and redisplay cart table
var pos = -1;
for (var i=0; i<cart.length; i++){
if (index == cart[i]){
pos = i;
break;
}
}
if (pos>-1){
cart.splice(pos, 1);
// reset the cart table
displayCartItems();
} else {
alert("Could not find!");
}
}
function displayCartItems(){
// create a table row for each item in cart array
var itemInfo = '';
for (var i=0; i<cart.length; i++){
var index = cart[i];
itemInfo += createTableRow(index);
}
$('#selected-list').html(itemInfo);
}
/*function createTableRow(index){
var trow = '';
trow+= "<tr><td>"+item_list[index].title + "</td>>";
trow += "<td>"+item_list[index].price + "</td>";
trow += "<td><input type='text' id='quantity' value='1' size='5' />";
trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
return trow;
}*/
function createTableRow(index){
var trow = '';
trow+= "<tr><td>"+item_list[index].title + "</td>>";
trow += "<td>"+item_list[index].price + "</td>";
trow += "<td><input type='text' class='quantity' value='1' size='5' />";
trow += "<td><button type='button' class='delete-item' value='"+index+"'>Delete</button></td></tr>";
return trow;
}
$('#show-cart').on('click', function(){
$('#selected-list').show();
});
$('#hide-cart').on('click', function(){
$('#selected-list').hide();
});
});
</script>
</head>
<body>
<div class='container'>
<div class='row' id='top-box' >
<div class='col-sm-12'>
<h2>Sam's Discount Store</h2>
<h3>Variety of Items!</h3>
</div>
</div>
<div class='row' id='content'>
<div class='col-sm-8'>
<h3 class='title'>Discounted Items</h3>
<h4>
<select id='category'>
<option value='0' >All</option>
<option value='baseballgear' >Baseball Items</option>
<option value='soccergear' >Soccer Items</option>
<option value='videogames'>Video Games</option>
</select>
</h4>
<table class='table table-bordered clmlabels' >
<tr class='t-head'><td >Product</td>
<td >Description</td>
<td >Cost</td>
</tr>
<tbody id='item-list'>
</tbody>
</table>
</div>
<div class='col-sm-4'>
<h2>Cart Items</h2>
<p><button class='btn btn-primary' id='show-cart'>Display cart</button>
<button class='btn' id='hide-cart'>Hide cart</button></p>
<table class='table selected-list' id='selected-list'>
</table>
</div>
<table class='cart-table'>
<tr>
<td>Subtotal: </td>
<td><span id='subtotal'>0</td>
</tr>
<tr>
<td>Tax: </td>
<td><span id='tax'>0</td>
</tr>
<tr>
<td>Shipping: </td>
<td><span id='shipping'>0</td>
</tr>
<tr>
<td>Total: </td>
<td><span id='total'>0</td>
</tr>
</table>
</div>
</div>
<div class='row' id='footer'
<div class='col-sm-12'> <p>Sam's Discount Store</p></div>
</div>
</div>
</body>
</html>
you have misspelled the word length in "cart.lengh" (should be cart.length) (line 185).
Then when calling the method "calculateSubtotal" from the method "calculateTotalPrice", the context gets lost and when you tries to use $(this) to get the quantity. One solution would be to get the input value in the method "calculateTotalPrice" and pass it as parameter to the method "calculateSubTotal".
function calculateTotalPrice(){
var quantity = parseInt($(this).val());
var subtotal = calculateSubtotal(quantity);
}
function calculateTotalPrice(quantity){}
I am attempting to create an encryption machine where you type in a 5 digit number, it encrypts that number by changing the numbers then converting them into letters. The directions are as follows:
Add the necessary code to the “Encrypt” button to do the following:
a) Create a for loop to add 10 to the number entered on the first box and multiply the
result by 3, add 20 to this result and then multiply it by 5, add 30 to this result and then multiply it by 7, etc. Follow that pattern 5 times (5 iterations).
b) After the iterations have been completed, there will be a resulting number in
memory, let's say 75432179
c) Now, this number needs to be turned into characters (letters) by matching each digit
to its corresponding letter of the alphabet based on the positions of the letters (0 will
be matched with the 10th letter of the alphabet). For our example: the resulting letters
will be: gedcbagi (g is the 7th letter of the alphabet, e is the 5th letter, d is the 4th
letter, etc.)
d) The last step of the encryption process is to further scramble the letters by using the
ancient Caesar's cipher: each letter replaced by another letter three positions to the
right. Therefore, the final result in our example would be: jhgfedjl (Notice that you
may also do steps c) and d) combined)
I have to display this whole thing in the form of a table with parameters:
Create a table with three columns and three rows
On the first column, just place descriptive information as illustrated in Figure 1 (Previous
page)
Create two text boxes on the second column (set the size of the text boxes to 16)
Create one button on the third column. Label it “Encrypt”
I have the majority of the code done so far, but i cannot seem to get it to work. Here is my code so far:
<style type="text/css">
body {background-color: black; color: lightgreen; font-family: helvetica; text-align: center}
table {margin-left: auto; margin-right: auto}
</style>
<body>
<script type ="text/javascript">
function encrypt(num) {
var sum = 0, str, i, result, index;
var chars = "abcdefghijklmnop";
var charBase = "0".charCodeAt(0);
for (i = 0; i < 5; i++) {
sum += (num * ((2 * i) + 3)) + ((i * 10) + 10);
}
str = sum + "";
result = "";
for (i = 0; i < str.length; i++) {
index = str.charCodeAt(i) - charBase + 3;
result += chars.charAt(index);
}
return result;
}
document.getElementById("go").addEventListener("click", function() {
var num = parseInt(document.getElementById("num").value, 10);
var out = encrypt(num);
document.getElementById("encryptedValue").innerHTML = out;
});
</script>
<h1>ATM</h1>
<br/>
<hr/>
<br/>
<table align="center" border="1">
<tr>
<td><b>Plaintext</b> (Plain information)</td>
<td><input type="text" size="16" onchange=''/></td>
<td><button id="go"> Encrypt </button></td>
</tr>
<tr>
<td><b>Ciphertext</b> (Encrypted information)</td>
<td><input type="text" name="encryptValue" size="16" onchange=''/></td>
<td></td>
</tr>
<tr>
<td>.</td>
<td></td>
<td></td>
</tr>
</table>
</body>
Trying to respond to the one simpler question you put in your comment:
This line in the code you have:
document.getElementById("encryptedValue").innerHTML = out;
puts the result of the encrypt operation into a non-form object on your page (such as a div or a span) that has id="encryptedValue". You can create a div or span in your HTML and give it that id and your code should put the result into that object on the page.
Or, change the <input> you have labeled Ciphertext to be a div.
Or, add the id="encryptedValue" to the Ciphertext <input> tag and change the above line of code to:
document.getElementById("encryptedValue").value = out;