This is JavaScript code:
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1")
Price = 12.5;
Stock = 15;
else
Price = "40";
Stock = "5";
document.getElementById("price") = Price;
document.getElementById("stock") = Stock;
}
< /script
In the body of HTML:
<select id="product"><option value="1" >PRODUCT 1</option>
<option value="2">PRODUCT 2</option> </select
<input type="button" value="Submit" onclick="Choose()">
<input type="text" value="0" id="price">
<input type="text" value="0" id="stock">
I need help!Why this code doesn't work?
Where is my failure?
You need to set the value of the DOM element
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
You need to set the attribute value of the DOM element and not the DOM element itself to an integer value
Also you are missing {} around the if-else block. I am assuming that you missing the > operator while closing the script tag is a typo and not in the original code. If its there change it in the original code too
<script type="text/javascript">
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
< /script>
function Choose() {
var n1, Price, Stock;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = "12.5";
Stock = "15";
} else {
Price = "40";
Stock = "5";
}
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
<select id="product">
<option value="1" >Product1</option>
<option value="2">Product2</option>
</select>
<input type="button" value="Submit" onClick="Choose()">
<input type="text" id="price"/>
<input type="text" id="stock"/>
First of all it might not be the case but you are missing the end tag of the script.
</script>
Secondly you are also missing the brackets for the if and else statements.
if (n1=="1"){
Price=12.5;
Stock=15;
}
else{
Price="40";
Stock="5";
}
Hope it helps!
Br,
José Sousa
<script type="text/javascript">
function Choose(){
var n1,Price,Stock ;
n1 = document.getElementById("product").value;
if (n1 == "1") {
Price = 12.5;
Stock = 15;
}
else {
// place it in block
Price = "40";
Stock = "5";
} // place it in block
document.getElementById("price").value = Price;
document.getElementById("stock").value = Stock;
}
</script>
Assume that the error you get is misplaced else.
If more than one statements are written under condition or loop, it must be made as block
Related
I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.
I hope you are well!!
Recently I created this calculator following a tutorial on youtube.
How you can see below I put all the variable outside the function.
In Firefox is working fine, but if I use Google Chrome and I try to use it, is giving me the result of NaN..... I fixed this error moving the var inside the function, but I don't understand why with Chrome I have to move it inside and Firefox no....
If anyone would be able to give me an explanation I will really appreciate!
Thanks!!!!
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var total = document.getElementById("total");
var calculate;
function result() {
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>
The problem is you're grabbing the values before the user fills them in, right away, when the page loads. (You've said it's "working" in Firefox. It doesn't for me, but if you have autofill enabled, it may be filling in values from a previous run.)
Instead, grab the values within the result function:
var total = document.getElementById("total");
function result() {
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var calculate;
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>
Hello everyone I need you guys help with this
It's suppose to convert the value you entered after you choose an option and click convert.
HTML CODE:/(I'm not sure how to use drop down menus with java script)
<html>
<body>
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1" >Currency 1 to Currency2</option>
<option value="2" >Currency 2 to Currency1</option>
</select>
<br><br>
Value <input type="text" id="value"><br>
Conversion <input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
</body>
</html>
JAVASCRIPT CODE:
<script type="text/javascript">
function Conversion()
{
var val = document.getElementById ("value").value;
var madeSelection = document.getElementById ("Selection").value;
if(madeSelection==1( var ans= +value * 1.37); )){
if(madeSelection==2 ( var ans= +value * 1.30; )){
}
}
conversion.value = ans;
}
</script>
There are several problems that are causing this to be non-functional:
You declare a variable called val that you are not using. Everywhere else in your code, it is called value.
var val = document.getElementById ("value").value;
Older browsers may not deal with a value property of a select element
var madeSelection = document.getElementById ("Selection").value;
Your if statements are malformed (and nested for some reason), and some of the operations are weird.
if(madeSelection==1( var ans= +value( 0.37); )){
if(madeSelection==2 ( var ans= +value * 0.30; )){
...
When properly formatted, your code is:
if (madeSelection == 1(var ans = +value(0.37);)) {
if (madeSelection == 2(var ans = +value * 0.30;)) {
if (madeSelection == 3(var ans = +value * 2.70;)) {
if (madeSelection == 4(var ans = +value * 0.80;)) {
if (madeSelection == 5(var ans = +value * 3.38;)) {
if (madeSelection == 6(var ans = +value * 1.25;)) {}
}
}
}
}
}
When more properly written, it should be:
if (madeSelection == 1) {
var ans = +value(0.37);
}
if (madeSelection == 2) {
var ans = +value * 0.30;
}
if (madeSelection == 3) {
var ans = +value * 2.70;
}
if (madeSelection == 4) {
var ans = +value * 0.80;
}
if (madeSelection == 5) {
var ans = +value * 3.38;
}
if (madeSelection == 6) {
var ans = +value * 1.25;
}
although:
the ans variable, along with all of your other variables should be declared at the top of the function (because that's where they're actually declared anyway, look up variable hoisting).
I'm not sure why you're prefixing the righthand assigment with the +.
value is not a function, but you're apparently attempting to use it as one if madeSelection == 1.
Finally, you're referencing a variable called conversion which has not been defined. This will still probably work as you have an input with an id of conversion and most (but not all) browsers will store the id as a global variable pointing to the element.
Also, when you have many if statements, you may wan't to consider using a switch statement instead.
All together, it should look more like this:
function Conversion() {
var value = document.getElementById("value").value,
conversion = document.getElementById("conversion"),
madeSelection = document.getElementById("Selection"), // get the select
selection = madeSelection.options[madeSelection.selectedIndex].value, // get the selected option
ans = 0;
value = parseFloat(value);
if (!isNaN(value)) {
switch (selection) {
case "6":
ans = value * 1.25;
break;
case "5":
ans = value * 3.38;
break;
case "4":
ans = value * 0.8;
break;
case "3":
ans = value * 2.7;
break;
case "2":
ans = value * 0.3;
break;
case "1":
ans = value * 0.37;
break;
default:
ans = 0;
break;
}
}
conversion.value = ans;
}
<select name="converts" id="Selection">
<option>Choose Option</option>
<option value="1" >EC to US</option>
<option value="2" >EC to Euro</option>
<option value="3" >US to EC</option>
<option value="4" >US to Euro</option>
<option value="5" >Euro to EC</option>
<option value="6" >Euro to US</option>
</select>
<br />
<label for="value">Value</label>
<input type="text" id="value"><br>
<label for="conversion">Conversion</label>
<input type="text" id="conversion"><br><br>
<input type="Button" onclick="Conversion()" value="Convert">
This should work for you:
function Conversion() {
var val = document.getElementById("value").value,
madeSelection = document.getElementById("Selection").value,
ans
if (madeSelection == 1) ans = val * 0.37;
if (madeSelection == 2) ans = val * 0.30;
if (madeSelection == 3) ans = val * 2.70;
if (madeSelection == 4) ans = val * 0.80;
if (madeSelection == 5) ans = val * 3.38;
if (madeSelection == 6) ans = val * 1.25;
document.getElementById("conversion").value = ans;
}
<form>
<select name="converts" id="Selection">
<option>Chose Option</option>
<option value="1">EC to US</option>
<option value="2">EC to Euro</option>
<option value="3">US to EC</option>
<option value="4">US to Euro</option>
<option value="5">Euro to EC</option>
<option value="6">Euro to US</option>
</select>
<br>
<br>Value
<input type="text" id="value">
<br>Conversion
<input type="text" id="conversion">
<br>
<br>
<input type="Button" onclick="Conversion()" value="Convert">
</form>
Instead a lot IF statements you should use SWITCH.
This is the right way
JS
function Conversion()
{
var val = parseInt(document.getElementById ("value").value);
var madeSelection = parseInt(document.getElementById ("Selection").value);
switch(madeSelection)
{
case 1:
var converted = val * 0.37; //EC to US
break;
case 2:
var converted = val * 0.30; //EC to EUR
break;
case 3:
var converted = val * 2.70; //US to EC
break;
//ETC....
default:
alert('You chose wrong option'); // if user chose wrong option, send him message
break;
}
document.getElementById ("conversion").value = converted;
return false; //prevent for submit form
}
Here is fiddle : http://jsfiddle.net/1cdkvpms/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var result = document.getElementById('answer').value;
if (document.getElementById('add')) {
function myFunction() {
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.innerHTML = ans;
}
}
</script>
</head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
</body>
</html>
I'm trying to make a sum solver by taking the values from the two text boxes and after clicking the button, it should post the result in the text box below. However it is not doing that.
I also want the program to change how a problem is solved using the dropdown menu with the mathematical symbols.
Thanks.
I think you're after something like this
function myFunction() {
var result = document.getElementById('answer'),
operator = document.getElementById('problem').value,
add1 = document.getElementById('num1').value,
add2 = document.getElementById('num2').value,
ans = 0;
switch (operator) {
case '+':
ans = (parseInt(add1) + parseInt(add2));
break;
case '-':
ans = (parseInt(add1) - parseInt(add2));
break;
case 'x':
ans = (parseInt(add1) * parseInt(add2));
break;
case '÷':
ans = (parseInt(add1) / parseInt(add2));
break;
}
result.value = ans;
}
instead of using if statements, and creating different functions, just have one function and determine the operand.
Edit: Also, watch out for your variable declarations. 'ans', 'add1' and 'add2' weren't being declared which resulted in global variables being created
The problem should be with the line
var result = document.getElementById('answer').value;
Try the below snippet
var result=document.getElementById('answer');
ans = (parseInt(add1)+parseInt(add2));
result.value=ans;
http://jsfiddle.net/2W5za/1/
You have a few issues. Not sure what you were going for with the if but remove it. Also, set the value of a textbox with value not innerHTML.
function myFunction() {
var result = document.getElementById('answer');
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.value = ans;
}
http://jsfiddle.net/LjqMJ/
Regarding the first part of the question (and that for which this question is titled), one problem I see is this line of code right here:
var result = document.getElementById('answer').value;
What is the type of result? Later on you treat it as if it is a DOMElement with result.innerHTML = ans; by assuming it has a property innerHTML. However because you used .value it's in fact a string which will not have innerHTML.
Regarding the second part, you can assert which function is selected in the <select> by looking at it's .value. The <option> tags will always exist, regardless of if they are selected or not.
Speaking more broadly, I highly recommend you check out using the debugger in either chrome or firefox. That will allow you to drop a breakpoint in your code, and figure out if the value is being computed correctly, and see what it is attempting to write to, all interactively.
Chrome:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
Firefox:
https://developer.mozilla.org/en-US/docs/Tools/Debugger
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">x</option>
<option value="div">%</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
<script type="text/javascript">
function myFunction()
{
var e = document.getElementById("problem");
var sOperation = e.options[e.selectedIndex].value;
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)){
if(sOperation=='add'){
//Add
ans = parseInt(add1)+parseInt(add2);
} else if (sOperation=='sub') {
//Subtract
ans = parseInt(add1)-parseInt(add2);
} else if (sOperation=='mul') {
//Multiple
ans = parseInt(add1) * parseInt(add2);
} else if (sOperation=='div') {
//Divide
ans = parseInt(add1) / parseInt(add2);
}
document.getElementById("answer").value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
There are many things wrong with your code. However, to fix your problem, change = ans to = ans.toString();
You see, in javascript integers and strings cannot change to each other's values without a conversion (kind of like a brother and sister refusing to share), so toString() is used for a conversion to String.
The other thing to change is innerHTML to value, because you are dealing with text boxes.
HTML
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
JavaScript
function myFunction() {
var result = document.getElementById('answer');
var operator = document.getElementById('problem').value;
var add1 = document.getElementById('num1').value;
var add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)) {
//Addition
if (operator == '+')
{
ans = (parseInt(add1) + parseInt(add2));
}
//Subtraction
else if (operator == '-') {
ans = (parseInt(add1) - parseInt(add2));
}
//Multiplication
else if (operator == 'x') {
ans = (parseInt(add1) * parseInt(add2));
}
//Division
else if (operator == '÷') {
ans = (parseInt(add1) / parseInt(add2));
}
//Result
result.value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
Fiddle Demo
There is something in this javascript or html which is is allowing the checkboxes to be ticked but for not even half a second. (I need the checks to stay there!) I also need the additems function to work
var computer = new Array();
computer[0] = "10001, Nvidia Geforce GTX 690, 1200";
computer[1] = "10002, Raedon HD 7950, 450";
computer[2] = "20001, Ivy Bridge i7 3770, 400";
computer[3] = "20002, Ivy Bridge i7 3770k, 420";
computer[4] = "20003, Sandy Bridge i7 2700k, 340";
computer[5] = "20004, Bulldozer FX-8150, 270";
computer[6] = "30001, Antec eleven-hundred, 120";
computer[7] = "30002, Coolermaster HAF-X, 170";
computer[8] = "30003, Antec three-hundred, 50";
computer[9] = "30004, Corsair 550D, 160";
computer[10] = "40001, INTEL-ASrock fatal1ty Z77 Professional Motherboard, 250";
computer[11] = "40002, INTEL-ASrock Z77 extreme9 Motherboard, 350";
computer[12] = "40003, AMD-ASrock fatal1ty 990FX Professional Motherboard, 240";
computer[13] = "40004, AMD-ASUS Sabertooth 990FX Motherboard, 260";
Check all checkboxes function
function check() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 1;
} else {
inputs[x].checked = true;
}
}
}
Uncheck all checkboxes function
function uncheck() {
var leftSide = document.getElementById('table_container_left');
var inputs = leftSide.getElementsByTagName('input');
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'text') {
inputs[x].value = 0;
} else {
inputs[x].checked = false;
}
}
}
add checked items to cart
function addItems() {
var leftSide = document.getElementById('table_container_left');
var rightSide = document.getElementById('table_container_right');
var inputs = leftSide.getElementByTagName('input');
var totalPrice = 0;
var basketTable = "<h3>My Basket:</h3><table><thead><tr><th>Item</th><th>Quantity</th><th>price</th><th>Sub-total</th></tr></thead><tbody>";
for (x=0; x<=inputs.length-1; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].checked == true) {
var quantity = ParseFloat(inputs[x+1).value);
var itemName = computer[x/2].split(",")[1];
var itemPrice = parseFloat(computer[x/2].split(",")[2])
var itemTotal = parseFloat(quantity*itemPrice);
totalPrice += itemTotal;
basketTable += "<tr><td>"+itemName+"</td><td>"+quantity+"</td><td>$"+itemPrice+"</td><td>$"+itemTotal+"</td></tr>";
}
}
basketTable +=" <tr><td> colspan='3'><b>Total:</b></td><td><b>$"+totalPrice+"</b></td></tr></tbody><table>";
rightsSide.innerHTML = basketTable;
}
update quantity to 1 when item is checked
function updateQty(id) {
var targetRow = document.getElementById(id);
var qtyBox = targetRow.getElementsByTagName('input')[1];
if (qtyBox.value == 0) {
qtyBox.value = 1;
} else {
qtyBox.value = 0;
}
}
Here's the HTML as requested
<form name="myForm" action="index.html" method="post">
<div id="table_container_left">
<button onclick="check();">Select All</button>
<button onclick="uncheck();">Unselect All</button>
<button onclick="addItems();">Add Items</button>
<table>
<thead>
<th><u>Item Code</u></th>
<th><u>Item</u></th>
<th><u>Qty</u></th>
<th><u>Price</u></th>
</thead>
<tbody>
<script type="text/javascript">
for(x=0; x<=computer.length-1; x++) {
document.write("<tr id='"+x+"'><td><label><input type='checkbox' name='item' value='"+x+"' onclick='updateQty('"+x+"');'/> "+computer[x].split(",")[0]+"</label></td><td>"+computer[x].split (",")[1]+"</td><td> <input name='qty' id='qty' type='textbox' value='0' onchange='qtychange ('"+x+"');'/></td><td>$"+computer[x].split(",")[2]+"</td></tr>");
}
</script>
</tbody>
</table>
</div>
<div id="table_container_right">
<table id="shoppingBasket">
<input name='selectAll' type='button' value='Select All' onclick="itemSelected();"/>
<input name='clearAll' type='button' value='Clear All' onclick=""/>
<input name='removeItem(s)' type='button' value='Remove Item(s)' />
<input name='sortItemCode' type='button' value='Sort by Item Code' disabled='disabled' />
<input name='sortPrice' type='button' value='Sort by Price' disabled='disabled' />
</tbody>
</table>
</div>
</div>
</form>
Your JS syntax is way off, this is what it should look like
function addItems(field) {
for (i = 0; i <= field.length-1; i++)
{
if (field[i].checked == true)
{
if (computer[i]!=null) {
selected[i] = computer[i];
}
}
}
}
Half of your if statements are missing parentheses, that's some basic wrongfulness.
I don't know what and where should any of the variables be, but here is my best shot:
function addItems(field) {
var i;
for (i = 0; i < field.length; i++) {
if (field[i].checked === true) {
if (computer[i] !== null) {
selected[i] = computer[i];
}
}
}
}
You are using i = 0 rather than var i = 0, which will introduce a global variable. This could be a problem if you're writing similar code elsewhere.
Your if-statements are not statements at all. They look like pseudo-code. You're also comparing with = rather than ==, which will cause an assignment rather than a condition, even if you fix up your syntax.
You are not properly indenting your code, which will make you much more prone to introduce new errors.
These are the general issues I notice immediately. Of course, heaps of things could be wrong with this code. fields might not be an array, computer and selected might not match the size of fields, etc.
If you have any specific problem, please describe that, and we may be able to address it.