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">
Related
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>
I have tried two different Javascript code to find the largest number from three user inputs. I am not getting the highest number from none of the codes. Please help!
HTML Code:
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<input type="button" id="high" value="high" onclick="high()">
<input type="text" id="avg">
<p id="result"></p>
JavaScript Code(Try 1):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
var avg = Math.max(Number(num1),Number(num2),Number(num3))
document.getElementById("result").innerHTML=avg;
JavaScript Code(Try 2):
function high() {
let num1 = document.getElementsByName("num1")[0].value;
let num2 = document.getElementsByName("num2")[0].value;
let num3 = document.getElementsByName("num3")[0].value;
if(Number(num1)>Number(num2) && Number(num1)>Number(num3))
{
document.getElementsByName("avg")[0].value = num1;
}
if(Number(num2)>Number(num1) && Number(num2)>Number(num3))
{
document.getElementsByName("avg")[0].value = num2;
}
if(Number(num3)>Number(num2) && Number(num3)>Number(num1))
{
document.getElementsByName("avg")[0].value = num3;
}
you are making things complex try this code .
Assignment 1: <input type="text" name="num1"><br>
Assignment 2: <input type="text" name="num2"><br>
Assignment 2: <input type="text" name="num3"><br>
<button onclick="high()">Submit</button>
<p id="result"></p>
<script>
function high(){
var arr = document.querySelectorAll("input");
var emptyarray = [];
arr.forEach((elem) => {
emptyarray.push(elem.value);
})
var max = Math.max.apply(null, emptyarray);
document.getElementById("result").innerHTML=max;
}
</script>
you will get the heighest number result , you can restrict the input field to just enter the number so that no one can add string instead of number and your code work fine .
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);
}
I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">
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>