Grab form fields and calculate based on inputs - javascript

I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>

You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>

Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?

Related

How to know what type of variable user enter in JavaScript?

I tried to make a function that receive data from user and combine such data either by concatenation in case of string or by getting the sum as a result if the entered data was integer.
My main problem is that I don't know what what condition in if statement I use to JavaScript act according to data entered by user.
That's my last invented code to solve such problem
function GetFullName() {
var first = document.getElementById('FirstName').value;
var last = document.getElementById('LastName').value;
if (first == "string" || last == "string") {
document.getElementById('FullName').value = first + " " + last;
} else {
var first = parseInt(document.getElementById('FirstName').value);
var last = parseInt(document.getElementById('LastName').value);
document.getElementById('FullName').value = first + last;
}
document.getElementById('FirstName').focus();
}
<form>
First Name <input type="text" id="FirstName" />
Last Name <input type="text" id="LastName" />
<input type="button" value="submit" onclick="GetFullName()" />
<input type="reset" value="reset" />
<br />
Full Name <input type="text" id="FullName" />
</form>
when you get an element's value it will always be a string,
you can check of a variables type by typeof first
for your specific problem if you want to check if the user inputted integers then you will have to use isNaN
if(isNaN("123")) {
} else {
//this executes
}
All in all the new code would be:
if (isNaN(first) || isNaN(last)) {
document.getElementById('FullName').value = first + " " + last;
} else {
document.getElementById('FullName').value = parseInt(first) + parseInt(last);
}

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Compare input text with person name belongs to only one input number id

Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}

validate form for dynamically created inputs count

I am dynamically creating the inputs in the form
I want user to enter at least 'n' elements.
<html lang="en-US">
<head>
<meta name="referrer" content="origin">
<script>
var counter = 0;
var limit = 50;
function addInput(divName, arrName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
var af = "autofocus"
newdiv.innerHTML = "<input id='my-div-"+counter+"' type='text' name='" + arrName + "[]' required autofocus=" + af + ">";
document.getElementById(divName).appendChild(newdiv);
document.getElementById('my-div-'+counter).focus();
counter++;
}
}
function validateForm(){
var frm = document.forms['simples'];
a = parseInt(frm.elements['myInputs_1[]'].length)
var sum = parseInt(frm.elements['myInputs_1[]'].length)
if(parseInt(sum) < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
</script>
</head>
<body>
<form name="simples" action="part.php" align="center" onsubmit="return validateForm()" method="POST">
<div id = "dynamicInputHolder_1">
<b>Emotion </b><input type="text" value="" name="emotion" id="emotion" class="generatedEmotion" readonly>
<input type="hidden" value="" name="uniqueID" id="uniqueID">
<div id="dynamicInput_1">
<textarea rows="5" cols="50" readonly class="floating-box">
John arrived at Sally's house to pick her up. John and Sally were going to a fancy restaurant that evening for a dinner. John was little nervous because he was going to ask Sally to marry him.</textarea>
</div>
<input type="button" value="Add connecting sentences" onClick="addInput('dynamicInput_1', 'myInputs_1');">
</div>
<br>
<input type="submit" value="show me what is next">
</form>
</body>
</html>
The method validateForm() works only if number text boxes are greater than equal to 2, for 0 and 1 it does not work.
Please not that this is minimal example, in real website, I have many such divs collecting input in multiple arrays, so I am summing them over something like:
var sum = parseInt(frm.elements['myInputs_1[]'].length) + parseInt(frm.elements['myInputs_2[]'].length) + parseInt(frm.elements['myInputs_3[]'].length)
but it may happen that few of the arrays are empty.
How do I check that collectively there are atleast n inputs?
frm.elements['myInputs_1[]'] has a different behavior for each of the cases.
for no elements entered, it will be undefined
for 1 element, it only contains that element, so it does not have a length
for two elements onwards it is an object of type RadioNodeList, which is inherited from NodeList and has a length attribute.
so the validate form method changes to:
function validateForm(){
var frm = document.forms['simples'];
ele = frm.elements['myInputs_1[]'];
if(typeof ele === 'undefined'){
alert('no element at all..');
return false;
}
else if(ele.value == ""){
if (ele.length < 4){
alert("You must write at least 4 sentences ");
return false;
}
}
else{
alert('contains one element');
return false;
}
return true;
}
and it works!

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Categories

Resources