Script is getting executed before I press button - javascript

I'm stuck in this code this is a coursera assignment on angularjs. I'm beginner in angular js and new to stackoverflow. This is a code about to find how much a person should it. It counts the number of items and then show the result. Items are seperated by ','.
(function () {
'use strict';
angular.module('LunchCheck', [])
.controller('LunchCheckController', LunchCheckController);
LunchCheckController.$inject = ['$scope'];
function LunchCheckController($scope) {
//$scope.msg="";
//console.log($scope.calculate);
$scope.calculate="";
$scope.check = Checker($scope);
}
function Checker(string) {
var str = string.calculate;
console.log(str);
var str1 = str.split(',');
var temp = str1.length;
console.log(temp);
string.msg=message(string,temp);
}
function message(string,temp) {
if(temp > 3) {
return "Too Much!";
}
else if (temp==0) {
return "Aren`t you hungry??";
}
else {
return "Enjoy";
//console.log('Enjoy');
}
}
})();
<!doctype html>
<html lang="en">
<head>
<title>Lunch Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link rel="stylesheet" href="styles/bootstrap.min.css">-->
<style>
.message { font-size: 1.3em; font-weight: bold; }
</style>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="LunchCheck">
<div class="container" ng-controller="LunchCheckController">
<h1>Lunch Checker</h1>
<div class="form-group">
<input id="lunch-menu" type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control" ng-model="calculate">
</div>
<div class="form-group">
<button class="btn btn-default" ng-click="check();">Check If Too Much</button>
</div>
<div class="form-group message">
<!-- Your message can go here. -->
{{msg}}
</div>
</div>
</body>
</html>
Here javascript function is getting executed before I enter any input. I want it to execute after I enter a input. Please help.
Thanks in advance.

Related

How can I change the display a message depending on which number the user has selected?

I want when somebody input a number lower than 4.2, my app shows message as result, but i can't make it happen.
I already tried with return.
JS code
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styleRx.css"/>
<script src="Rxappjs.js"></script>
<title>HVDN Rx app</title>
</head>
<body>
<div class="container">
<header>
<h1>Valoraciones de Rx</h1>
</header>
<div class="box">
<form action="">
<div class="values">
<label for="peso" id="peso__label">Peso</label>
<input class="text__input" type="number" step="0.1" id="number__select" placeholder="Peso"
min="0" required>
</div>
<button id="calcular" onclick="calculate()">Calcular</button>
</form>
<p id="results"></p>
</div>
</div>
</body>
</html>
You have the variable numberEl set to an html element and therefor it will never be less than or equal too 4.2. Try to get the value of that element instead:
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl.value <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}

Javascript variable not defined, using eventlistener in an external js file

Just started learning javascript and started to using an external js file.
Starting trying to make a password strength checker.
But pass keeps coming up as undefined.
I cant seem to find the problem.
Thanks for your time and help.
The js file
pass.addEventListener('keyup', function(){
stength();
})
function strength() {
var val = document.getElementById("pass").value;
var status = document.getElementById("length").value;
var counter = 0;
if (val != ""){
if(val.length <= 6)
counter=1;
if(val.length >= 7 && val.length <= 10)
counter=2;
if(val.length < 10)
counter=3;
if (counter == 1) {
status.innerHTML="Weak";
status.style.background="#fc2407";
status.style.color="#ffffff";
}
if (counter == 2) {
status.innerHTML="Good";
status.style.background="#fc9e07";
status.style.color="#ffffff";
}
if (counter == 3) {
status.innerHTML="Strong";
status.style.background="#21dd53";
status.style.color="#ffffff";
}
}
}
The html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script src="index.js"></script>
</head>
<body>
<div class="wrap text-center">
<p class="head">Enter Password</p>
<input type="password" id="pass"/>
</div>
<div class="wrap text-center">
<p class="head"> Password Strength</p>
<p ckass="strength" id="length"></p>
</div>
</body>
</html>
do that!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
</head>
<body>
<div class="wrap text-center">
<p class="head">Enter Password</p>
<input type="password" id="pass"/>
</div>
<div class="wrap text-center">
<p class="head"> Password Strength</p>
<p ckass="strength" id="length"></p>
</div>
<script src="index.js"></script>
</body>
</html>
<script ... is just before </body> => HTML is a top down interpreter too
Welcome to SO.
If this is all your code, it seems like you never actually defined what pass is.
Try putting this at the top of your code before you reference pass.
var pass = document.getElementById('pass');
So your code should look something like this.
var pass = document.getElementById('pass');
pass.addEventListener('keyup', function(){
stength();
})
Or if you are not going to reference that variable again you can just do it this way.
document.getElementById('pass').addEventListener('keyup', function(){
stength();
})

Angularjs ng-model in input does not update value in controller

Can anyone explain to me why when I print console.log($scope.inputvalue) the variable is not updated with the values that I enter in the input?
Maybe I just misunderstood the meaning of ng-model, in this case, how do I pass a value from the view to controller?
(function () {
'use strict';
angular.module('LunchCheck', [])
.controller('checkiftoomuch', ['$scope', checkiftoomuch]);
function checkiftoomuch($scope){
$scope.inputvalue = "";
console.log($scope.inputvalue);
}
})();
<!doctype html>
<html lang="en" ng-app="LunchCheck">
<head>
<title>Lunch Checker</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="styles/bootstrap.min.css">
<style>
.message { font-size: 1.3em; font-weight: bold; }
</style>
</head>
<body>
<div class="container" ng-controller="checkiftoomuch">
<h1>Lunch Checker</h1>
<div class="form-group">
<input id="lunch-menu"
type="text"
placeholder="list comma separated dishes you usually have for lunch"
class="form-control"
ng-model="inputvalue">
</div>
<div class="form-group">
<button class="btn btn-default">Check If Too Much</button>
</div>
<div class="form-group message">
Total number of disches: {{ inputvalue }}
</div>
</div>
</body>
</html>
You're setting $scope.inputvalue = ""; before the console.log. But after you change the value, you need to console.log it again.
Try using:
function checkiftoomuch($scope){
$scope.inputvalue = "";
console.log($scope.inputvalue);
$scope.$watch('inputvalue', function(newValue, oldValue){
console.log(newValue);
})
}
Or add a function on your button click like:
<div class="form-group">
<button class="btn btn-default" ng-click="showValue()>Check If Too Much</button>
</div>
And in JS:
function checkiftoomuch($scope){
$scope.inputvalue = "";
console.log($scope.inputvalue);
$scope.showValue = function(){
console.log($scope.inputvalue);
}
}
AngularJS has 2-way data binding which means, the values in the view and controller are in sync always, they do not have to be passed back and forth.

text input in html to check for keywords using javascript and return a score

I have the following html page that seeks to check for keywords in text input and return a score depending on how many keywords are entered. For instance, if two keywords are returned, the score would be 2, and if the answer contains no keywords, then a score of 0 would be returned.
In the example below two accepted keywords have been used (e.g. good and eternal) and therefore the user would receive a score of 2.
I've made an attempt (a beginner to JS) but would appreciate some help.
UPDATE: The javascript i have used nearly works (to search for multiple keywords) but doesnt display the showscore variable correctly each time.
This is what I have so far:
<script>
document.getElementById('longanswer').addEventListener('input', function(e){
let keyword = e.target.value;
document.getElementById('greeting').innerHTML = "Just write this";
});
function displayScore() {
var showscore = 0;
var answer = document.getElementById('longanswer').value;
var keyword1="eternal";
var keyword2="good";
var keyword3="true";
if (answer.indexOf(keyword1)!=-1){
showscore=showscore+1
document.getElementById("displayscore").innerHTML = showscore;
} else if (answer.indexOf(keyword1)!=-1 & answer.indexOf(keyword2)!=-1){
showscore=showscore+2
} else if (answer.indexOf(keyword1)!=-1 & answer.indexOf(keyword2)!=-1 & answer.indexOf(keyword3)!=-1){
showscore=showscore+3
} else {
showscore=0
}
document.getElementById("displayscore").innerHTML = showscore;
}
</script>
The interface is below:
Whole code that can be easily re-created below:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Long Answer Question & Answers</title>
</head>
<body>
<form>
<h1> Q and A </h1>
<div class="form-group">
<label for="longanswer">What is the meaning of life?:</label><br>
<textarea rows="4" cols="100" id="longanswer">
</textarea>
<br>
<button onclick="displayScore()" type="button" class="btn btn-success">Submit</button>
</div>
</form>
<div class="card border-primary mb-3" style="max-width: 18rem;">
<div class="card-header">Score</div>
<div class="card-body text-primary">
<h5 class="card-title">Generating a score for your answer</h5>
<p class="card-text" id="displayscore">Once you've clicked submit we will display your score for this answer here.</p>
</div>
</div>
<script>
document.getElementById('longanswer').addEventListener('input', function(e){
let keyword = e.target.value;
document.getElementById('greeting').innerHTML = "Just write this";
});
function displayScore() {
var showscore;
var answer = document.getElementById('longanswer').value;
var keyword1="eternal";
var keyword2="good";
if (answer.indexOf(keyword1)!=-1)
{
showscore="found"
}
document.getElementById("displayscore").innerHTML = showscore;
}
</script>
To have it more dynamic, I'd use a new RegExp in which you can check the text; the length of match' result will be the score
let keywords = new RegExp("(" + ["foo", "bar", "baz"].join('|') + ")", 'gi');
document.getElementById('btn').addEventListener('click', e => {
document.getElementById('score').innerHTML =
document.getElementById('foo').value.match(keywords).length;
});
<textarea id="foo"></textarea>
<button id="btn">
Check
</button>
<div id="score">
</div>

Pushing both keys and value into an json array structure dynamically

I have angularjs front end code as follows:
function addController($scope, $http) {
$scope.tableNames = [];
$scope.addNewColumn = function(item) {
$scope.tableNames.push({})
}
}
<html ng-app>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="addController">
<div class="col-sm-10">
<fieldset ng-repeat="item in tableNames track by $index">
<span> TextBox1:<input type="text" ng-model="item.item1" />
TextBox2:<input type="text" ng-model="item.item2" /></span>
</fieldset>
<button class="btn btn-default" ng-click="addNewColumn()">Add Colname</button>
</div>
<pre>{{tableNames|json}}</pre>
</body>
</html>
So when I enter text in the textbox1 and textbox2 it shows array of below format:
[{
"item1":"textbox1value",
"item2":"textbox2value"
}]
and also when i click addColname button and generate another textbox, values are pushed in different property as follows,it generates:
[{
"item1":"textbox1value",
"item2":"textbox2value"
},
{
"item1":"textbox1value",
"item2":"textbox2value"
}
]
but what actually i need is of structure,
[{
"textbox1value":"textbox2value",
"textbox1value":"textbox2value",
.....
}]
note(:"textboxvalue" are values entered inside textboxes.
somebody help me to get desired output. thanks in advance
This is a working code. I hope this helps :)
<html ng-app>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script>
function addController($scope, $http) {
$scope.tableNames = [];
$scope.getData={};
var i=-1;
$scope.addNewColumn = function (item) {
$scope.tableNames.push({})
i++;
}
$scope.addData = function(item){
if(i >= 0){
$scope.newData=[];
$scope.getData[$scope.tableNames[i].item1]=$scope.tableNames[i].item2;
$scope.newData.push($scope.getData);
}
}
}
</script>
</head>
<body ng-controller="addController">
<div class="col-sm-10">
<fieldset ng-repeat="item in tableNames track by $index">
<span> TextBox1:<input type="text" ng-model="item.item1" ng-keyup="addData()"/>
TextBox2:<input type="text" ng-model="item.item2" ng-keyup="addData()"/></span>
</fieldset>
<button class="btn btn-default" ng-click="addNewColumn()">Add Colname</button>
</div>
<pre>{{newData|json}}</pre>
</body>
</html>

Categories

Resources