Angular beginner here.
I'm trying to create a shopping cart for college.
I need to add the name and price in a text input and after clicking a button the item is supposed to be added to a list.
The thing is that whenever I press the button nothing happens, and I'm lost since the console doesn't tell me anything about what could be wrong. So, here's my code:
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div">
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
And this is my js code:
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
function addProduct() {
$scope.productos.push({nombre:$scope.nameProduct, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});
You have pushed the values to wrong object .
and also you need to change lot .and your button click should be need write to
$scope.addProduct= function () {
//code
}
So please copy and past my code to instead of your code
HTML
<!DOCTYPE html>
<html ng-app = "myApp">
<head>
<title>Shopping Cart</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<script src = "app.js"></script>
</head>
<body ng-controller = "myShoppingCart">
<h1>Add to cart</h1>
<form >
<p>Product: <input type = "text" ng-model = "nameProduct"></p>
<p>Price: <input type = "number" min = "0" step = "any" ng-model = "priceProduct"></p>
<input type = "submit" value = "Add" ng-click = "addProduct()">
</form>
</div>
<div>
<ul>
<li ng-repeat = "product in products">
<span>{{product.name}}</span>
<span>{{product.price}}</span>
<span><input type = "number" min = "0" placeholder = "0" value = "0" ng-model = "amount"></span>
<span>{{product.price*amount}}</span>
</li>
</ul>
</div>
</body>
</html>
and JS Code
var myApp = angular.module("myApp", []);
myApp.controller('myShoppingCart', function($scope) {
$scope.products = [];
$scope.addProduct= function () {
$scope.products.push({name:$scope.name, price:$scope.priceProduct});
$scope.nameProduct = "";
$scope.priceProduct = "";
}
});
<input type = "submit" value = "Add" ng-click = "addProduct()">
Needs to be
<input type = "button" value = "Add" ng-click = "addProduct()">
Submit will submit the form to the server, not exactly what you're looking for I guess.
Also, bad typo here:
<div">
And here (products, not productos):
$scope.productos
Related
Why does the activityInput.value always equal an empty string. This seems very simple, I feel stupis asking something so simple but I cant get it to work. Please help me!
function addActivityListEntry(){
let activityListContainer = document.getElementById('activityList');
let newActivity = document.querySelector("#activityListInput").value
console.log(newActivity)
};
let activitySubmitButton = document.getElementById('activitySubmit');
activitySubmitButton.addEventListener('click', e => {
e.preventDefault();
addActivityListEntry()
})
<div id = "activityListContainer">
<input type ="text" class = "input" value = '' id = "activityListInput" name = "activityListInput" >
<label for = 'activityListInput'></label>
<button class = "button" id = "activitySubmit">
submit activity
</button>
<div id = 'activityList' ></div>
</div>
I can't seem to find where there should be an
activityInput.value
all you have is an
activityListInput.value
This html file should work and shows the logs for "activityListInput"
<!DOCTYPE html>
<head></head>
<body>
<div id = "activityListContainer">
<input type ="text" class = "input" value = '' id = "activityListInput" name = "activityListInput" >
<label for = 'activityListInput'></label>
<button class = "button" id = "activitySubmit">
submit activity
</button>
<div id = 'activityList' ></div>
</div>
</html>
<script>
function addActivityListEntry(){
let activityListContainer = document.getElementById('activityList');
let newActivity = document.querySelector("#activityListInput").value
console.log(newActivity)
};
let activitySubmitButton = document.getElementById('activitySubmit');
activitySubmitButton.addEventListener('click', e => {
e.preventDefault();
addActivityListEntry()
})
</script>
</body>
I was working on some code where I create a website to practice French. I created a method to check my answers but it did not work for a second question. My HTML and JavaScript are below:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src = "Contest.js"></script>
<title>Verb Practice</title>
</head>
<body>
<input type = "button" onclick = "location.href = 'file:///C:/Users/aryan/Desktop/HTML,%20JavaScript,%20&%20CSS/Contest.html#vocab';" value = "Back To Main" />
<center>
<h2>Verb Practice</h2>
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type = "text" name = "Q1" value = "" id = "ansGiven"><br>
<input type = "submit" value = "Answer" id = "Q1" onclick = "getAns('acheter')">
<p id = "ansRes"></p>
</fieldset>
<fieldset>
<p>What does the verb <i>attendre</i> mean?</p>
<input type = "text" name = "Q2" value = "" id = "ansGiven"><br>
<input type = "submit" value = "Answer" id = "Q2" onclick = "getAns('to wait')">
<p id = "ansRes"></p>
</fieldset>
</center>
</body>
</html>
JavaScript:
function getAns(ans) {
var ansGiven = document.getElementById("ansGiven").value;
console.log(ans);
console.log(ansGiven);
if (ansGiven === ans) {
document.getElementById("ansRes").innerHTML = "Correct!";
} else {
document.getElementById("ansRes").innerHTML = "Try Again.";
}
ansGiven = "";
}
Theoretically, the method getAns() should say whether the input for the given question is correct or wrong. Instead, the first question works fine, but the second question displays its input as nothing. Why would this be happening and what was wrong with the code?
From w3schools:
An ID should be unique within a page. However, if more than one
element with the specified ID exists, the getElementById() method
returns the first element in the source code.
To fix that you have to distinguish between your multiple ansGiven and ansRes too (eg. ansGiven1, ansGiven2, ...). This will lead to more complicated code and you will probably have to think about it for a while. You can also use the click event target to find out which element has been clicked.
This happens because you have non-unique IDs for some of the DOM elements and the document.getElementById() function returns the first element with the given ID.
ansGiven and ansRes are used two times each. Instead, use unique IDs like ansGiven-1, ansGiven-2, etc. and ansRes-1, ansRes-2 etc.
You can change the function signature to accept the number of the question as argument:
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type="text" name="Q1" value="" id="ansGiven-1"><br>
<input type="submit" value="Answer" id="Q1" onclick="getAns('acheter', 1)">
<p id="ansRes-1"></p>
</fieldset>
function getAns(ans, answerNumber) {
var ansGiven = document.getElementById("ansGiven-" + answerNumber).value;
if (ansGiven === ans) {
document.getElementById("ansRes-" + answerNumber).innerHTML = "Correct!";
} else {
document.getElementById("ansRes-" + answerNumber).innerHTML = "Try Again.";
}
ansGiven = "";
}
"id" of dom elements must be unique. Your inputs have the same id "ansGiven" and result paragraphs "ansRes". First of all, you have to make them unique. Absolutely not the best method, but since you said you're practicing, give the below code a shot:
<!DOCTYPE html>
<html>
<head>
<script src = "Contest.js"></script>
<title>Verb Practice</title>
</head>
<body>
<input type = "button" onclick = "location.href = 'file:///C:/Users/aryan/Desktop/HTML,%20JavaScript,%20&%20CSS/Contest.html#vocab';" value = "Back To Main" />
<center>
<h2>Verb Practice</h2>
<fieldset>
<p>What is the infinitive for the verb underlined?</p>
<p>J'<ins>achète</ins> une pizza.</p>
<input type = "text" name = "Q1" value = "" id = "ansGiven1"><br>
<input type = "submit" value = "Answer" id = "Q1" onclick = "getAns('acheter', 1)">
<p id = "ansRes1"></p>
</fieldset>
<fieldset>
<p>What does the verb <i>attendre</i> mean?</p>
<input type = "text" name = "Q2" value = "" id = "ansGiven2"><br>
<input type = "submit" value = "Answer" id = "Q2" onclick = "getAns('to wait', 2)">
<p id = "ansRes2"></p>
</fieldset>
</center>
</body>
</html>
javascript
function getAns(ans, questionIndex) {
var ansGiven = document.getElementById("ansGiven" + questionIndex).value;
console.log(ans );
console.log(ansGiven);
if (ansGiven === ans) {
document.getElementById("ansRes" + questionIndex).innerHTML = "Correct!";
} else {
document.getElementById("ansRes" + questionIndex).innerHTML = "Try Again.";
}
ansGiven = "";
}
I have 10 input fields each of them looks like:
<input type='text' ng-model='value1' ng-keyup='checkValue($event)'>
now inside my angular controller, the checkValue function is
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
event.target.value = "";
}
}
here the value is getting empty if the if condition is true but the problem is this value is not removing from ng-model. So I tried to access the ng-model name of the target element like this:
var modelName = angular.element(event.target)[0]attributes[2].nodeValue;
So now in modelName i have the ng-model name of the target element and I tried to reset it :
$scope.modelName = "";
So finally my code looks like:
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
event.target.value = "";
var modelName = angular.element(event.target)[0]attributes[2].nodeValue;
$scope.modelName = "";
}
}
I know it is treating $scope.modelName as a new independent scope variable but how can I change the value of ng-model?
EDIT
What I really want to achieve is: I have 10 fields with different ng-model name now when I am writing the angular function, I don't want to use the ng-model directly inside the function. Example:
$scope.checkValue = function(event){
if(event.target.value > someOtherDynamicValue){
// I have to reset the value here
$scope.value1 = ""; //I don't want to do this, because $scope.value1 is for one text field and I have 10 filed if i use this i need to write it 10 times
}
}
So $scope.value1 I want to generate dynamically using event.target.
Thanks.
Based on values you enter on third textbox values of one and two changes
// Code goes here
var app = angular.module('TestApp', []).controller('HomeController', HomeController);
HomeController.$inject = ['$scope'];
function HomeController($scope) {
var home = this;
home.checkValue = function($event) {
if ($event.target.value < 100) {
home.val1 = 0;
}else{
home.val2 = 10;
}
}
}
<!DOCTYPE html>
<html ng-app="TestApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="HomeController as home">
<div>
{{ home.val1 }} | {{ home.val2 }} | {{ home.val3}}
</div>
<input type="number" ng-model="home.val1" ng-keyup='home.checkValue($event)'>
<input type="number" ng-model="home.val2" ng-keyup='home.checkValue($event)'>
<input type="number" ng-model="home.val3" ng-keyup='home.checkValue($event)'>
</div>
</body>
</html>
Trying to auto-populate first input field value into second input field value, However if the second input field as existing values then i would like to append / concatenate the first input field value to second.
logic:
if ( second ){
second = first + second;
}else{
second = first;
}
html:
<input type='text' ng-model='owner' required class="form-control">
<input type='text' ng-model='member' required class="form-control">
code:
app.controller("Controller", ['$scope', function($scope){
$scope.$watch(function () {
return $scope.owner;
},
function (newValue, oldValue) {
if ( $scope.member ){
$scope.member = $scope.owner + ',' + $scope.member;
}else{
$scope.member = newValue;
}
}, true);
}]);
plunker
Update (problem):
When i type Jake in Owner Field, it loops through the letters and print's as Jake,Jak,Ja,Jin member field. If i have pre-existing value Adam in member field, upon entering Tom in owner filed it will create Tom,To,T,Adam in member field. Please check the plunker for demo.
Mad-D consider changing your approach as it is prone to a circular dependency based on the way ng-model works.
You already have access to both values and you can display it in other ways. Plus your controller looks cleaner and acts as a true view model (vm):
Plunker
app.controller("Controller", function(){
var myCtrl = this;
myCtrl.owner = "";
myCtrl.member = "";
});
I have created a plnkr
. And also given below. Check whether it's correct one for you.
var app = angular.module('form-example1', []);
app.controller("Controller", ['$scope', function($scope){
$scope.permaMember = $scope.member?$scope.member:'';
$scope.editSecond = function(member){
$scope.permaMember = member?member:'';
}
$scope.editFirst = function(owner){
if(owner){
$scope.member = $scope.permaMember + owner
}
else{
$scope.member = $scope.permaMember
}
}
}]);
<!doctype html>
<html ng-app="form-example1">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="Controller">
<form name="testform">
<div class='form-group'>
<label>Owner</label>
<input type='text' ng-model='owner' required class="form-control" ng-change="editFirst(owner)">
</div>
<div class='form-group'>
<label>Member</label>
<input type='text' ng-model='member' required class="form-control" ng-change="editSecond(member)">
</div>
<button ng-disabled="testform.$invalid" ng-click ="submit()">SAVE</button>
</form>
</div>
</body>
</html>
Why not just have a 3rd read only text box or label that displays $scope.owner, $scope.member?
Ok, so here's my script...I can't get it to output the length of the string though! Please help, I'm a complete noob when it comes to Javascript, this is for a college class. Thanks!
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
/*
Purpose of script: report length of string given by user
*/
"use strict";
function stringLength()
{
var str=(document.StringLength.string);
var n=str.length;
document.StringLength.answerBox.value=length;
}
//Get string from user
//Output to user
</script>
</HEAD>
<BODY>
<form name = StringLength>
Enter Your String <input type = "text" name = "string">
<br>
Length <input type = "text" name = "answerBox">
<input type = "button" onclick = "stringLength()" value = "Run">
</BODY>
</HTML>
You need to check the length of the value of the string input box
function stringLength(){
var str=document.StringLength.string.value;
var len=str.length;
document.StringLength.answerBox.value=len;
}
See this JSFiddle for a demo.
You may try like this:
var x = document.getElementById('yourinput');
var y = document.getElementById('characters');
x.onkeyup = function() {
y.innerHTML = x.value.length;
}
JSFIDDLE
function stringLength()
{
var str=(document.StringLength.string);
var n=str.length;
document.StringLength.answerBox.value = n ;
}
Can you try this one, you have not ended form tag properly
<HTML>
<HEAD>
<TITLE></TITLE>
<script type="text/javascript">
/*
Purpose of script: report length of string given by user
*/
function stringLength()
{
document.StringLength.answerBox.value=document.StringLength.string.value.length;
}
//Get string from user
//Output to user
</script>
</HEAD>
<BODY>
<form name ="StringLength" >
Enter Your String <input type = "text" name = "string">
<br> Length <input type = "text" name = "answerBox">
<input type = "button" onclick = "stringLength()" value = "Run">
</form>/*encloded form tag here*/
</BODY>
</HTML>