I was trying to find the reason why my code doesnt work, and chrome comes back with this eror:
Uncaught ReferenceError: calcMPG is not defined...
Can someone spot my mistake ?(desperate)
<script type="text/javascript">
function calcMPG() {
document.calc.startingMileage.value = startMileage;
document.calc.endingMileage.value = endMileage;
document.calc.gallonsUsed.value = gallUsed;
var MPG = (endMileage - startMileage) / gallUsed;
if (isNAN(startMileage) || isNAN(endMileage) || isNAN(gallUsed)) alert('please type in numbers only!');
else document.calc.milesPerGalon.value = MPG;
}
</script>
<form name="calc">Starting mileage:
<input type="text" value="0" name="startingMileage" onchange="calcMPG()">
<br>Ending mileage:
<input type="text" value="0" name="endingMileage" onchange="calcMPG()">
<br>Gallons used:
<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()">
<br>Miles per galon:
<input type="text" value="0" name="milesPerGalon">
</form>
Your declarations are wrong please correct them.
var startMileage = document.calc.startingMileage.value ;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
I don't know why you do that, but try this:
<script type="text/javascript">
function calcMPG(){
var startMileage = document.calc.startingMileage.value,
endMileage = document.calc.endingMileage.value,
gallUsed = document.calc.gallonsUsed.value,
MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed)){
alert('please type in numbers only!');
} else {
document.calc.milesPerGalon.value = MPG;
}
}
</script>
<form name="calc">
Starting mileage:<input type="text" value="0" name="startingMileage" onchange="calcMPG()"><br>
Ending mileage:<input type="text" value="0" name="endingMileage" onchange="calcMPG()"><br>
Gallons used:<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()"><br>
Miles per galon:<input type="text" value="0" name="milesPerGalon">
</form>
startMileage
and your other right side references don't mean anything, they are undefined variables.
Give your inputs an id and fetch the values from them like this:
var startingMileage = document.getElementById('startingMileage').value;
Check here Fiddle
function calcMPG(){
var startMileage = document.calc.startingMileage.value;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
var MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed))
alert('please type in numbers only!');
else
document.calc.milesPerGalon.value = MPG;
}
Related
I have below code that is working fine, but I want to validate textbox TBMonday to force users to enter in the specified pattern. How can I do this with Javascript (Please I don't want to use input type='time')
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" pattern="(2[0-4]|1[0-9]|[1-
9])\:(5[0-9]|4[0-9]|3[0-9]|2[0-9]|1[0-9]|[0-9])-(2[0-4]|1[0-9]|[1-9])\:(5[0-9]|4[0-9]|3[0-
9]|2[0-9]|1[0-9]|[0-9])" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value = document.getElementById('TBMonday').value;
}
</script>
Here is how I finally write my code and it work for me.
<input type="text" id="TBMonday" size="7" placeholder="hh:mm-hh:mm" required
onblur="validateMon();" onKeyUp="TBMondayEl();">
<input type="text" id="TBMonday2" size="7">
<script>
function validateMon(){
var phoneNumber = document.getElementById('TBMonday').value;
var phoneRGEX = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5]
[0-9]$/;
var phoneResult = phoneRGEX.test(phoneNumber);
if(phoneResult == false)
{
document.getElementById('TBMonday').value = '';
document.getElementById('TBMonday2').value = '';
alert('Please enter TimeBelt in "HH:MM-HH:MM" format');
return false;
}
return true;
}
<script>
function TBMondayEl()
{
document.getElementById('TBMonday2').value
document.getElementById('TBMonday').value;
}
</script>
Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>
How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />
In this code, the variable value of "ans" is always false whether I have entered value according to pattern or not. I cannot understand the reason.
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
Try this
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
<script>
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
</script>
You should move all your code into a defined function validate()
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
You used function named validate in the submit button event, but did not define it. After defining the validate function, everything works fine.
function validate() {
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
When I make this button:
<div id="Input #1">
<label for="input1">Input #1:</label>
<input type="number" id="input1" name="input1" onchange="i1set()">
</div>
And then have this JavaScript:
var i1 = undefined;
var i1set = function(){
i1 = document.getElementById("input1").value;
}
var solution = parseFloat(i1)+parseFloat(i2);
alert(solution);
It works no problem.
But, when I eliminate the onchange part of the html, and instead create an event listener in js, then I get problems. One of the problems is that having parseFloats give me "NaN" instead of a number answer... but the bigger problem is that even when I get rid of parseFloats, even with subtraction, addition, division, it gives me weird incorrect answers.
Below is my current code that no longer works:
<form>
<input type="radio" id="addition" name="addition" value="addition"><label>Addition</label><br>
<input type="radio" id="subtraction" name="subtraction" value="subtraction"><label>Subtraction</label><br>
<input type="radio" id="multiplication" name="multiplication" value="multiplication"><label>Multiplication</label><br>
<input type="radio" id="division" name="division" value="division"><label>Division</label><br>
<div id="Input #1">
<label for="input1">Input #1:</label>
<input type="number" id="input1" name="input1">
</div>
<div id="Input #2">
<label for="input2">Input #2:</label>
<input type="number" id="input2" name="input2">
</div>
<input type="submit" id="submit" value="Solve" />
</form>
<script>
var i1 = undefined;
var i2 = undefined;
var i1set = function(){
i1 = document.getElementById("input1").value;
}
var i2set = function(){
i2 = document.getElementById("input2").value;
}
var solve = function(){
if ( (i1 != undefined) && (i2 != undefined) ) {
if(document.getElementById('addition').checked) {
var solution = parseFloat(i1)+parseFloat(i2);
alert(solution);
}
if(document.getElementById('subtraction').checked) {
var solution = i1-i2;
alert(solution);
}
if(document.getElementById('multiplication').checked) {
var solution = i1*i2;
alert(solution);
}
if(document.getElementById('division').checked) {
var solution = i1/i2;
alert(solution);
}
}
}
document.getElementById("input1").addEventListener("change", i1set(), false);
document.getElementById("input2").addEventListener("change", i2set(), false);
document.getElementById("submit").addEventListener("click", solve, false);
</script>
</body>
</html>
The problem is that empty string is not equal to udnefined so this checkes:
if ((i1 != undefined) && (i2 != undefined)) {
behave not the way you expect. The if block can be simpler:
if (i1 && i2) { // or i1 !== '' && i2 !== ''
The second problem is that you need to provide function reference as event listener, not execute it immediately with ():
document.getElementById("input1").addEventListener("change", i1set, false);
// Note, you don't need () here ------^