Javascript how to allow array to take more than one digit? - html

I've been trying lately to build up a mean calculator using html and javascript. i want to take all the inputs from the one text box add them to an array and get the average result. what i did in the following code takes only one digit because of str[i-1] is there any other alternative way of doing it? Thanks!
Output photo
function calculate()
{
var str= document.getElementById("meanvalue").value;
for(var i=0; i<str.length; i++)
{
if(str[i] == ".")
{
sum+=parseInt(str[i-1]);
count++;
}
}
sum/=count;
document.getElementById("meanresult").value=sum;
}

Here is a small example:
document.getElementById('input').onkeyup = function() {
this.value = this.value.replace(/[^0-9\.]/gi, '');// restrict non digit
var sum = 0;
var array = this.value.split(/\./);
array.forEach(function(str) {
sum += (parseInt(str, 10) || 0); //avoid NaN
});
document.getElementById('output').value = (sum / array.length || 0);// avoid NaN
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />
i just want to know how the values are updated while im typing my
inputs automatically
Here, I am using onkeyup event to handle user input.
document.getElementById('input').onkeyup = function() {
document.getElementById('output').value = this.value;//get input, set output
}
<input type="text" id="input" />
<input type="text" id="output" readonly='' />

You can use the split function on the input. I give you a quick example here :
var string = "1.3.45.7";
var array = string.split(".");
// array = [1, 3, 45, 7]
document.write(array);

First split your str and than use for loop.
var str= document.getElementById("meanvalue").value.split('.');
Also remove your if condition inside the loop.
for(var i=0; i<str.length; i++)
{
//if(str[i] == ".")
// {
sum+=parseInt(str[i-1]);`
count++;
// }
}
sum/=count;
document.getElementById("meanresult").value=sum;
hope this helps you.

Related

Angular-Calling function result in HTML

I have a function in my ts file:
makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
And what I want is to return result of this function in my html. I can call a funtion in html like:
<input [readonly]="true" formControlName="caseId" matInput placeholder="Radni nalog br:" value="{{ makeid(15) }}">
But every time I click anywhere, it changes the value, and I'm getting an error:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Every time the component reloads it will change because the function will run again.
To keep the value of the first call use a variable to store the value on ngOnInit()
Examle:
x: string;
ngOnInit(){
this.x = makeid(15)
}
makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
And in the HTML:
<input [readonly]="true" formControlName="caseId" matInput placeholder="Radni nalog br:" [value]="x">
You should use [( ngModel )] or put a variable in your component.ts file and change that variable with your function and html will change automatically:
something like this
<input id="Last Name" name="Last Name" type="text" [(ngModel)]="user.lastName" />
this stackblitz will help you https://stackblitz.com/edit/angular-6-value-changes-v2?file=src%2Fapp%2Fapp.component.html

HTML table filters not filtering multiple filters

Filters work correctly as separate filters only i.e. if a user filters in "packages", it will filter as required or if a user filters "Nights" it will filter as required.
If a user wants to filter by two or more filters,rather than return the correct results, it will return the results for the last filtered only
i.e. If a user filters by Package:Silver and Nights:3, it should return four results, not 12.
The requirement is to return the exact results based on all filters chosen by the user.
The 's are from line 65 - 67 and the is from line 2243 - 2292.
It would be a bonus if the "number of people" input was a drop down form with values 1, 2, 3, 4 , but that's not a requirement at this point.
Code too large to paste, see link Table 1
You might wanna combine 3 functions into 1 because they look almost identical.
function filter() {
var filter_package = document.getElementById("myInput").value.toUpperCase().trim();
var filter_num_nights = document.getElementById("myInput1").value.toUpperCase().trim();
var filter_num_people = document.getElementById("myInput2").value.toUpperCase().trim();
var rows = document.querySelectorAll("tr");
// First few rows are headers
for (var i = 2; i < rows.length; i++) {
var items = rows[i].querySelectorAll("td");
if (items.length === 0) continue;
var pkg = items[0];
var night = items[1];
var people = items[2];
var package_text = pkg.innerHTML.toUpperCase().trim();
var night_text = night.innerHTML.toUpperCase().trim();
var people_text = people.innerHTML.toUpperCase().trim();
if (package_text.includes(filter_package) &&
night_text.includes(filter_num_nights) &&
people_text.includes(filter_num_people)) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
and modify the keyup events for the input boxes like below:
<input type="text" id="myInput" onkeyup="filter()" placeholder="Search for Packages.." title="Type in a Package name">
<input type="text" id="myInput1" onkeyup="filter()" placeholder="Search for Number of Nights.." title="Type in Number of Nights">
<input type="text" id="myInput2" onkeyup="filter()" placeholder="Search for Number of People.." title="Type in Number of People">
Please note
If your browser does not support string.includes naively then you can copy and paste the following polyfill into your javascript code. (ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes):
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}

Make basic search in array with if and else

I am trying to make a basic search function. if input.value does exist in array alert message, if not, push it to array ans show in HTML. I think I have already most of work done, but there is somewhere a mistake. Thank you in advance for your help guys .)
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value = myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
In javascript, there are 2 ways to do a comparison.
Strict Equality Operator === strict equality operator.
If you are not sure about the exact datatype for the values being compared, then you can use the == for comparison.
The line document.getElementById("inputForMyDict").value = myDict[i] needs comparison operator and not the assignment operator (=). So you need to replace the = with either == or ===.
so your javascript code should look like
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value == myDict[i]) {
// If you know exact data type, then use the below line instead and comment the above line if (document.getElementById("inputForMyDict").value === myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
Update1: Based on the clarification, provided by comments, you don't need to have a for loop to check for existence of element in array. Javascript provides a convenient way by indexOf method on an array. indexOf method check for the existence of an element in an array and returns the index of the element in the Array. However, if the element is not found then it returns -1.
Full code below which should work.
<!DOCTYPE html>
<html>
<body>
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
//for (var i = 0; i < myDict.length; i++) {
var valueInTextbox = document.getElementById("inputForMyDict").value;
if(myDict.indexOf(valueInTextbox) > -1){
alert("your input is already in your list");
} else {
myDict.push(valueInTextbox);
document.getElementById("demo").innerHTML = myDict;
}
}
//}
</script>
</body>
</html>

How Can I Clear The Selected Field In Input Using Angularjs?

I am using MEAN stack in my application with AngularJS as my front-end. How Can I clear selected filed in input element,My Plunker
Look at my plunker for reference.
I have used Start date and End date inputs , which is used to filter the Due_date. If we select Start Date like:- 16-09-2016 the data's has filtering in the table.
In that date input has one X close button to clear the field, but which is not working, if we click that x clear button the table is showing like empty data's.
What we excatly looking for , if we click that x clear button it's should to be clear selected fileds and need to display all datas in table ....like we have given the exaple plunker is here :- http://plnkr.co/edit/QuJvCXFpKbwVd0OlkHZ2?p=preview for this plunker x clear button is working perfectly, I don't where I made a mistake,
Please help us.
My controller for daterange filter:-
.filter("myfilter", function() {
return function(items, from, to) {
var df = from;
var dt =to;
var result = [];
console.log(to);
for (var i=0; i<items.length; i++){
var date = moment(items[i].invoice_date);
date.add(items[i].terms,'d');
var tf = date;
if (date.isAfter(moment(from)) && date.isBefore(moment(to))) {
result.push(items[i]);
}
}
//console.log(items);
return result;
};
});
My html :-
<input type="date" class="form-control" name="from" ng-model="from">
<input type="date" class="form-control" name="to" ng-model="to">
Filter for daterange:-
<tr ng-repeat="data in record | myfilter:from:to">
<td> {{addDays(data.invoice_date,data.terms) | date:'yyyy-MM-dd'}}</td>
</tr>
I have created my plunker to reference :- My Plunker
Add date validation in your filter
app.filter("myfilter", function() {
return function(items, from, to) {
if(from.length!=0 && to.length!=0)
{
var df = from;
var dt =to;
var result = [];
console.log(to);
for (var i=0; i<items.length; i++){
var date = moment(items[i].invoice_date);
date.add(items[i].terms,'d');
var tf = date;
if (date.isAfter(moment(from)) && date.isBefore(moment(to))) {
result.push(items[i]);
}
}
//console.log(items);
return result;
}else
{
return items;
}
};
});
Change the filter condition to:
if (date.isAfter(moment(from)) || from == null && date.isBefore(moment(to)) || to == null)
This will remove the date constraint if from or to is not set.
Plunkr
Edit: Please add brackets like this:
if ((date.isAfter(moment(from)) || from == null) &&
(date.isBefore(moment(to)) || to == null)) {
//...
}
Updated Plunkr

getelementbyid issue with radio button

I'm trying to make an alert with the value of the selected radio button, but I allways get the first of them, regardless the one I choose...(Acompanhado);
html:
<form/>
<input type="radio" class="simple_form" name="grupo_1" value="Acompanhado" id="saida"/>
<span class="texto">Acompanhado</span>
<input type="radio" class="simple_form" name="grupo_1" value="Individual" id="saida"/>
<span class="texto">Individual</span>
</form>
js:
function save() {
var saida_js = document.getElementById('saida').value;
alert("Tipo de saida: " + saida_js);
}
Any idea ?
#Quentin: I have alot of alerts, cause Im trying to get all data from a form. I used your code, and I get no alert at all.
function save() {
var morada_js = document.getElementById('morada').value;
var data_js = document.getElementById('data').value;
var hora_js = document.getElementById('hora').value;
var radio_saida = document.getElementsByName('name_saida');
var notas_js = document.getElementById('notas').value;
var condicoes_atm_js = document.getElementById('condicoes_atm').value;
alert("Morada: " + morada_js);
alert("Data: " + data_js);
alert("Hora: " + hora_js);
function get_checked_radio(radio_saida) {
for (var i = 0; i < radio_saida.length; i++) {
var current = radio_saida[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radio_saida).value);
alert("Notas: " + notas_js);
}
An id must be unique in a document.
To find the value of a selected radio button in a group, get the group by its nameā€¦
var radios = document.getElementsByName('radio_name'); // or
var radios = document.forms.formId.elements.radio_name;
Then loop over them until you find the one with the true checked property.
function get_checked_radio(radios) {
for (var i = 0; i < radios.length; i++) {
var current = radios[i];
if (current.checked) {
return current;
}
}
}
alert(get_checked_radio(radios).value);
Makes sense because you've got two input tags with the same id saida