Javascript won't read from "select" in a form - javascript

I am trying to get my code to read a value based off the selected item from a select list in my form, but it says it's undefined. When I simply give the function a value and tell it to return the value, it reads, but won't take values from the form.
The following is the code I'm using
for the form (in html):
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost()">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
and the javascript reads
function calculateCost()
{
var orderPrice = getItemPrice();
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
function getItemPrice()
{
var itemPrice = 0;
var theForm = document.forms["orderForm"];
var selectedItem = theForm.elements["item"];
itemPrice = item_prices[selectedItem.value];
return itemPrice;
}

HTMLCollection.item() is method of HTML select element Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
theForm.elements["item"] will return function expression of the HTMLCollection.item and which is causing the undefined value as theForm.elements["item"] does not have property value
Either pass this in inline-event or use other id and name attribute to select element than item
function calculateCost(elem) {
var orderPrice = getItemPrice(elem.value);
document.getElementById('totalPrice').innerHTML = orderPrice;
}
var item_prices = [];
item_prices["None"] = 0;
item_prices["Candlestick"] = 10;
item_prices["Bowl"] = 10;
item_prices["Burl_Bowl"] = 20;
item_prices["Clock"] = 15;
item_prices["Vase"] = 5;
item_prices["Pen"] = 2;
item_prices["Top"] = 1;
function getItemPrice(val) {
var itemPrice = 0;
itemPrice = item_prices[val];
return itemPrice;
}
<form action="" id="orderForm" name="orderForm" onsubmit="return false;">
<select id="item" name='item' onchange="calculateCost(this)">
<option value="None">Select Item</option>
<option value="Candlestick">Candlestick ($10)</option>
<option value="Bowl">Bowl ($10)</option>
<option value="Burl_Bowl">Burl Bowl ($20)</option>
<option value="Clock">Clock ($15)</option>
<option value="Vase">Vase ($5)</option>
<option value="Pen">Pen ($2)</option>
<option value="Top">Spinning Top ($1)</option>
</select>
<div id="totalPrice">hallo</div>
</form>
Edit: Or just use getElementById => var selectedItem = document.getElementById('item'); to access the select element.Fiddle here

This entire operation could be simplified a bit as well.
var item_prices= new Array();
item_prices["None"]=0;
item_prices["Candlestick"]=10;
item_prices["Bowl"]=10;
item_prices["Burl_Bowl"]=20;
item_prices["Clock"]=15;
item_prices["Vase"]=5;
item_prices["Pen"]=2;
item_prices["Top"]=1;
EDIT, you should use an object here if you want to be correct.
item_prices = {
None: 0,
Candlestick: 10
};
// etc...
document.getElementById('item').addEventListener('change', function (event) {
document.getElementById('totalPrice').innerHTML = item_prices[event.target.value];
});

Related

Some of the methods are working but not all of them

I am new to Js and I am having trouble with the code. The problem is that when I multiply different methods together the program does not work. However, some of the methods are are working even though they are kind of identical. The other problem is that I have to change the first selection first and then the other to get the total I need. I want to get a total that changes whenever I choose any selection from the drop box regardless of ordering. I know I am foreseeing a mistake here or simply cant understand. Please feel free to point out my mistakes and help me better my code because I know its more complicated than it should be. Thank you for your help.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/scriptt.js "></script>
</head>
<body onload="hideTotal()">
<form method="POST" class="device"/>
<center class="all" >
<div class= "data">
<label class="req">Select The Device</label>
<select class="mydevice" id= "selectDevice" onChange="calculateTotal()">
<option> None </option>
<option value="100" id='lg'> LG X CHARGE </option>
<option value="129"> ZTE MAX XL </option>
<option value="123"> LG DYNASTY </option>
<option value="400"> LG TRIBUTE </option>
</select>
<label for="For" class="req"> For </label>
<select class="mydevice" id="port" onChange="calculateTotal()">
<option id= 'none' value='none'> None </option>
<option id='port' value="129" >Port-In</option>
<option class="upgrade">Upgrade</option>
<option class="newAct">New Activation</option>
</select>
<label for="Plan" class="req">Plan</label>
<select class="plan" id='plan' onChange="calculatedToral()">
<option>None</option>
<option value="35" >$35 plan</option>
<option value="50">$50 plan</option>
<option value="60">$60 plan</option>
</select>
<div class="access" >
<label for="phoneInsurance"> Phone Insurance </label>
<select class="myinsurance" id='insurance' onChange="calculatedToral()">
<option>None</option>
<option value="7">Yes</option>
</select>
<label for="phoneCase"> Phone Case </label>
<select class="mycases" id='case' onChange="calculatedToral()">
<option>None</option>
<option value="25">Regular</option>
<option value="35">Wallet</option>
</select>
<label for="screenProtector"> Screen Protector </label>
<select class="myscreen" id='screen' onChange="calculatedToral()">
<option value="15">Yes</option>
<option>No</option>
</select>
<center>
<div id="total"></div>
Js
var device_prices = new Array();
device_prices["100"]=100;
device_prices["129"]=129;
device_prices["123"]=123;
device_prices["400"]=400;
var port_prices = new Array();
port_prices["129"]=0.097;
var plan_prices = new Array();
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
var insurance_prices = new Array();
inusrance_prices["7"]=7;
var phone_case = new Array();
phone_case["25"] = 25;
phone_case["30"] = 30;
var screen_protector = new Array();
screen_protector["15"] = 15;
function getDevicePrice() {
var deviceSelect = document.getElementById('selectDevice');
//alert(device_prices[deviceSelect.value]);
return device_prices[deviceSelect.value];
}
function getPortPrice() {
var portSelect = document.getElementById('port');
return port_prices[portSelect.value];
}
function getPlanPrice() {
var planSelected = document.getElementById('plan');
return plan_prices[planSelected.value];
}
function getInsurancePrice() {
var insurancee = document.getElementById('insurance');
return insurance_prices[insurancee.value];
}
function getCasePrice() {
var caseSelect = document.getElementById('case');
return phone_case[caseSelect.value];
}
function getScreenPrice() {
var screenSelect = document.getElementById('screen');
return screen_protector[screenSelect.value];
}
function calculateTotal() {
var total = getDevicePrice()*getPlanPrice()*getPortPrice();
total = total.toFixed(2);
var totalEl = document.getElementById('total');
document.getElementById('total').innerHTML = "Your Total is: $" + total;
totalEl.style.display = 'block';
}
function hideTotal() {
var totalEl = document.getElementById('total');
totalEl.style.display = 'none';
}
spelling
var insurance_prices = new Array();
inusrance_prices["7"]=7;
funtion or method not define
calculatedToral
var device_prices = new Array();
device_prices["100"]=100;
device_prices["129"]=129;
device_prices["123"]=123;
device_prices["400"]=400;
var port_prices = new Array();
port_prices["129"]=0.097;
var plan_prices = new Array();
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
var insurance_prices = new Array();
insurance_prices["7"]=7;
var phone_case = new Array();
phone_case["25"] = 25;
phone_case["30"] = 30;
var screen_protector = new Array();
screen_protector["15"] = 15;
function getDevicePrice() {
var deviceSelect = document.getElementById('selectDevice');
//alert(device_prices[deviceSelect.value]);
alert("1");
return device_prices[deviceSelect.value];
}
function getPortPrice() {
var portSelect = document.getElementById('port');
alert("2")
return port_prices[portSelect.value];
}
function getPlanPrice() {
var planSelected = document.getElementById('plan');
alert("3")
return plan_prices[planSelected.value];
}
function getInsurancePrice() {
alert("4")
var insurancee = document.getElementById('insurance');
return insurance_prices[insurancee.value];
}
function getCasePrice() {
alert("5")
var caseSelect = document.getElementById('case');
return phone_case[caseSelect.value];
}
function getScreenPrice() {
alert("6")
var screenSelect = document.getElementById('screen');
return screen_protector[screenSelect.value];
}
function calculateTotal() {
alert("7")
var total = getDevicePrice()*getPlanPrice()*getPortPrice();
total = total.toFixed(2);
var totalEl = document.getElementById('total');
document.getElementById('total').innerHTML = "Your Total is: $" + total;
totalEl.style.display = 'block';
}
function calculatedToral()
{
alert("8")
}
function hideTotal() {
alert("9")
var totalEl = document.getElementById('total');
totalEl.style.display = 'none';
}
i was corrected your all function or method of your JavaScript and all are working (i was add alert() for function check). check calculation errors yourself
The JS calls in your HTML tags have wrong names.
Eg: You've calculatedToral() instead of calculatedTotal()in the following:
<select class="myinsurance" id='insurance' onChange="calculatedToral()">
<option>None</option>
<option value="7">Yes</option>
</select>
Check all the names properly.
Also, some footnotes since you're a beginner:
Try to avoid inline scripting. (look at this) I.e., as far as possible, don't mix the javascript event calls (like onChange(), onClick()) in the HTML tags. It'll make the code difficult to read and change in future.
Instead of inline scripting, try to put all Javascript either within the <script> tags (at end of page is usually better). Use .getElementsByClass() for wider control and .getElementById() for granular control of events.
Also, since you're using jQuery, include the <script> calling the jQuery CDN at the end, just before </body>

Javascript arrays with html select list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a select list that goes from 0-4 and when selecting a number, it will output the name in the array. Instead of when selecting the number 1 and getting the ouput "Adam", i just get "Ron" for every number.
friends = new Array('Alex', 'Adam', 'Jake', 'Cydney', 'Ron');
document.getElementById('go').onclick = function() {
var nameSelected = document.getElementById('index').value;
oneArrayValue = friends[0];
oneArrayValue = friends[1];
oneArrayValue = friends[2];
oneArrayValue = friends[3];
oneArrayValue = friends[4];
document.getElementById('result').value = nameSelected;
};
<body>
<select id='number' name=''>
<option value = '0'>0</option>
<option value = '1'>1</option>
<option value = '2'>2</option>
<option value = '3'>3</option>
<option value = '4'>4</option>
<option value = '5'>5</option>
</select>
<button id='go' class=''>GO</button>
<input id='result' name='' value='' class=''>
<script src='js/javascript 07.js'></script>
</body>
friends = new Array('Alex','Adam','Jake','Cydney','Ron');
/*
you can even declare using the following:
friends = ['Alex','Adam','Jake','Cydney','Ron']; // <- this
*/
document.getElementById('go').onclick = function () {
var nameSelected = document.getElementById('number').value;
// getting the name from the index selected
oneArrayValue = friends[nameSelected];
document.getElementById('result').value = oneArrayValue;
};
<select id = 'number' name = ''>
<option value = '0'>0</option>
<option value = '1'>1</option>
<option value = '2'>2</option>
<option value = '3'>3</option>
<option value = '4'>4</option>
<option value = '5'>5</option>
</select>
<button id = 'go' class = ''>GO</button>
<input id = 'result' name = '' value = '' class = ''>
Your code is not coded as the you expect result, see working code below
friends = new Array('Alex','Adam','Jake','Cydney','Ron');
document.getElementById('go').onclick = function () {
var nameSelected = document.getElementById('index').value;
oneArrayValue = friends[nameSelected];
document.getElementById('result').value = oneArrayValue;
};
<input type="text" id="result">
<select id="index">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<input type="button" value="go" id="go" />
I think you're trying to achieve something like this:
var friends = ['Alex', 'Adam', 'Jake', 'Cydney', 'Ron'];
document.getElementById('go').addEventListener('click', function() {
var idx = parseInt(document.getElementById('index').value);
document.getElementById('result').innerHTML = friends[idx];
});
<select id="index">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="button" value="Go" id="go" />
<div id="result"></div>
That's because you keep overwriting oneArrayValue so that only the last assignment sticks. Not to mention that oneArrayValue doesn't even seem to be declared in your code.
This is actually much simpler than what you are doing:
// Here's the sligtly simpler "Array Literal" syntax for making an array
var friends = ['Alex','Adam','Jake','Cydney','Ron'];
// Use the modern, standards-based approach to event binding, not `onclick`, etc.
document.getElementById('go').addEventListener("click", function () {
// Get the value out of the select
var nameSelected = document.getElementById('number').value;
// Set the content of the output area to the corresponding index element:
document.getElementById('result').textContent = friends[nameSelected];
});
<select id = 'number' name = ''>
<option value = '0'>0</option>
<option value = '1'>1</option>
<option value = '2'>2</option>
<option value = '3'>3</option>
<option value = '4'>4</option>
<option value = '5'>5</option>
</select>
<button id = 'go' class = ''>GO</button>
<!-- If you are just outputting a value, don't use a form element. -->
<span id="result"></span>

get two option id in one function

I want calculate a sum with the selected ID so I get all ID in different var then call them by find() my code is not work :
$(window).load(function(){
function doStuff() {
var uone= $("#ud").children(":selected").attr("id") == 'a';
var utwo= $("#ud").children(":selected").attr("id") == 'b';
var uthree= $("#ud").children(":selected").attr("id") == 'c';
var bone= $("#bt").children(":selected").attr("id") == 'd';
var btwo= $("#bt").children(":selected").attr("id") == 'e';
var getValue;
if ($(uone).find(bone)) {
getvalue = 75;
}
if ($(uone).find(btwo)) {
getvalue = 70;
}
if ($(utwo).find(bone)) {
getvalue = 81;
}
if ($(uthree).find(bone)) {
getvalue = 79;
}
var shw = $('#inputamount').val();
var total = getvalue * shw ;
$(".totalop").html(total);
}
$("#inputamount").on('keyup', doStuff);
$("#ud").on('change', doStuff);
$("#bt").on('change', doStuff);
});
<select name="sucompn" id="ud">
<option id="a">a</option>
<option id="b">b</option>
<option id="c">c</option>
</select>
<select name="ducompn" id="bt">
<option id="d">d</option>
<option id="e">e</option>
</select>
<input autocomplete="off" name="inputamount" id="inputamount" value="" type="text">
<span id="ttotal"></span>
Actually I want to create a result users input and select based. Something like when user select 'a' and 'd' then 'input=1' so result come = 75 .It will change when user change any option or input .
You should use value attributes:
<select name="sucompn" id="ud">
<option value="1" id="a">a</option>
<option value="2" id="b">b</option>
<option value="3" id="c">c</option>
</select>
And then access it via jQuery:
var gvalue = $('#ud').val();
If you'd like to overwrite it with the selected value of the other select element, you could simply do the same for the other one and overwrite it:
var otherValue = $('#sd').val();
if (otherValue) gvalue = otherValue

How to add option value to url

I am working on a calculator tax.
I wanted to receive the selected values of that was redirected to the url value, so that I could for example send someone a link to the values that I have chosen, so it does not have to set them again only to be had when you start link.
http://kalkulator.atrocki.pl/calculator/index.html
<div class="styled-select">
<h1>Vat</h1>
<select id="vat">
<option value='0'>0%</option>
<option value='0.08'>8%</option>
<option value='0.23'>23%</option>
<option value="other">Add another VAT value..</option>
</select>
<input type="text" class="vatInput" id="vatInputId" placeholder="Vat w %">
</div>
<div class="styled-select">
<h1>tax 2</h1>
<select id="tax">
<option value="0">0%</option>
<option value='0.18'>18%</option>
<option value='0.19'>19%</option>
<option value='0.32'>32%</option>
<option value="other">Add another TAX value..</option>
</select>
JavaScript has no built in function for handling query string parameters.
It's very easy to do this with whatever back-end language you are using in your server.
If you absolutely must do this with Javascript, check this question:
How to get the value from the GET parameters?
You can parse the query string into a nice object, then look for the key value pair you want.
function parseQuery() {
var query = {};
var indexOfQ = window.location.href.indexOf("?");
if (indexOfQ < 0)
return null;
var a = window.location.href.substr(indexOfQ + 1).split('&');
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
return query;
}
function loadQueryString() {
var query = parseQuery();
if (!query) return;
if (typeof query['val'] !== 'undefined') {
var newSelection = $("<option>", { value: query['val'], text: (Math.floor(parseFloat(query['val']) * 100)) + '%'});
$('select').prepend(newSelection);
}
}
loadQueryString();

Switch based url redirection

I'm having a problem get this piece of code to work:
$(document).ready(function(){
$('#ButtonAluguel').click(function(){
{
var id = $(this).attr('name');
var str = "";
$("option:selected").each(function () {
switch(id=='Trololo'){
case true:
var option = $(this);
str += '?tid_1[]='+ option.attr('value');
break;
case false:
var option = $(this);
str += '?tid[]='+ option.attr('value');break;
}
});
window.location = "localhost/aluguel"+ str;
}});
});
I need it to keep adding stuff to "str" based on the name of a multiple select, identified above as id. Long story short, if the name of the select is "Trololo", id adds tid_1[], if not, it adds tid[] to the str. Any help is appreciated.
Edit:
The multiple select code is as follows(Forgot to put it in the first place, the question doesn't make much sense without it)
<form >
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar" >
</form>
To explain it more clearly, the user must fill the form and choose between the options, so when he clicks the "ButtonAluguel", every option from the select "SelectTipoAluguel" is added to the URL as tid[] and the ones from "SelectBairroAluguel" is added to the URL as tid_1[]
Code edited to reference updated question and OP's comments.
$(document).ready(function() {
var id;
var str = "";
$('#ButtonAluguel').click(function() {
var option = [];
$('select option:selected').each(function(i, selected) {
id = $(this).parent().attr('name');
option[i] = $(selected).val();
if (id == 'Trololo') {
str += '?tid_1[]=' + option[i];
} else {
str += '?tid[]=' + option[i];
}
});
var url = "localhost/aluguel" + str;
console.log(url);
//window.location = "localhost/aluguel" + str;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="SelectTipoAluguel" multiple="true" data-placeholder="Tipo de Imóvel" style="width:200px;">
<option value="1">Aasdasdasd</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<select name="Trololo" class="SelectBairroAluguel" id="trololo" multiple="true" data-placeholder="Bairro" style="width:200px;">
<option value="1">Aadasd</option>
<option value="2">Basda</option>
<option value="3">Casda</option>
<option value="4">Dasda</option>
</select>
<input class="ButtonSubmitHome" id="ButtonAluguel" value="Pesquisar">

Categories