Limiting Text Input Based On Another Text Input - javascript

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">

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

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);
}

Limit number of characters in collection of number input fields

I have used the reference from from this question and I want to achieve exactly what the question asked however for multiple input text fields. I would like to restrict the user to not type further and have used getElementsByClassName instead of getElementById.
HTML
<td>
<input id="quantity_scroll" cart_id="<?php echo $cart_row['id']; ?>" min="1" type ="number" max="99" value="<?php echo $cart_row['quantity'] ;?>" oninput = "checkLength()" class="form-control form-quantity" style=" width: 60px;text-align: left;" >
</td>
Javascript
function checkLength(){
var elements = document.getElementsByClassName("form-quantity");
var y;
var ele = elements.length/2;
for(y=0; y < ele; y++){
var length = elements[y].value.length;
if(length <= 2){
return true;
}else{
var value = elements[y].value;
value = value.substring(0, value.length-1);
document.getElementsByClassName("form-quantity")[y].value = value;
}
}
}
However the user is restricted only in the first input box and not in the others. I tried different ways however cannot understand why it isn't happening.
Check the below code. It will restrict users to not enter more than 3 digit numbers. You just need to ensure that all your input fields have the same class form-field:
$(".form-field").on('input', function() {
var enteredVal = $(this).val();
if (enteredVal.length > 3) {
$(this).val(enteredVal.substring(0, enteredVal.length - 1));
console.log('More than 3 characters not allowed.');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-field' />

Grab form fields and calculate based on inputs

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?

Want to output a visual price

ok, I've spent the past 5 hours trying to codge together a small javascript code for a website.
Basically the widths are set values of 2 or 4 (which the user will use a simple drop-down option).
Length can be anything from 1 to 60.
The price will be a fixed price, so can just be hidden out of the way.
Now this is where I start to go South with the situation, I'm having problems spitting the result out into a div area on the page, this is what I have so far;
<script type="text/javascript">
function only_numbers(value){
var check_this = value;
var expression = /^\d*\.*\d*$/;
if(expression.test(check_this)){ return true; }
else{ return false; }
}
function calculate(){
var lengthVal = document.mult.lengthVal.value;
var heightVal = document.mult.heightVal.value;
var priceVal = document.mult.priceVal.value
var showValue = 0;
if(only_numbers(lengthVal) && only_numbers(heightVal) && only_numbers(priceVal)){
var showValue = ((lengthVal * heightVal) * 1.25) * priceVal;
// showValue = Math.round(showValue * 100) / 100;
document.getElementById('showValue').innerHTML = "showValue";
}else{
alert("Please enter only numerical values.");
}
}
</script>
</head>
<body>
<form name="mult">
Length: <input type="text" name="lengthVal" /> <br />
Height: <input type="text" name="heightVal" /> <br />
Price: <input type="text" name="priceVal" /> <br />
<input type="button" value="Calculate" onClick="calculate()" />
</form>
<div id="showValue"></div>
I know I've not sorted the price out to be hidden and is just an open variable atm, please guys, any help would be great.
document.getElementById('showValue').innerHTML = "showValue";
You probably want to write your variable value in there, not the string "showValue". So you should be using:
document.getElementById('showValue').innerHTML = showValue;

Categories

Resources