integer output returning NaN in javascript - html

I'm trying to write this extremely simple javascript app where the user can input two numbers and the sum of these two is automatically outputted to screen. I'm very new to javascript so I'm not sure where I went wrong. The following code will print NaN for a second after I press the button. Any idea as to how I handle this input better?
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}
</script>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
</body>
</html>

var x = parseInt(first_num);
var y = parseInt(second_num);
Instead of first_num and second_num, you need to retrieve the value from the input boxes, like this
var x = parseInt(document.getElementById("first_num").value);
var y = parseInt(document.getElementById("second_num").value);

You have to use a selector to get the value of the two input elements:
var x = parseInt(document.getElementById('first_num').value);
var y = parseInt(document.getElementById('second_num').value);
...
And you have to close your form tag in your HTML use and use a <input type="button"> instead of <button> so your form doesn't post unnecessarily.
<form>
<input id="first_num" name="first_num" > first num <br />
<input id="second_num" name="second_num" > second num <br />
<input type="button" onclick="myFunction()" value="calculate">
</form>

Here is working demo.
The reason of NaN is you trying to parseInt with not initialized variable. beside this input tag is not closed.
function myFunction() {
document.getElementById("demo").innerHTML = parseInt(document.getElementById('first_num').value) + parseInt(document.getElementById('second_num').value);
}
and html:
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num" />first num
<br>
<input id="second_num" name="second_num" />second num
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>

Here is a working sample:
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<p>Enter two numbers to be added together.</p>
<input id="first_num" name="first_num">first num<br />
<input id="second_num" name="second_num">second num<br />
<button onclick="myFunction()">calculate</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("first_num").value;
var y = document.getElementById("second_num").value;
var z = ((x && x != "") ? parseInt(x) : 0) + ((y && y != "") ? parseInt(y) : 0);
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>

Do the following:
<p>Enter two numbers to be added together.</p>
<form>
<input id="first_num" name="first_num" > first num<br>
<input id="second_num" name="second_num" > second num
<button onclick="myFunction(parseInt(document.getElementById("first_num").value),parseInt(document. getElementById("second_num").value))">calculate</button>
<p id="demo"></p>
function myFunction(first_num,second_num)
{
var x = parseInt(first_num);
var y = parseInt(second_num);
var z = x + y;
var a = z.toString();
document.getElementById("demo").innerHTML = a;
}

Related

Html: JavaScript: input: razor:minRange and maxRange

I have an input element with a minRange and maxRange set and am trying to get a custom validity message. I also have a Input TagHelper to write a custom message that I am trying to override on client-side.
I have tried this so far and it doesn't seem to be working.
<input asp-for="Amount" minRange="50.00" maxRange="100.00" oninput="check(this)" />
<script type="text/javascript">
function check(input) {
if (input.validity.rangeUnderflow || input.validity.rangeOverflow) {
input.setCustomValidity("Please enter an amount between $50.00 and $100.00.");
}
}
</script>
Rendered html:
<input oninput="check(this)" type="text" data-val="true" data-val-number="The field Amount must be a number." data-val-required="The Amount field is required." id="Model_Amount" name="Model.Amount" value="97.95" data-val-range-min="50.00" data-val-range-max="100.00" data-val-range="Please enter an Amount between 50.00 and 100.00" class="form-control valid" placeholder="Amount" aria-required="true" aria-invalid="false" aria-describedby="Model_Amount-error">
It still inputs "Please enter Amount between 50.00 and 100.00"
input taghelper:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (MinRange != null && MaxRange != null)
{
TagHelperAttribute minAttr = new TagHelperAttribute("data-val-range-min", MinRange);
output.Attributes.Add(minAttr);
TagHelperAttribute maxAttr = new TagHelperAttribute("data-val-range-max", MaxRange);
output.Attributes.Add(maxAttr);
TagHelperAttribute rangeAttr = new TagHelperAttribute("data-val-range", string.Format("Please enter a {0} between {1} and {2}", DisplayName, MinRange, MaxRange));
output.Attributes.Add(rangeAttr);
}
}
Any help is appreciated.
Thanks
NH
Changed your code with some comments added. Hope this helps
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- Change minRange/maxRange to just min/max -->
<input asp-for="Amount" min="50.00" max="100.00" oninput="check(this)" />
<span id="display"></span>
</body>
<script type="text/javascript">
function check(input) {
//Get current input field value
var num = parseInt(document.querySelector('input').value);
//Check if num is < or > than input.min/max
if(num >= input.min && num <= input.max){
document.getElementById('display').innerText = '';
}else{
document.getElementById('display').innerText = 'Number must be between 50 and 100';
}
}
</script>
</html>

How can I create a loop for Chat Bubbles?

I want to develop a loop for chat bubbles. Every time I write a message, a bubble should be created and be on the right. When the chat partner replies, the message should be on the left in the bubble. How can I develop this loop?
My current code is this one:
<div class="Webview">
<div class="message_container" id="myForm"></div>
<form class="send_container">
<input id="textField" type="text">
<p>
<input type="button" id="theButton" value="Nachricht absenden!" onclick="document.getElementById('myForm').innerHTML=document.getElementById('textField').value" />
</p>
<h3>
<div id="div"></div>
</h3>
</form>
</div>
OK, it is not add messages to the DOM in loops, but just add message on Enter on the trigger that sending the message.
If you want to add value from Text Field such as text input,
You probably want to do two steps:
Getting the value from the input
Inject the value into a balloon template (html) and then into the DOM.
Then, you should add Javascript scope into your html or just include js file that contain the following function:
function addMessage() {
// Add XSS validation
const $messages = document.getElementById('myForm');
const $textElement = document.getElementById('textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.innerHTML += newMessage;
return false;
}
<input type="button" id="theButton" value="Nachricht absenden!" onclick="addMessage()" />
In jQuery it will be like this (in the js scope of course):
$("#theButton").off('click').on('click', function() {
e.preventDefault();
const $messages = $('#myForm');
const $textElement = $('#textField');
const newMessage = '<div class="message-balloon">' + $textElement.value + '</div>';
$messages.html += newMessage;
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="theButton" value="Nachricht absenden!" />
Hope it helps :)
Good luck

Angularjs Parse value from input box to controller

I have an input box of quantity that the user can change it's value by clicking the - and + buttons. The problem is that if I entre the value directly in the input box I can parse this value to my controller. If I change the value by clicking the buttons + or - I can not parse the value to controller, it keeps always the old value. Can anyone help me?
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) && qty > 0 ) result.value--;return false;"
class="reduced items-count"
type="button"
>
<i class="fa fa-minus"> </i>
</button>
<input
type="text"
class="input-text qty"
title="Qty"
maxlength="12"
id="qty"
name="qty"
ng-init="qty='1'"
ng-model="qty"
>
<button
onclick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty )) result.value++;return false;"
class="increase items-count"
type="button"
>
<i class="fa fa-plus"> </i>
</button>
And my controller,
$scope.$watch('qty', function (val) {
if (val) {
alert("qty2:" + val);
}
});
I don't quite understand what you are trying to implement, but you can use ng-click on your buttons to execute some function in your controller.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.qty = 0;
$scope.change = function(value) {
$scope.qty += value;
$scope.changed(); // execute after update
}
$scope.changed = function() {
/*
Do what you want after the update,
but $scope.qty is dynamic anyway
*/
//alert("qty: " + $scope.qty);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="change(-1)" type="button">-</button>
<input type="number" ng-model="qty" ng-change="changed()" />
<button ng-click="change(1)" type="button">+</button>
<br/>{{qty}}
</div>
</div>
</body>
</html>
This is totally the wrong approach... never use dom methods in angular app like that.
Use ng-click to modify the ng-model property. Also always follow the golden rule of making sure you have a dot in ng-model
angular
.module('app', [])
.controller('Ctrl', function($scope) {
$scope.data = {
qty: 0
}
$scope.updateQty = function(amt) {
$scope.data.qty += amt
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
<button ng-click="updateQty(-1)">-1</button>
<input ng-model="data.qty">
<button ng-click="updateQty(1)">+1</button>
</div>

Basic API with HTML: Creating Objects

I have a pretty simple calculator that I am trying to setup.
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit">
</form>
The next step is I need to pull the top 20 (quantity) cryptocurrencies, then divide the 500 (dollars) between them relative to market cap.
Here's the API website: https://coinmarketcap.com/api/
Clicking on https://api.coinmarketcap.com/v1/ticker/?limit=10 shows me the top 10 currencies.
How can I ADD up all the market caps of each individual currency on the page. Then create ratios from them?
Math part is pretty straightforward, what I don't get is how to actually pull the data from the API link and get it in a workable format.
Lookup Jquery and Ajax:
You can implement this like this:
function getCurrencies()
{
$.ajax(
{url:"https://api.coinmarketcap.com/v1/ticker/?limit=20",
success:function(data) {
//console.log(data);
var totalcap=0.0;
var u=$("<ul>");
for(var i=0;i<data.length;i++) {
var currency=data[i];
var cap=parseFloat(currency["market_cap_usd"]);
var li=$("<li />").html(currency["name"] + " " + cap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
u.append(li);
totalcap+=cap;
}
$('#currlist').html('').append(u);
$('#cap').html(totalcap.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
}));
$('#data').val(JSON.stringify(data));
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"}
);
}
textarea {width:600px;height:250px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<p>Crypto Currency Diversifier</p>
<div class="container">
<h1>Crypto Currency Diversifier</h1>
<form action="/action_page.php">
Dollars:<br>
<input type="text" name="dollars" value="500"><br><br>
# of Currencies:<br>
<input type="text" name="quantity" value="20"><br><br>
<input type="submit" value="Submit" onclick="getCurrencies(); return false"
>
Total Market Cap:<div id="cap"></div><br />
Currencies: <div id="currlist"></div><br />
<textarea id="data"></textarea>
</form>

Why are my inputs not resetting?

The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.