I am willing to implement an add to cart button in my Angular2 app, currently I can do it in JavaScript/Jquery; however, I don't know how to achieve that is Angular2.
Here is a JSfiddle of the working code:
$(document).ready(function() {
$(".up").on('click',function(){
var $incdec = $(this).prev();
if ($incdec.val() < $(this).data("max")) {
$incdec.val(parseInt($incdec.val())+1);
}
});
$(".down").on('click',function(){
var $incdec = $(this).next();
if ($incdec.val() > $(this).data("min")) {
$incdec.val(parseInt($incdec.val())-1);
}
});
});
http://jsfiddle.net/mail2asik/M8JTP/
I want to do the same, but in Angular2.
Any ideas?
An alternative answer would be to declare the text input as a variable and update it "directly"
HTML "Component template"
<tr>
<td>
<input type="button" (click)="dec(elem)" value="Down"/>
<input type="text" #elem value="0"/>
<input type="button" (click)="inc(elem)" value="Up"/>
</td>
</tr>
JS
inc(elem)
{
var nItem = parseInt(elem.value);
if(nItem < 5)
{
nItem +=1;
elem.value = nItem;
}
}
dec(elem)
{
var nItem = parseInt(elem.value);
if(nItem > 0)
{
nItem -=1;
elem.value = nItem;
}
}
Here is a working Plunker ^^
You can use simple javascript to achieve that functionality.
export class HelloWorld {
public amount: number = 1;
addToCart() {
this.amount = 1;
}
addItem() {
if (this.amount == 5) {
this.amount = 5;
}
else {
this.amount = this.amount + 1;
};
}
removeItem() {
if (this.amount == 0) {
this.amount = 0;
} else {
this.amount = this.amount - 1;
};
}
}
html:
<button (click)="addToCart()">ADD item</button>
<br>
<br>
<button (click)="removeItem()" class="btnSign">Down</button>
<input type="text" class="incdec" value="{{amount}}"/>
<button (click)="addItem()" class="btnSign">Up</button>
Here is the example in the plunker
Related
I am currently trying to learn to become a web developer and have a task where I need to use luhn algorithm to check credit cards are valid. If they are valid the box goes green, if they are not the box goes red. I’ve found the below javascript on GitHub that looks to do what I need, but I am unsure on how to add the code to make the boxes change colour. I believe I need an if/ else statement but I’m not sure how to implement it. I was thinking something like this as the code for the color change:
document.getElementById(‘cardInput’).style.backgroundColor = “green”;
Here is my html:
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" onkeyup="letterscheck(this)" type='text' name='name' placeholder="Enter Your Name"/></li>
<li>Email:<input id="emailInput" onkeyup="emailcheck(this)" type='text' name='email'placeholder="Enter Your Email"/></li>
<li>Card:<input id="cardInput" onkeyup="cardnumber(this)" type='text' name='card' placeholder="Enter a Proxy Credit Card Number."/></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</div>
Here is the JS i found on GitHub:
function cardnumber(value) {
if (/[^0-9-\s]+/.test(value))
return false;
let nCheck = 0, bEven = false;
value = value.replace(/\D/g, “”);
for (var n = value.length - 1; n >= 0; n–) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven && (nDigit *= 2) > 9) nDigit -= 9;
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
My JS for the other 2 fields
function letterscheck(inputtxt)
{
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if(inputtxt.value.match(namechecker))
{
document.getElementById('nameInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('nameInput').style.backgroundColor = "red";;
return false;
}
}
function emailcheck(inputtxt)
{
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(inputtxt.value.match(emailchecker))
{
document.getElementById('emailInput').style.backgroundColor = "green";
return true;
}
else
{
document.getElementById('emailInput').style.backgroundColor = "red";
return false;
}
}
Hopefully, this is a really easy one for you all! Any help would be great.
Thanks!
The algorithm contains several errors so I've searched and found on Stackoverflow
You can change the background-color conditionally. I've changed the background-color inside the letterscheck for name field. You can return true or false and do it in the addEventListener like in email field.
const nameInput = document.querySelector("#nameInput")
const emailInput = document.querySelector("#emailInput")
const cardNumberInput = document.querySelector("#cardInput")
function valid_credit_card(value) {
if (/[^0-9-\s]+/.test(value)) return false;
var nCheck = 0,
nDigit = 0,
bEven = false;
value = value.replace(/\D/g, "");
for (var n = value.length - 1; n >= 0; n--) {
var cDigit = value.charAt(n),
nDigit = parseInt(cDigit, 10);
if (bEven) {
if ((nDigit *= 2) > 9) nDigit -= 9;
}
nCheck += nDigit;
bEven = !bEven;
}
return (nCheck % 10) == 0;
}
function letterscheck(inputtxt) {
var namechecker = /^[a-zA-Z]+(?:[\s.]+[a-zA-Z]+)*$/;
if (inputtxt.match(namechecker)) {
nameInput.style.backgroundColor = "green";
} else {
nameInput.style.backgroundColor = "red";;
}
}
function emailcheck(inputtxt) {
var emailchecker = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return inputtxt.match(emailchecker);
}
nameInput.addEventListener("keyup", e => {
letterscheck(e.target.value);
})
emailInput.addEventListener("keyup", e => {
const isEmailValid = emailcheck(e.target.value)
if (isEmailValid) {
e.target.style.backgroundColor = "green";
} else {
e.target.style.backgroundColor = "red";
}
})
cardNumberInput.addEventListener("keyup", e => {
const isCardValid = valid_credit_card(e.target.value);
if (isCardValid) {
cardNumberInput.style.backgroundColor = "green";
} else {
cardNumberInput.style.backgroundColor = "red";
}
})
li {
list-style-type: none;
}
input {
margin: .25rem 1rem;
}
<form name="form1" action="#">
<ul>
<li>Name:<input id="nameInput" type='text' name='name' placeholder="Enter Your Name" /></li>
<li>Email:<input id="emailInput" type='text' name='email' placeholder="Enter Your Email" /></li>
<li>Card:<input id="cardInput" type='text' name='card' placeholder="Enter a Proxy Credit Card Number." /></li>
<li class="submit"><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
I have to generate a add to cart link for a page from value inputed by our customer. For example, the customer wants to order 3 products from our site www.example.com, so the code generates a link to add these 3 product to cart on page www.example2.com/?add-to-cart=25&quantity=3″.
Any ideas? I would be very grateful.
Here is the qet quantity code which works like a charm.
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
Here is a code sample which I wrote for you which does the job:
JSBIN Snippet Link: https://jsbin.com/guborazuqu
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if (el.value == 1) return false;
el.value = Number(el.value) - 1;
}
function generateAddToCartLink() {
var productID = document.getElementById('productID').value;
var quantity = document.getElementById('gumb2').value;
var generatedLink = `${location.protocol}//${location.hostname}/?add-to-cart=${productID}&quantity=${quantity}`;
window.location.href = generatedLink;
}
<button class="plus" onclick="buttonClickUP();">+</button>
<input id="productID" type="text" value="25">
<input id="gumb2" type="text" value="1">
<button class="plus" onclick="buttonClickDOWN();">-</button>
<button id="order" onclick="generateAddToCartLink()">ORDER NOW</button>
i'm trying to write a program that keeps adding to the current total price displayed as the user keeps inputting/adding more items in the text box area. The code i wrote currently resets the price every time a user inputs/adds an item into the text box. Please how can i solve this problem. I need items and price added to the text box to be added to the current amkunt displayed and not start from the beginning.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
forEachFormItem(form, items, updateItemQuantity);
total = forEachFormItem(form, items, getItemTotal);
updateTotal(priceField, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
goods.push(inp.value);
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
theForm.onchange = calculateTotal;
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" value="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem()";>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>
The problem is that you are not storing the entered goods anywhere, you are just storing the names.
I recommend that instead of just storing the name, you store an object containing added goods, along with the total amount.
function getPrice(itemField) {
return itemField.value || 0;
}
function updateItemfield(itemField) {
var item = getPrice(itemField);
if (getPrice(itemField)) {
itemField.value = item;
} else {
itemField.value = itemField.defaultValue;
}
}
function displayItems(disp, goods) {
hide(disp);
if (goods != 0) {
show(disp);
disp.innerHTML = goods;
}
}
function getQuantity(quantityField) {
return parseInt(quantityField.value, 10) || 0;
}
function updateItemQuantity(itemField, quantityField) {
var quantity = getQuantity(quantityField);
if (quantity < 1) {
quantity = 1;
}
if (getPrice(itemField)) {
quantityField.value = quantity;
} else {
quantityField.value = quantityField.defaultValue;
}
}
function getItemTotal(itemField, quantityField) {
return getPrice(itemField) * getQuantity(quantityField);
}
function hide(el) {
el.className = 'hidden';
}
function show(el) {
el.className = '';
}
function updateTotal(el, amount) {
hide(el);
if (amount > 0) {
show(el);
el.innerHTML = "Your Order Total is $" + amount;
}
}
function forEachFormItem(form, items, func) {
var i,
item,
itemField,
quantityField,
result = 0;
for (i = 0; i < items.length; i += 1) {
item = items[i];
itemField = form.elements[item],
quantityField = form.elements[item + 'quantity'],
result += func(itemField, quantityField);
}
return result;
}
// function addRecord() {
// var inp = document.getElementById('inputtext');
// quotes.push(inp.value);
// inp.value = "";
// }
function calculateTotal() {
var form = this,
items = ['wine'],
total = 0,
priceField = form.priceField;
// Get total goods and update total
total = goods.reduce((a, c) => a + c.total, 0);
updateTotal(totalPrice, total);
}
var goods = [];
function addItems() {
var inp = document.getElementById('inputtext');
// Calculate total price
const itemField = theForm.elements['wine'];
const quantityField = theForm.elements['winequantity'];
const total = getItemTotal(itemField, quantityField);
// Store name and total price
goods.push({name: inp.value, total});
inp.value = "";
}
function newItem() {
document.getElementById("itemDisplay").innerHTML = goods.map(x => x.name).join(", ");
}
var theForm = document.getElementById('order');
theForm.priceField = document.getElementById('totalPrice');
.hidden {
display: none;
}
<form id="order" method="post" action="mailto:seyicole#gmail.com">
<fieldset id="selections">
<legend><strong>Your Selections</strong></legend>
<img class="wine" src="wine.png" alt="Select Your Items!!">
<p>
<label>Wine:</label>
<input type="text" name="" id="inputtext" placeholder="item">
<input type="text" name="wine" value="0" size="8">
<input type="text" name="winequantity" placeholder="Quantity" size="8">
<button type="button" id="add" onclick="addItems(), newItem(), calculateTotal()" ;>Add </button>
</p>
</fieldset>
<h1>Items</h1>
<div id="itemDisplay">
</div>
<br>
<input type="submit" value="Place order">
</form>
<div id="totalPrice"></div>
Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle
All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>