Below I have Javascript code (a calculator). Also I have several inputs (<input name="roip" value="xxxx" class="input c2" type="text">). What should I write in value (value"xxxx" )?
This is my HTML:
<input name="amount" value="xxxx" onchange="calculate()" type="text">
<input name="roip" value="xxxx" class="input c2" type="text">
<input name="ret" value="xxxx" class="input c2" type="text">
And my Javascript:
function calculate() {
c = new Array(1, 10, 500, 104, 1, 501, 2000, 105, 1, 2001, 5000, 106, 1, 5001, );
a = document.calc.amount.value
p = 0;
for (i = 0; i < c.length; i += 4) {
if (c[i] == document.calc.plan.selectedIndex + 1) {
if ((a >= c[i + 1]) && (a <= c[i + 2])) p = c[i + 3];
}
}
if (p == 0) {
p = '-';
a = '-';
} else {
a = a * p / 100;
}
document.calc.roip.value = p;
document.calc.ret.value = a;
}
calculate();
Write whatever you think is a good default/example value or don't supply a default. Alternatively you could have a message like "type amount here" which is cleared when the user first clicks the textbox.
are you asking how to display the results in the inputs?
you don't need to assign a value to your inputs, because the js function is getting the values ( document.getValueByName('amount').value )
you can use :
to display the value zero as default value
Related
I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>
How to I restrict a number entering into input field (numeric) greater than another number using JavaScript?
I used:
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal").value;
var matricobtained = document.getElementById("matricobtained").value;
var intertotal = document.getElementById("intertotal").value;
var interobtained = document.getElementById("interobtained").value;
var bachelortotal = document.getElementById("bachelortotal").value;
var bachelorobtained = document.getElementById("bachelorobtained").value;
var mphilltotal = document.getElementById("mphilltotal").value;
var mphillobtained = document.getElementById("mphillobtained").value;
if (matricobtained > matrictotal || interobtained > intertotal || bachelorobtained > bachelortotal || mphillobtained > mphilltotal) {
alert("pleses provide obtained marks less then total marks");
e.returnValue = false;
e.preventDefault();
} else {
return true;
}
}
But after alert it allows number place in input field.
First, just get the object that represents each object then pass in the two methods into a helped method to do the actual comparison. If the values are not what you are looking for, then set the objects value to "" and highlight the textbox to show which one is wrong.
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal");
var matricobtained = document.getElementById("matricobtained");
var intertotal = document.getElementById("intertotal");
var interobtained = document.getElementById("interobtained");
var bachelortotal = document.getElementById("bachelortotal");
var bachelorobtained = document.getElementById("bachelorobtained");
var mphilltotal = document.getElementById("mphilltotal");
var mphillobtained = document.getElementById("mphillobtained");
checkValue(matrictotal, matricobtained);
checkValue(intertotal, interobtained);
checkValue(bachelortotal, bachelorobtained);
checkValue(mphilltotal, mphillobtained);
}
function checkValue(total, obtained){
if (obtained.value > total.value) {
alert("Please provide obtained marks less then total marks: " + obtained.id);
obtained.value = "";
obtained.classList.add("error");
} else {
obtained.classList.remove("error");
return true;
}
}
.error {
border: 2px solid #FF0000;
}
<label for="matrictotal">matrictotal</label>
<input type="text" id="matrictotal" value="10">
<label for="matricobtained">matricobtained</label>
<input type="text" id="matricobtained" value="10">
<br />
<label for="intertotal">intertotal</label>
<input type="text" id="intertotal" value="10">
<label for="interobtained">interobtained</label>
<input type="text" id="interobtained" value="10">
<br />
<label for="bachelortotal">bachelortotal</label>
<input type="text" id="bachelortotal" value="10">
<label for="bachelorobtained">bachelorobtained</label>
<input type="text" id="bachelorobtained" value="10">
<br />
<label for="mphilltotal">mphilltotal</label>
<input type="text" id="mphilltotal" value="10">
<label for="mphillobtained">mphillobtained</label>
<input type="text" id="mphillobtained" value="10">
<button onclick=numberalert(this)>Check values</button>
Note : In Javascript there is no strictly greater than or strictly less than comparator .
In case if you need strictly greater than use
(a !==b && a > b) (or) (!(a < b))
Similarly for strictly less than use
(a !== b && a < b) (or) (!(a>b))
var toCheckNumber = 100;
validate = function(el, event) {
var errorText = document.getElementById('errorText');
errorText.innerHTML = "";
var x = event.which;
var value = el.value;
var number = 0;
switch (x) {
case 48: number =0;break;
case 49: number = 1; break;
case 50: number = 2; break;
case 51: number = 3; break;
case 52: number = 4; break;
case 53: number = 5; break;
case 54: number = 6; break;
case 55: number = 7; break;
case 56: number = 8; break;
case 57: number = 9; break;
case 8: number = -1; break;
case 46: number = -1; break;
default : event.preventDefault(); return ;
}
var tempval = (number !== -1) ? value * 10 + number : value;
if (!(tempval < toCheckNumber)) {
event.preventDefault();
errorText.innerHTML = "Enter number less than " + toCheckNumber;
}
}
<input type="number" onkeydown="validate(this,event)" onchange="document.getElementById('errorText').innerHTML=''">
<div id="errorText" style="color:red"></div>
I am making a program that has an array of numbers and then the user inputs some values in and clicks on verify. the value he enters has to be in order with the array of numbers and if it isn't the user gets an alert message sorry.
The value inside the first input bar decides from which number of the array should the comparison should start. For example, if the array holds numbers like {2,4,6,8,10} and the user enters 6 in the first input bar and then he enters 8 and 10 in the next two bars, he should get the result "678"
If he doesn't get the first number right lets say he enters 3, and since 3 isn't in the array, then it doesn't matter what he enters in the other input bars, he would get the result "Sorry".
Similarly, if the user types 4 in the first input bar but then then in the second bar he types 8, he should still get the result "Sorry" since the order of the array is {4,6,8} not {4,8}.
I made a program but whenever I click on the verify button, nothing happens.
Here is my codes. and here is also the result I am getting:
https://jsfiddle.net/53j19rpt/
<html>
<head>
</head>
<script type="text/javascript">
var arr = [];
var t;
var num = 2;
var x = [];
for (var x = 0; x < 4; x++) {
document.getElementById("one" + x);
}
function go() {
for (var t = 0; t < 4; k++) {
x[t] = num * (t + 1);
}
for (var k = 0; k < 4; k++) {
if (document.getElementById("one0").value >= x[k])
if (document.getElementById("one" + k).value == x[k])
document.write(document.getElementById("one" + k).value);
else
document.write("Sorry");
}
}
</script>
<body>
<input id="one0" type="text">
<input id="one1" type="text">
<input id="one2" type="text">
<input id="one3" type="text">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
</body>
</html>
Version 1 - all 4 have to be correct in order
var x = [],num=2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = num * (i + 1);
}
console.log(x);
function go() {
var found=0;
for (var i = 0; i < 4; i++) {
if (document.getElementById("one" + i).value == x[i]) {
found++;
}
}
document.getElementById("result").innerHTML = found==x.length?x:"Sorry";
}
<input id="one0" type="text" value="" />
<input id="one1" type="text" value="" />
<input id="one2" type="text" value="" />
<input id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" />
<span id="result"></span>
Version 2 Error if anything entered is wrong
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = "";
for (var i = 0; i < field.length; i++) {
res += field[i].value; // string concatenation
}
document.getElementById("result").innerHTML = (res == x.join("")) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
Version 3 - any 1, 2, 3 or 4 entries are deemed correct if they are subpart of array, e.g. 46 is ok and so is 68 but not 26
var x = [],
num = 2;
// I assume you will want to change this to random later
for (var i = 0; i < 4; i++) {
x[i] = ""+num * (i + 1); // make string
}
console.log(x);
window.onload = function() {
var field = document.querySelectorAll(".entry");
for (var i = 0; i < field.length; i++) {
field[i].onkeyup = function() {
document.getElementById("result").innerHTML = (x.indexOf(this.value) == -1)?"Sorry":this.value;
}
}
}
function go() {
var field = document.querySelectorAll(".entry"),
error = false,
res = [];
for (var i = 0; i < field.length; i++) {
if (x.indexOf(field[i].value) !=-1) res.push(field[i].value);
}
document.getElementById("result").innerHTML = (x.join(".").indexOf(res.join("."))!=-1) ? res : "Sorry";
}
<input class="entry" id="one0" type="text" value="" />
<input class="entry" id="one1" type="text" value="" />
<input class="entry" id="one2" type="text" value="" />
<input class="entry" id="one3" type="text" value="" />
<input type="button" id="verifyBtn" value="verify" onclick="go()" /><br/>
<span id="result">test</span>
If I understand your question well this should work:
<html>
<head>
</head>
<body>
<input id="one0" type="text" value="">
<input id="one1" type="text" value="">
<input id="one2" type="text" value="">
<input id="one3" type="text" value="">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
<script type="text/javascript">
function go() {
var arrinputs = [];
var arr = [2, 4, 10, 12];
for (var x = 0; x < 4; x++) {
var tmp = parseInt(document.getElementById("one" + x).value)
if (!isNaN(tmp))
arrinputs.push(tmp);
}
var a = "-" + arrinputs.join('-') + "-";
var b = "-" + arr.join('-') + "-";
if (b.indexOf(a) != -1) {
alert("Ok!");
} else {
alert("Sorry!");
}
}
</script>
</body>
</html>
Test 1 (check array 2, 4, 6, 8)
Returns: Corrent
Test 2 (check array 2, 4, 6, 8)
Returns: Corrent
Test 3 (check array 2, 4, 6, 8)
Returns: Sorry
Test 4 (check array 2, 4, 10, 12)
Returns: Corrent
Test 5 (check array 2, 4, 10, 12)
Returns: Sorry
Test 6 (check array 2, 4, 10, 12)
Returns: Sorry
I have one textbox and keypad design to take date of birth by user.
HTML code
Memory = "0"; // initialise memory variable
Current = "0"; // and value of Display ("current" value)
Operation = 0; // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) //ADD A DIGIT TO DISPLAY (keep as 'Current')
{ if (Current.indexOf("!") == -1) //if not already an error
{ if ( (eval(Current) == 0)
&& (Current.indexOf(".") == -1)
) { Current = dig;
} else
{ Current = Current + dig;
};
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else
{ Current = "Hint! Press 'Clear'"; //Help out, if error present.
};
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
}
function Clear() //CLEAR ENTRY
{ Current = "0";
document.calc.display.value = Current;
}
<form Name="calc" method="post">
<input class="intxt1" autocomplete="off" id="ptdob" maxlength="6" name="display" type="tel" value="" placeholder="MM/DD/YYYY"><button class="cancel-icon" type="reset" OnClick="Clear()"></button>
<div class="calculator" style="margin: 30px auto;">
<!-- Screen and clear key -->
<div class="keys">
<!-- operators and other keys -->
<span OnClick="AddDigit('1')">1</span>
<span OnClick="AddDigit('2')">2</span>
<span OnClick="AddDigit('3')">3</span>
<span OnClick="AddDigit('4')">4</span>
<span OnClick="AddDigit('5')">5</span>
<span OnClick="AddDigit('6')">6</span>
<span OnClick="AddDigit('7')">7</span>
<span OnClick="AddDigit('8')">8</span>
<span OnClick="AddDigit('9')">9</span>
<span OnClick="AddDigit('0')" style="width: 166px;">0</span>
<span class="clear" OnClick="Clear()">
<div class="xBox">X</div>
</span>
</div>
</div>
</form>
I am taking date in MM/DD/YYYY format. Above code is working fine. It takes digits by automatically adding / in between digits. But when user wants to enter date like 05/11/2016, for month it does not allowing to take 0 at start. when user clicks 0 from keypad and then 5 for example, it coverts 0 to 5. It does not take 0 at the beginning. And it adds next clicked digit to month. e.g. 51/11/2016 like this.
How should I allow 0 at the beginning for month?
NOTE: I have my web page design for above is like below image:
User should not type directly in textbox. Textbox should have inputs from the keypad that I have design. So no use of applying date functionality on textbox like type="date" or using datepicker or any plugins as user is not directly using textbox.
You're quite close, but there are definitely better ways of doing this, as suggested in the comments (DatePicker, moment.js(), etc.).
However, looking at your code, you have a few problems.
Current = "0"; - why are we setting the default value to '0'? It should be Current = "";.
if(eval(Current) == 0) - I have no idea what this is doing. However, if the first digit is '0', then you're doing if(eval(0) == 0). i.e. if(false == false). i.e. if(true).
eval is evil, but if you insist on doing it that way, then you can switch that line to if(eval(Current) === undefined).
Lastly, in Clear, Current = "0"; - same as before. Current = "";.
What you have isn't a bad first attempt at JS, so keep practicing. Some tips:
Lose the Title Case var/function names.
Use var whenever defining variables (unless using ES6 - then use let/const)
Don't recreate the wheel - use libraries that already exist.
Use correct HTML attributes - onClick over OnClick.
Memory = "0"; // initialise memory variable
Current = ""; // and value of Display ("current" value)
Operation = 0; // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) //ADD A DIGIT TO DISPLAY (keep as 'Current')
{ if (Current.indexOf("!") == -1) //if not already an error
{ if ( (eval(Current) === undefined)
&& (Current.indexOf(".") == -1)
) { Current = dig;
} else
{ Current = Current + dig;
};
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else
{ Current = "Hint! Press 'Clear'"; //Help out, if error present.
};
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
}
function Clear() //CLEAR ENTRY
{ Current = "";
document.calc.display.value = Current;
}
<form Name="calc" method="post">
<input class="intxt1" autocomplete="off" id="ptdob" maxlength="6" name="display" type="tel" value="" placeholder="MM/DD/YYYY"><button class="cancel-icon" type="reset" OnClick="Clear()"></button>
<div class="calculator" style="margin: 30px auto;">
<!-- Screen and clear key -->
<div class="keys">
<!-- operators and other keys -->
<span OnClick="AddDigit('1')">1</span>
<span OnClick="AddDigit('2')">2</span>
<span OnClick="AddDigit('3')">3</span>
<span OnClick="AddDigit('4')">4</span>
<span OnClick="AddDigit('5')">5</span>
<span OnClick="AddDigit('6')">6</span>
<span OnClick="AddDigit('7')">7</span>
<span OnClick="AddDigit('8')">8</span>
<span OnClick="AddDigit('9')">9</span>
<span OnClick="AddDigit('0')" style="width: 166px;">0</span>
<span class="clear" OnClick="Clear()">
<div class="xBox">X</div>
</span>
</div>
</div>
</form>
I have a field that reads your lawn takes a ___ hour shower. It is calculated by the square footage input. When the value of this field equals 8,11,or 18. I would like it to read "an ____ hour shower." How would this be made possible?
http://jsfiddle.net/on6c360o/
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var g = document.getElementById("g");
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
b.innerHTML = a.value * .62;
g.innerHTML = Math.round(a.value * .0103);
}
<div class="mobile" style="text-align:center">
<h2>Lawn Square Footage</h2>
<input id="a" onkeypress="return isNumberKey(event)" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />
<h2>Water Usage</h2>
<h2 id="b">___</h2>
<h2>Gallons per day</h2>
<h2>Your lawn takes <span id="g">___</span> hour showers</h2>
</div>
You can use a ternary operator to say if hours is 8, 11, or 18 then display an else display a.
var hours = Math.round(a.value * .0103);
g.innerHTML = (hours === 8 || hours === 11 || hours === 18 ? 'an' : 'a') + ' ' + hours;
Here's an example http://jsfiddle.net/bmec3tad/
You could perform an if check when changing the HTML contents like so:
function calculate() {
b.innerHTML = a.value * .62;
var gVal = Math.round(a.value * .0103);
g.innerHTML = gVal + ([8, 11, 18].indexOf(gVal) == -1 ? "a" : "an");
}