Enable the submit button after adding 2 number and comparing the number - javascript

I'm trying to enable the submit button , there are 3 fields in a form value of 1st field-box is fixed and the addition of 2nd field-box and 3rd field-box is stored in 4th field box. So what i need is it should compare with the 1st number and th3 4th number (addition of 2nd and 3rd) and if the condition satisfied then it should enable the submit button or else button should be disable. I have done some work around and not able to figure it out what i am missing. Please help me regarding the same.
I have added the JSfiddle code on which I am working:
let $form = $('form');
let $first1 = $('#first1');
let $total1 = $('#total1');
let $total2 = $('#total2');
let $answer = $('#answer');
let $submitButton = $(':submit');
$form.on('submit', function(event) {
let val1 = Number($first1.val());
let val2 = Number($answer.val());
if (val1 < val2) { // If condition is NOT met.
event.preventDefault(); // Default submit from happening.
return false; // Stop function.
}
});
$form.on('input', function(event) {
let val1 = Number($first1.val());
let val2 = Number($answer.val());
console.log(val1, val2)
let isDisabled = val1 < val2; // Will return true or false.
$submitButton.prop('disabled', isDisabled);
});
$form.on('input', function(event) {
let val1 = Number($total1.val());
let val2 = Number($total2.val());
console.log(val1, val2)
let number = parseInt($('#total1').val()) + parseInt($('#total2').val());
$('#answer').val(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="order.php">
<label for="first1">Fixed Number</label>
<input type="number" id="first1" value="10" />
<br>
<label for="total1">First Number</label>
<input type="number" id="total1" class="change"/>
<br>
<label for="total2">Second Number</label>
<input type="number" id="total2" class="change"/>
<br>
Answer = <input type="number" id="answer" name="answer" value=""/>
<br>
<input type="submit" value="submit" disabled title="Not Relevant">
</form>

You can simplify your function more by combining the two input event listeners and put them in one. And the submit event listener is not needed either.
val1 and val2 are already numbers cause of the Number() constructor wrapping the $total1.val() function. It does the same thing as parseInt.
Add val1 to val2 and store that result in a new variable called total.
Then check if the total is lower or higher than the firstVal (fixed value) and disable or enable the submit button.
Add a readonly attribute to inputs that you don't want modified by the user.
let $form = $('form');
let $first1 = $('#first1');
let $total1 = $('#total1');
let $total2 = $('#total2');
let $answer = $('#answer');
let $submitButton = $(':submit');
$form.on('input', function(event) { // This function gets called every time you change the value in one of the inputs
let firstVal = Number($first1.val()); // Get fixed number
let val1 = Number($total1.val()); // Get 2nd field number
let val2 = Number($total2.val()); // Get 3rd field number
let total = val1 + val2; // Add 2nd and 3rd field
let isDisabled = total < firstVal; // If total is lower than fixed number, then is true, otherwise is false.
$submitButton.prop('disabled', isDisabled); // Disable based on if isDisabled is true or false
$answer.val(total); // Show the total
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="order.php">
<label for="first1">Fixed Number</label>
<input type="number" id="first1" value="10" readonly/>
<br>
<label for="total1">First Number</label>
<input type="number" id="total1" class="change"/>
<br>
<label for="total2">Second Number</label>
<input type="number" id="total2" class="change"/>
<br>
<label for="answer">Answer</label>
<input type="number" id="answer" name="answer" value="" readonly/>
<br>
<input type="submit" value="submit" disabled title="Not Relevant">
</form>

Related

limit text input to match HH:MM format with max hours and resetting to previous value if entered wrong

I want to limit value/numbers inside a text input to match the HH:MM format, possibly also limit max hrs input (i.e. max 8) while also preventing any other input format in that field. Ideally would be if a number is entered to high, instead of resetting the field/number set it back to the previous number that was already contained or selected via the range slider (not simply clearing it).
Would I have to extract the first, second, fourth & fifth number from that text field and check them individually or any other approach I could use?
The only other alternative I can think of is using two separate text input fields and display a static colon symbol between them, checking each individually (but entry field may look neater where only hrs and mins are changeable) i.e.
document.getElementById('hrs').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 0 || parseInt(this.value) > 8 || isNaN(this.value)) ? "00" : (this.value)
});
document.getElementById('mins').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 0 || parseInt(this.value) > 8 || isNaN(this.value)) ? "00" : (this.value)
});
//still requires a reset to previous value instead of fixed "00"
//I also tried this with just one field but no idea how to target just the first and last double digits separately while ignoring the colon symbol.
Here is my HH:MM range slider with synced text input field to allow for either input (I haven't found yet any better alternative to this).
HTML
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
></script>
<div class="slidecontainer">
<input type="text" id="durationtimestamp" value="00:00" oninput="durationtimestamp(this.value)" required="required">
<input type="range" min="0" max="480" value="0" class="durationslider" id="durationrange" oninput="durationslider(this.value)">
</div>
JS
function durationslider(value) {
var hours = Math.floor(value / 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var minutes = (value % 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
duration = hours+':'+minutes;
document.getElementById("durationtimestamp").value = duration;
}
function durationtimestamp(value) {
var hours = Math.floor(value / 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var minutes = (value % 60).toLocaleString('en-US', {
minimumIntegerDigits: 2,
//useGrouping: false
});
var myduration = moment.duration(value).asMinutes().toString();
var current = document.getElementById("durationrange").value;
document.getElementById("durationrange").value = myduration;
}
Demo: https://jsfiddle.net/markusd1984/u3gfod5x/11/
You can check the input with js like this
const input = document.querySelector("input");
const checkingInput = (event) => {
console.log(event.target.value.length <= 5);
if(!/0[0-8]:[0-5][0-9]$/.test(event.target.value)){
input.value = null;
}
}
<input type="text" onchange="checkingInput(event)"/>
it should work 🤔
You can also use the pattern attribute or a <datalist>.
Although you didn't mention them a <select> or some radio buttons could also be used.
const error = document.getElementById("error");
document.getElementById("frm").addEventListener("change", function(e) {
const valid = this.checkValidity();
error.classList.toggle("hidden", valid);
if (!valid) {
const value = this.getAttribute("value");
this.value = value;
}
});
.hidden {
display: none;
}
.error {
color: red;
}
<span id="error" class="error hidden">Error</span>
<form id="frm">
<label for="time">Time</label>
<input type="text" id="time" pattern="[0]?[0-8]:[0-5][0-9]" placeholder="HH:MM" value="1:00" required>
<br>
<label for="duration">Time</label>
<input list="duration-options" id="duration" pattern="[0]?[0-8]:[0-5][0-9]" placeholder="HH:MM" value="1:00" required>
<datalist id="duration-options">
<option>0:30</option>
<option>1:00</option>
<option>4:00</option>
<option>8:00</option>
</datalist>
<br>
<label for="times">Time</label>
<select id="times">
<option>0:30</option>
<option>1:00</option>
<option>4:00</option>
<option>8:00</option>
</select>
<p>Time</p>
<label><input type="radio" name="time" value="0:30">0:30</label>
<label><input type="radio" name="time" value="1:00">1:00</label>
<label><input type="radio" name="time" value="4:00">4:00</label>
<label><input type="radio" name="time" value="8:00">8:00</label>
</form>

jquery two number inputs automatically recalculating each input if another is changed

I'm good with html, but no so good with javascripting :(
I've searched all over stackoverflow and googled for it, but didn't found exactly what i need, only thing i found which is more or less close to what i need is http://jsfiddle.net/mrobin/QWSQp/64/
But what i need is two inputs:
<input type="text" name="num1" maxlength="15" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" value="">
<input type="text" name="num2" maxlength="15" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" value="" >
Both are set with rule, that only numbers with only one DOT is available:
oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');
Now question, i have a X value which is incerted by php
<?=$eur_price ?>
Point is creating two inputs where one is quantity and second is total price, but each field could be edited and if one is edited, another should be recalculated.
Example:
X=1.5 (set price) ... Num1=10 so Num2 would be calculated to 15
X=1.5 (set price) ... Num2=6 so Num1 would be calculated to 4
And so on...
So you can set how many u need or how much u would like to spend...
Any help how to do it, or how to edit example which i found?
Separate the responsibilities in your logic to reuse your code
Create an event i.e: calculate and bind it to num2.
Dispatch that event from input event of num1.
The first two step must be applied to element num2.
Add id to your inputs for a better performance.
Move your logic to accept numbers and one dot to the event input.
Look at this code snippet
With this approach you can trigger the event calculate from anywhere
const calculate = new Event('calculate');
let n1 = document.getElementById("num1");
let n2 = document.getElementById("num2");
let eurPrice = 1.5;
// -------- num1 logic ---------
n1.addEventListener("input", function(e) {
this.value = this.value.replace(/[^0-9.]/g, '');
this.value = this.value.replace(/(\..*)\./g, '$1');
n2.dispatchEvent(calculate);
});
n1.addEventListener('calculate', function(e) {
this.value = (n2.value / eurPrice).toFixed(2);
});
// -------- num2 logic ---------
n2.addEventListener("input", function(e) {
this.value = this.value.replace(/[^0-9.]/g, '');
this.value = this.value.replace(/(\..*)\./g, '$1');
n1.dispatchEvent(calculate);
});
n2.addEventListener('calculate', function(e) {
this.value = (n1.value * eurPrice).toFixed(2);
});
<input type="text" id="num1" name="num1" maxlength="15" value="">
<input type="text" id='num2' name="num2" maxlength="15" value="">
If using addEventListener, you can do this with one event and just check if num1 or num2 has been changed, if num2 changed, calc num1, if num1 changed calc num2;
Here is a simple example below.
const euro = 1.5;
const num1 = document.querySelector("[name=num1]");
const num2 = document.querySelector("[name=num2]")
document.body.addEventListener("input", function (evt) {
if (evt.target === num1) {
num2.value = (parseFloat(num1.value) * euro).toFixed(3);
} else {
num1.value = (parseFloat(num2.value) / euro).toFixed(3);
}
});
<input type="text" name="num1" maxlength="15">
<input type="text" name="num2" maxlength="15">

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

how to make bind submit working always? it's working from time to time

I'm trying to compare to values (min - max) from two inputs
if min is greater than max should alert a message... that works
The problem is when I correct max value and submit again, it is showing the same alert...
this is my HTML:
<form>
<input type="text" placeholder="min" id="input1" class="numberInput"/>
<input type="text" placeholder="max" id="input2" class="numberInput"/>
<input type="submit"/>
<span class="msg"></span>
</form>
and this is my (relevant?) JS:
var $input1 = $("#input1");
var $input2 = $("#input2");
$(document).ready(function() {
$('form').bind("submit", function(e) {
if ($input1.val() > $input2.val()) {
alert('min value is greater than max value');
$input1.focus();
e.preventDefault();
} else {
alert('normally submitted');
evt.preventDefault();
}
})
})
You can find the full sample on http://jsfiddle.net/cruzj/Lcwhqjj7/1/
Thanks!!
.val() returns a string, so
$input1.val() > $input2.val() === true when input1 = "7" and input2 = "456456"
to avoid that comportement you have to use parseInt() function
parseInt($input1.val()) > parseInt($input2.val()) === false when input1 = "7" and input2 = "456456"
example here

Calculate sum and multiply its value

I'm calculating the sum of a and b and putting it in text box named sum.
After I enter a number in number text box, it should calculate the final = sum * number.
<input type="text" class="txt_1_0" name="a" />
<input type="text" class="txt_1_0" name="b" />
<input type="text" id="sum" name="sum" />
<input type="text" class="number" name="number" />
<input type="text" class="final" name="final" />
I tried the following:
$(document).ready(function() {
$(".txt_1_0").change(function() {
var total = 0.00;
var textbox3 = 0.00; // this gonna be your third textbox
$(".txt_1_0").each(function() {
total += parseFloat(this.value) / 5;
});
textbox3 = $("#sum").val((total).toFixed(2));
});
});
How do I get the number value and calculate final?
You haven't actually added any function that would do the final calculation. So to multiply the sum (subtotal) with number, do the following:
$(".number").change(function () {
var final = $("#sum").val() * $(this).val();
$('.final').val(final);
});
Here is a demo - note that I have removed the division by 5 from your previous function as it didn't make sense from the the way your question was asked.
Or you can use keyup event with this jQuery code Fiddle
<script type="text/javascript">
$(document).ready(function(){
$('input[type="text"]').on('keyup',function(){
var a=parseFloat($('.txt_1_0:first').val())
var b=parseFloat($('.txt_1_0:last').val())
if(a && b){$('#sum').val(a+b)}
var number=$('.number').val()
if(number){
$('.final').val($('#sum').val()*number)
}
})
})
</script>

Categories

Resources