Why do I get same result from two difference? - javascript

<h2>Volume</h2>
<b>Choose Convert : </b><br><br>
<input type=radio name=volConvert id="LitToGal" value="LitToGal" checked>Litre To Gallon<br>
<input type=radio name=volConvert id="GalToLit" value="GalToLit">Gallon To Litre
<br><br>
<label>
<b>Input a data: </b><br>
<input name="volData" id="inVolData" type="text" size="10">
</label><br><br>
<p>
<input type=button value="Convert" onClick="VolConvert()" />
</P>
<h4 id="result"></h4>
</div>
var value = parseFloat(0);
var conValue = parseFloat(0);
function VolConvert() {
if (document.getElementById("LitToGal")) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 16.52);
} else if (document.getElementById("GalToLit")) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 113.50);
}
var conValue = value.toFixed(2);;
resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;
}

You need to compare the "checked" value
function VolConvert() {
if (document.getElementById("LitToGal").checked) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 16.52);
} else if (document.getElementById("GalToLit").checked) {
var inputData = parseFloat(document.getElementById("inVolData").value);
value = (inputData * 113.50);
}
var conValue = value.toFixed(2);;
resultmessage = ("The converted value: " + conValue);
document.getElementById("result").innerHTML = resultmessage;
}

In your code you have the following If-Statement:
if (document.getElementById("LitToGal")) {
...
else if (document.getElementById("GalToLit")) {
...
}
This document.getElementById("LitToGal") will always be true since the element exists in your HTML .
Meaning value = (inputData * 16.52); will always be the result.
To fix the statement, try the following:
if (document.getElementById("LitToGal").checked) {
...
else if (document.getElementById("GalToLit").checked) {
...
}

if(document.getElementById("LitToGal").checked)
if (document.getElementById("GalToLit").checked)

Related

Javascript loop array for form validation

I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}

adding the sum of two separate functions

(ETA: I'm working on this for a class and the teacher wants everything to be "oninput"...yes, it's annoying :p )
I'm working on a form where each function miltiplies a number and gives me a "subtotal" on input. I'd like to take the two "subtotal" answers from the two functions and add them togething into a "total" amount. I feel like this should be simple but nothing I've tried works.
Here's what I've got in the javascript that works to give me the two subtotals:
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
document.getElementById('subTotalOne').innerHTML = '$ ' + qty1 * 19.99;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
document.getElementById('subTotalTwo').innerHTML = '$ ' + qty2 * 37.99;
}
Here's the important parts of the html:
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()"/><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()"/><br>
</div>
<div class="price">
<label for="price">Price</label>
<p>$19.99</p>
<p>$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
I'm trying to add the subTotalOne and subTotalTwo and have them output at orderTotal, essentially. :)
Thanks!
//Global variables (concidering ID is unique)
let subTotalOne, subTotalTwo, qty1, qty2, orderTotal;
const setup = () => {
subTotalOne = document.getElementById('subTotalOne');
subTotalTwo = document.getElementById('subTotalTwo');
qty1 = document.getElementById('qty1');
qty2 = document.getElementById('qty2');
orderTotal = document.getElementById('orderTotal');
myCalculator();
myCalculatorTwo();
};
const updateTotal = (target, value) => {
if(target == null || value == null || Number.isNaN(value)) return;
target.textContent = `$ ${value.toFixed(2)}`;
target.setAttribute('data-value', value.toFixed(2));
}
const getTotal = () => {
if(subTotalOne == null || subTotalTwo == null) return 0;
const [value1, value2] = [
Number.parseFloat((subTotalOne.dataset?.value ?? 0), 10),
Number.parseFloat((subTotalTwo.dataset?.value ?? 0), 10)
];
if(Number.isNaN(value1) || Number.isNaN(value2)) return;
else return value1 + value2;
};
const updateOrderTotal = () => updateTotal(orderTotal, getTotal());
const myCalculator = () => {
const value = Number.parseFloat(qty1.value || 0, 10) * 19.99;
updateTotal(subTotalOne, value);
updateOrderTotal();
}
const myCalculatorTwo = () => {
const value = Number.parseFloat(qty2.value || 0, 10) * 37.99;
updateTotal(subTotalTwo, value);
updateOrderTotal();
}
window.addEventListener('load', setup);
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()" min="0"><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()" min="0"><br>
</div>
<div class="price">
<label for="price">Price</label>
<p data-value="19.99">$19.99</p>
<p data-value="37.99">$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
Here's how you do it:
function orderTotal() {
const qty1 = document.getElementById('qty1').value;
const qty2 = document.getElementById('qty2').value;
const total = parseInt(qty1) + parseInt(qty2);
document.getElementById('orderTotal').innerHTML = '$ ' + total;
}
Remove the oninput="orderTotal()" in your span element and trigger the above function using a button click e.g. <button onClick="orderTotal()">Calculate Total</button> or maybe when either of your two inputs' value changes. Also consider using const and let instead of var.
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
Instead of querying the DOM in Ray's answer--as DOM queries should generally be avoided since they are slow W3 Wiki, you could also consider using a shared variable between the two functions.
Also, consider using something else in place of innerHTML, mostly because of efficiency why-is-element-innerhtml-bad-code.
var total1;
var total2;
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
total1 = qty1 * 19.99
document.getElementById('subTotalOne').textContent = '$ ' + total1;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
total2 = qty2 * 37.99;
document.getElementById('subTotalTwo').textContent = '$ ' + total2;
}
function orderTotal() {
document.getElementById('orderTotal').innerHTML = '$ ' + (total1 + total2);
//parentheses because '$' isn't a number so the numbers total1 and total2 will be treated like strings and joined together
}

Set HTML textbox value from Javascript function return value- (Javascript)

How do I set the text box value from javascript return value? I tried the below code it's not working- where am I wrong?
function getname(name) {
var subindex = name.indexOf(" ") + 1;
return (name.substring(subindex));
}
var res = (getname("Harpreet Kaur"));
document.getElementById("lname").value = res;
//alert(res);
<body>
<input type="text" id="lname">
</body>
It works perfectly:
function getname(name) {
var subindex = name.indexOf(" ") + 1;
return (name.substring(subindex));
}
var res = getname("Harpreet Kaur");
document.getElementById("lname").value = res;
<input type="text" id="lname">

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

How to seperate the values of textbox so that I can sort by each value

I have a textbox where the user can input a value into a listbox. Then, I have buttons to either Delete that value, or Sort the value.
My problem is that I want the value to be sorted by those 2 separated values. For example, the user would enter City=Chicago in the textbox. And there would be 2 sort buttons, to 'Sort by City' and 'Sort by Value' where value in this case is Chicago.
So after hours of trying I can't figure out how to:
1. Restrict the user to only be able to enter a value like %=% (e.g. City=Chicago)
2. Have separate sort buttons for the values on either side of the equal sign
http://jsfiddle.net/uudff585/6/
<div class='teststyles'>
<h3>Test</h3>
Name/Value Pair
<br />
<input id="PairTextbox" type="text" value="city" />=<input id="PairTextbox1" type="text" />
<input type="button" value="Add" id="addButton" />
<br />
<br />Name/Value Pair List
<br />
<select multiple="multiple" id="PairListbox"></select>
<input type="button" value="Sort By Name" sort-type="0" id="sortName">
<input type="button" value="Sort By Value" sort-type="1" id="sortValue"><br>
<input type="button" value="Delete" id="deleteButton" />
Script:
var listArray = [];
function addNewItem() {
console.log("ok2");
var textbox = document.getElementById('PairTextbox');
var textbox1 = document.getElementById('PairTextbox1');
var listbox = document.getElementById('PairListbox');
var newOption = document.createElement('option');
newOption.value = listArray.length-1; // The value that this option will have
newOption.innerHTML = textbox.value + "=" + textbox1.value; // The displayed text inside of the <option> tags
listbox.appendChild(newOption);
listArray.push([textbox.value, textbox1.value, ]);
}
function deleteItem() {
var listbox = document.getElementById('PairListbox');
if (listbox.selectedIndex != -1) {
console.log(listbox.selectedIndex);
delete listArray[listbox.value];
listbox.remove(listbox.selectedIndex);
}
}
function sortItems(e) {
var sorttype = e.target.getAttribute("sort-type");
var $listbox = document.getElementById('PairListbox');
var $options = listArray.map(function (option) {
return option;
});;
$options.sort(function (a, b) {
var an = a[sorttype],
bn = b[sorttype];
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$listbox.innerHTML = "";
$options.forEach(function ($option, index) {
var newOption = document.createElement('option');
newOption.value = index; // The value that this option will have
newOption.innerHTML = $option[0] + "=" + $option[1]; // The displayed text inside of the
$listbox.appendChild(newOption);
});
}
document.getElementById('addButton').addEventListener('click', addNewItem);
document.getElementById('sortName').addEventListener('click', sortItems);
document.getElementById('sortValue').addEventListener('click', sortItems);
document.getElementById('deleteButton').addEventListener('click', deleteItem);
For those who would like to use jQuery, validation and auto-sorting this FIDDLE. The HTML is:
<div class='teststyles'>
<h3>Test</h3>
<p>Name/Value Pair</p>
<p><input id="PairTextbox" type="text" /> <input type="button" value="Add" id="addButton" /></p>
<p>Name/Value Pair List</p>
<p><select multiple="multiple" id="PairListbox"></select></p>
<p>
<input id="byname" type="radio" name="sortby" value="name" checked="checked" /> <label for="byname">sort by name</label><br />
<input id="byvalue" type="radio" name="sortby" value="value" /> <label for="byvalue">sort by value</label>
</p>
<p><input type="button" value="Delete selected" id="deleteButton" /></p>
</div>
and the script:
// Keep your pairs in memory
var pairs = [];
// Keep record of dynamic elements
var listbox = $('#PairListbox');
var textbox = $('#PairTextbox');
var sortInput = $('input[name=sortby]');
function sortItems() {
sortType = sortInput.filter(':checked').val();
if ( sortType=='name' ) {
// Sort by key
console.log( 'sort by key' );
pairs = pairs.sort(function (a, b) {
return a.k.localeCompare(b.k);
});
} else {
// Sort by value
console.log( 'sort by val' );
pairs = pairs.sort(function (a, b) {
return a.v.localeCompare(b.v);
});
};
console.log( pairs );
console.log( '----------' );
};
function printItems() {
var optionsHtml = '';
$.each(pairs, function(i, item) {
optionsHtml += '<option value="' + item.k + '=' + item.v + '">' + item.k + '=' + item.v + '</option>';
});
listbox.html(optionsHtml);
};
// Customize validation of new input
function validateInput() {
var str = textbox.val().replace(/\s+/g, '_');
var splited = str.split('=');
if (splited.length == 2 && splited[0] && splited[1]) {
// Maybe also check if pair already exists in array?
pairs.push({
k: splited[0],
v: splited[1]
});
return true;
} else {
false;
};
}
function addNewItem() {
if (validateInput()) {
sortItems();
printItems();
} else {
alert('Wrong input value!');
}
}
function deleteItem() {
var selectedItems = listbox.find('option:selected');
selectedItems.each(function(i) {
var thisItem = $(this);
var thisValueSplit = thisItem.val().split('=');
pairs = pairs.filter(function (el) {
return !(el.k==thisValueSplit[0] && el.v==thisValueSplit[1]);
});
printItems();
});
}
$('#addButton').on('click', addNewItem);
$('#deleteButton').on('click', deleteItem);
sortInput.on('change', function(e) {
sortItems();
printItems();
});

Categories

Resources