Background colors on Luhn Algorithm - JavaScript - javascript

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>

Related

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');

how to continually add to a price total in a shopping list

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>

After submit a form, stay same page, show a word in the page

After clicking "submit", stay on the page.
Input data, like "computer number" and "profit", stay inside those blank square.
A word "Submitted", appear in the center of this page.
The following is my code, Please help, thank you!
<html>
<head>
<title></title>
</head>
<body>
<form name="form"
onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer" required><br>
<p>How much is your profit?
<input id="id1" name = "id1" required>
<button type = "button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<script>
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect"; document.getElementById("Q1").style.color = "red";errosCount++;
} else {
text = "Correct"; document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if(errosCount === 3){
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution(){
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100"; document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
</script>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var q = document.forms["my form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;}
var w = document.forms["my form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;}
}
</script>
</body>
</html>
Firstly, you were having document.forms["my form"] which was invalid since your form name was form so I changed it to document.forms["form"].
And, on submit, I added return false at the bottom of the function to stay on the page. Also, before that, added "Submitted" text in the center of the page as shown below.
Here's working code snippet!
Hope that helps!
var errosCount = 0;
function myFunction() {
var x, text;
x = document.getElementById("id1").value;
if (isNaN(x) || x != 100) {
text = "Incorrect";
document.getElementById("Q1").style.color = "red";
errosCount++;
} else {
text = "Correct";
document.getElementById("Q1").style.color = "green";
}
document.getElementById("Q1").innerHTML = text;
if (errosCount === 3) {
errosCount = 0;
document.getElementById('btn1').style.display = 'block';
document.getElementById("Q1").innerHTML = '';
} else {
document.getElementById('btn1').style.display = 'none';
}
}
function Solution() {
text = "(P - w) * q<sub>o</sub> - I = (53 - 43) * 30 - 200 = 100";
document.getElementById("Q1").style.color = "red";
document.getElementById("Q1").innerHTML = text;
}
function validateForm() {
var q = document.forms["form"]["Computer"].value;
if (q == "") {
alert("Computer Number is Missing!");
return false;
}
var w = document.forms["form"]["id1"].value;
if (w != "100") {
alert("Question 1 is Incorrect!");
return false;
}
document.getElementById("submitted").innerHTML = "Submitted"
return false;
}
#submitted {
text-align: center
}
<form name="form" onsubmit="return validateForm()">
Computer Number:<br>
<input type="text" name="Computer"><br>
<p>How much is your profit?
<input id="id1" name="id1" required>
<button type="button" onclick="myFunction()">My Answer</button>
<button type="button" id="btn1" onclick="Solution()" style="display:none;">Solution</button>
</p>
<p id="Q1"></p>
<input type="submit" value="Submit">
</form>
<br/>
<div id="submitted">
</div>
Hello you should think abut using AJAX as you are sending a form.
This can be the button:
<button type="button"
onclick="validateForm('ajax_info.php', myFunction)"> Clic to Submit
</button>
And this the AJAX function:
function validateForm(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true); //can be POST
xhttp.send();
}
function myFunction(xhttp) {
document.getElementById("submited").innerHTML =
xhttp.responseText;
}

Form validation for appendChild

I created add rows form by using appendChild.
Whenever I click addrow button a row is formed but form validations are not applying for that row. And now I need validation for all rows. Please recommend a method.
I need validations for all other addon rows
var counter = 0;
var limit = 0 / 0;
function addInput(dynamicInput) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>User:" + " <input type='text' name='user' id='user'> " +
"Age:" + " <input type='number' name='Age'> " +
"Qualify:" + " <input type='text' name='qualification' id='qual'> " +
"Specilztn:" + " <input type='text' name='specialization' id='spec'> " +
"Percentage:" + " <input type='number' name='percentage' id='perc'> " +
" <input type='submit' id='subtn2'>";
document.getElementById(dynamicInput).appendChild(newdiv);
counter++;
document.getElementById("removerow").style.display = "block";
}
}
function removeInput() {
var x = document.getElementById("dynamicInput");
if (x.hasChildNodes()) {
x.removeChild(x.childNodes[14]);
}
}
function formvalidation() {
var a = document.getElementById("user");
var b = document.getElementById("age");
var c = document.getElementById("qual");
var d = document.getElementById("spec");
var e = document.getElementById("perc");
if (uservalidation()) {
if (agevalidation()) {
if (qualvalidation()) {
if (specvalidation()) {
if (percvalidation()) {
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
function uservalidation() {
if (a.value == "") {
document.getElementById("uerr").innerHTML = "Enter UserName";
document.getElementById("user").focus();
return false;
}
else {
document.getElementById("uerr").style.visibility = "hidden";
return true;
}
}
function agevalidation() {
if (b.value == "") {
document.getElementById("agerr").innerHTML = "Enter Age";
document.getElementById("age").focus();
return false;
}
else {
document.getElementById("agerr").style.visibility = "hidden";
return true;
}
}
function qualvalidation() {
if (c.value == "") {
document.getElementById("qerr").innerHTML = "Enter Qualification";
document.getElementById("qual").focus();
return false;
}
else {
document.getElementById("qerr").style.visibility = "hidden";
return true;
}
}
function specvalidation() {
if (d.value == "") {
document.getElementById("sperr").innerHTML = "Enter Specialization";
document.getElementById("spec").focus();
return false;
}
else {
document.getElementById("sperr").style.visibility = "hidden";
return true;
}
}
function percvalidation() {
var addrowbtn = document.getElementById("addrow");
if (e.value == "") {
document.getElementById("pererr").innerHTML = "Enter Percentage";
document.getElementById("perc").focus();
return false;
}
else {
document.getElementById("pererr").style.visibility = "hidden";
addrowbtn.style.display = "block";
}
}
}
b{
color:red;
}
#form2{
display:none;
}
#addrow{
display:none;
/* float:right;
margin-top:20px;
margin-right:45px; */
position: absolute;
top: 8px;
right: 75px;
background:green;
color:white;
cursor:pointer;
}
#removerow{
display:none;
background:red;
color:white;
cursor:pointer;
position: absolute;
top: 8px;
right: 5px;
}
<form method="post" id="form1" name="form1" onsubmit="return formvalidation()">
<div id="dynamicInput">
User: <input type="text" name="user" id="user">
Age: <input type="number" name="age" id="age">
Qualify: <input type="text" name="qualification" id="qual">
Specilztn:<input type="text" name="specialization" id="spec">
Percentage:<input type="number" name="percentage" id="perc">
<input type="submit" id="sbtn">
<p>
<b id="uerr"> </b>
<b id="agerr"> </b>
<b id="qerr"> </b>
<b id="sperr"> </b>
<b id="pererr"> </b>
</p>
</div>
<input type="button" value="Add Row" id="addrow" onClick="addInput('dynamicInput');">
<input type="button" value="Del Row" id="removerow" onClick="removeInput();">
</form>
There are many problems here. Here's a few tips:
1) When you are creating your new div, you aren't giving it an id, so your validation will never find it.
var newdiv = document.createElement('div');
newdiv.setAttribute("id", "Div1"); // you can generate the id from your counter
2) All of your validations are static so there aren't any validations on your new div, so now even though we just gave it an id, there's no logic to find it. Your validation doesn't know anything about the new div at all. You can add some validations using your new id:
var div1 = document.getElementById("Div1");
if(div1){
// ... validation logic
}
3) Another thing about your validation - it doesn't need to be that complicated. You have too many inner functions doing too many things. Doing JUST this for each of your validations in your formvalidation function would be a little cleaner, at least:
var user = document.getElementById("user");
if(!user){
document.getElementById("uerr").innerHTML = "Enter UserName";
document.getElementById("user").focus();
return false;
} else {
document.getElementById("uerr").style.visibility = "hidden";
}

How can I translate this JS to Angular2?

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

Categories

Resources