Calculating the total of an online order form using javascript - javascript

I'm working on a basic order form and I would like to see if I can build it from stratch.
I have a form which is made up of a table with 12 items listed and text input fields for item quantity. What I would like to do is have the code run through the form to check for any quantities that have been entered, then relate these values to the prices in an array.
So far I have the array:
var juicePrice = new Array();
juicePrice["citrusZing"]=20.00;
juicePrice["strawberrySmooth"]=22.00;
juicePrice["carrotSpin"]=21.50;
juicePrice["Tropical"]=20.75;
...
and a way to run through the form:
calculateTotal()
{
var juiceForm = document.forms["juiceform"];
//Get a reference to the juice the user Chooses name=selectedJuiceQty":
var selectedJuiceQty = juiceForm.elements["selectedJuiceQty"];
for(var i = 0; i < selectedJuiceQty.length; i++);
but I'm not quite sure how to connect the information from the form to calculate the totals. Can anyone point me in the right direction? Is it something like this?
for(var i = 0; i < selectedJuiceQty.length; i++){
var juiceTotal = 0;
if(selectedJuiceQty[i]>0) {
juiceTotal += juicePrice[selectedJuiceQty[i].value]*selectedJuiceQty;
//If we get a match then we break out of this loop
break;
}
return total;
}
Is it possible to use the same name tag for each field or should I just use citrusZingQty = parseInt(document.getElementById("citrusZing").value); for each item? Then I would have to list all of the items, which doesn't seem a very elegant way. What would happen if multiple items are selected?
Any help anyone can give to point me in the right direction would be great.

So you can do what you want. Michael pointed this out in the comments but it may have been overlooked.
var myPrices = new Object();
myPrices['eggs'] = 1.50;
myPrices['bread'] = 1.00;
// ...
Then you can loop through your form fields and check against your 'myPrices' object.
EDIT
To answer your question in the comments - I would not use the same name for all of my input fields. It does make looping through the form easier perhaps. However, using the id/class of the input tag is not a nice solution in my opinion. HTML id/class are there for CSS/Javascript manipulation and using it to identify which fruit the input represents will not be apparent to other developers working on the project (I realize this may be a small project for you but it's best not to start any bad habits). I would name each input after the juice/drink it represents.

Related

Netsuite SSv1 Replace Filters of Saved Search with Filters From Another Saved Search

I need to replace the filters of every search I loop through (selectedSearchId variable in loop) with the filters of a generic search (searchGen). I am successfully looping through my array and getting the IDs, so I just need to apply the filters. Any help?
var searchGen = nlapiLoadSearch('item','customsearch_ca_export_detail_search__38'); //loads a generic search
//TODO: get filters from searchGen
for (var i = 0; i<selectedMarketsArray.length; i++){
//TODO: replace filters of each selectedSearchId with filters from searchGen
var selectedSearchId = marketplaces[selectedMarketsArray[i]].searchId;
nlapiLogExecution('DEBUG','selectedSearchId',selectedSearchId);
}
Side note, I spent a couple weeks going back and forth with Netsuite reps with this same issue in SSv2 to only find that it was a bug that needs to be fixed. This is why I am re-writing in v1.
I am still new to suitescript (especially SSv1) so any help is appreciated.
Thanks!
Jesse
I did end up figuring this out, if anyone is interested. I use the "getFilters()" and "setFilters()" functions as such:
var searchGen = nlapiLoadSearch('item','customsearch_ca_export_detail_search__38'); //loads a generic search
searchGenFilters = searchGen.getFilters();
nlapiLogExecution('DEBUG','searchGenFilters',searchGenFilters);
if(updateSearches){
for (var i = 0; i<selectedMarketsArray.length; i++){
//TODO: replace filters of each selectedSearchId with filters from searchGen
var selectedSearchId = marketplaces[selectedMarketsArray[i]].searchId;
nlapiLogExecution('DEBUG','selectedSearchId',selectedSearchId);
var selectedSearch = nlapiLoadSearch('item',selectedSearchId);
selectedSearch.setFilters(searchGenFilters);
nlapiLogExecution('DEBUG','Selected Search Filter',selectedSearch.getFilters());
selectedSearch.saveSearch();
}
}
Hope this is helpful!
Jesse

javascript if statement syntax (need help)

I've looked through the prior questions but do not see an answer that I can understand (they are all more complicated than mine).
I'm bootstrapping some javascript using old manuals and my experiences using a scripting language back 15 years ago.
By modifying a tutorial file I have this code and it works fine
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
total_current_draw.value = oemdc1 + oemdc2 + oemdc3
But I need to add this code so that if the user clicks a radio button (include_prism_draw) they get a different total.
if (oemdc4 == 1)
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
else
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
But I get the added value (prism_cd) in my calculation regardless of the radio button values (a "1" or a "0"). Even if neither button is clicked I still get the added value.
So I think I need some braces or parentheses or something.
I have the var prism_cd declared at the top of the doc and it is inserted into a results field so it is working in that sense.
Any help is much appreciated.
(Okay, found the edit link, they should make it more prominent).
I cut/pasted the code from #Adam and still get the prism_cd regardless of the state of the buttons. (prism_cd is a number I set as a var and it shows up accurately but even when I don't want it.)
the button code is below. Maybe there is a simple mistake
Include PRISM 1.5 mA current draw in calculation?
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="1" /> Yes
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="0" /> No
To answer the other question about the vars, they are from popups the user manipulates, the script adds the values from the popups and does so accurately until I add the yes/no code with the buttons.
If the user wants to add the prism current draw (prism_cd) they click yes and it is to be added but as I say it is getting added whenever the code is in the script. At this point I do not have either button set to be checked.
The rest of script works accurately as I can test with the spreadsheet I am porting it from.
I still have more things to work through but they are mostly based on this type of "if/else set a var" logic so once I get this working hopefully I should be good to go.
I very much appreciate the replies.
M./
I'm not certain what your problem is. But, the best practice for if..else syntax is to put both blocks in braces.
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
if (oemdc4 === 1){
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
} else {
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
}
Look at this question: Get Radio Button Value with Javascript
You cannot get the value of a number of associated radio-buttons by just doing
document.getElementById(ID).value;
also look at this question, why you should not give the same id to multiple HTML elements: Why is it a bad thing to have multiple HTML elements with the same id attribute?
Now a possible simple solution for you problem (according to solution from first link):
You could write a function, which returns the value of your two radio-buttons:
function getPrismDrawValue()
{
// predefined result, if no radio button is checked.
// in this case result will be 0 -> "No"
var result = 0;
// get a list of all HTML-elements with the name 'include_prism_draw'
var radios = document.getElementsByName('include_prism_draw');
// loop through all this elements and check if one of them is checked
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
// get the value of the checked radio button
result = parseInt(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
return result;
}
Now your variable oemdc4 should be declared like this:
var oemdc4 = getPrismDrawValue();
EDIT to answer new question:
now your problem is here:
var oemdc4 = parseInt(document.getElementById("prism_draw").value);
if you pass 1.5 to parseInt()-function it will return 1.
use function parseFloat() instead to get your expected result.
var oemdc4 = parseFloat(document.getElementById("prism_draw").value);

Run 4 individual form submit functions from a single button click using Javascript

I am currently attempting to make a page that would allow for users to search multiple knowledge bases from a single field.
Currently, I have been able to build this tool out so that clicking the corresponding button will search the designated tool, but I am trying to get a single button to search all 4.
Where I am stuck is the function tied to the All button. When I click it, it only appears to be running the last function in the group rather than opening 4 browser tabs with all 4 results.
I have attached a JSFiddle, in case my explanation is poor.
Note: The page is not pretty as I am trying to get it working before I add any CSS. I really just need JS advice. I am still somewhat of a novice with JS, so if anyone can provide a fairly simple solution, that would be most ideal.
Super Search Fiddle:
This is just to give an idea on how it might work depending on you needs. Ill assume that all the searches return a boolean value. So the code would go something like this:
function doAll() {
var msg = ["google","payroll","inquira","sdfc"]
var retvalue = [googleSearch(),payrollSearch(),inquiraSearch(),sfdcSearch()];
for (var i = 0; i < retvalue.length; i++){
if(retvalue[i] == false){
console.log(msg[i]+" search returned false");
}
}
}
It will do all the searches first and after it finishes, it will give out which searches failed, but you can change that functionality according to your needs.
Hope it helps
Update/Alternative(Almost same code):
function doAll() {
var msg = ["google","payroll","inquira","sdfc"]
var retvalue1 = googleSearch();
var retvalue2 = payrollSearch();
var retvalue3 = inquiraSearch();
var retvalue4 = sfdcSearch();
var retvalue = [retvalue1,retvalue2,retvalue3,retvalue4];
//var retvalue = [googleSearch(),payrollSearch(),inquiraSearch(),sfdcSearch()];
for (var i = 0; i < retvalue.length; i++){
if(retvalue[i] == false){
console.log(msg[i]+" search returned false");
}
}
}

Javascript not checking whether a checkbox was selected or not

I'm trying to build a quiz with multiple choice questions, one of which has multiple correct answers. So I'm trying to check which checkboxes in my questions have been selected by a student in order to give the right feedback. my code is:
for(var i = 0; i< input1.length; i++)
{
if(input1[0].checked && input1[1].checked)
{
submit_answer.onclick = showFeedback1;
}
else
{
submit_answer.onclick = false1;
}
}
It never takes the first if, even if I select those two only. No matter what I put in the if statement, it only takes the else.
and this is just a part of my .js
var quiz = document.getElementById('quiz');
var questions = quiz.getElementsByTagName('p');
input1 = questions[0].getElementsByTagName('input');
var submit_answer = document.getElementById('submit_answers'); // this is the submit button
I cannot make proper assumption of what you are trying to do.
FIRST PROBLEM
Your for loop is incrementing on 1, so on the each next iteration it is comparing using same previously used value.
SECOND PROBLEM
Your structure is horrible, your script fetches up all the input elements inside every p. You should properly organize your element in groups and then match whether or not they are checked.

Can I make an array list adaptable in the HTML?

I am currently creating a spelling game where you drag and drop letters onto the corresponding words. At the moment I have a list of words in the array list that generate a grid dynamically.
The problem is when new words need to be added to the game, they have to be added through the HTML as that side of the office are not familiar with JavaScript/JQuery and not willing to learn.
What would be the best approach to this?
Is there a way that they can add things to the array in the script through HTML?
This is the script I have at the moment...
var listOfWords = new Array();
listOfWords['mat'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['cat'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['dog'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['pit'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['pot'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['fog'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['log'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['pan'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['can'] = 'http://www.wav-sounds.com/cartoon/bugsbunny1.wav';
listOfWords['man'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
listOfWords['pin'] = 'http://www.wav-sounds.com/cartoon/daffyduck1.wav';
listOfWords['gag'] = 'http://www.wav-sounds.com/cartoon/porkypig1.wav';
Then i have script that takes the array list items and creates a grid dynamically.
var rndWord = null;
var guesses = new Array();
var shuffledWords = keys(listOfWords).slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 12);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < Object.keys(shuffledWords).length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
// IF FIREFOX USE cell.textContent = word[j]; INSTEAD
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
Thanks.
You could add a hidden object in the DOM:
<ul style="display:none;" id="wordlist">
<li data-word="mat" data-audio="http://www.wav-sounds.com/cartoon/daffyduck1.wav"></li>
<li data-word="cat" data-audio="http://www.wav-sounds.com/cartoon/porkypig1.wav"></li>
<!-- data-xxx can be read with JS, node["data-xxx"] or jQuery: node.data("xxx") -->
</ul>
You can then iterate over all elements using either jQuery or node.children:
var listOfWords = {};
var ul = document.getElementById("wordlist");
var i;
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = ul.children[i].getAttribute("data-audio");
}
console.log(listOfWords);
Demo
Hint: Please note that you're listOfWords is actually an object and not an array. An array supports only integer indexes and should be filled with .push.
Edit:
Please have a look at Tomas' answer. While this approach will definitely make it possible for your co-workers to add or change elements without actually writing JavaScript it's simply too much effort. Either way they will ask you questions how to add elements to the list. See also Dennis' comment.
Although Zeta's answer probably gives you an idea of how to do this, I'd say it doesn't really solve your actual problem. As you said yourself:
The problem is when new words need to be added to the game, they have to be added through the HTML as that side of the office are not familiar with JavaScript/JQuery and not willing to learn.
To me, this points to more fundamental difficulties in your team than just how to specify the dictionary in HTML; you seem to be working with people that are actively working against you. I see a couple of different ways to resolve this situation - some of them more provocative than others, while some requires more work on your part than others. You'll have to judge yourself which of them, if any, are applicable to you...
Force them to learn. It's not like they have to be jQuery masters to add a word to the dictionary - they just have to learn a specific syntax which you can teach them.
They are apparently capable of specifying the dictionary in HTML
markup, and can thus be assumed comfortable with some form of syntax.
I'd say your syntax for the dictionary is way simpler than what Zeta
suggested, so if they can learn one you should be able to teach them
the other.
If you need to, step up the company ladder and talk to their manager. They won't like it, but your development process probably will.
Do their work. Consider simplifying the whole process by reorganizing who does what in the development process. If the team responsible for the dictionary cannot add the actual key/value pairs to the code, maybe they can just ask you to do it for them? An email to a dedicated address, which you check a couple of times a day and add the corresponding stuff to the code would be one way to solve it.
Write them an admin system. This includes a lot of work on your part, both to create and support the feature - but it might earn you some goodwill in other matters. If the application should support later addition of new words, why not write a simple service that lets them add words to the dictionary from a web form? You store everything on the server, and load the dictionary with AJAX when you need it. The other team doesn't have to learn anything - they just enter the information in the form and click "send", and it's fixed.
My point is that if you're working with a team that doesn't want to meet half-way in a simple matter as this, you have bigger problems than just how to get these words into the list. I would focus on resolving the real problem here.
In short - No, you can't do it using only HTML
You need to write simple script which will generate js file containing array and you can include this file to your HTML file.
Basicly script may looks like this:
<?php
if (isset($_POST['code']) && isset($_POST['path'])){
$string = "listOfWords['" . $_POST['code'] . "'] = '" . $_POST['path'] . "';"
$fh = fopen('listofwords.js', 'a');
fwrite($fh, $string);
fclose($fh);
}
?>
<form action="" method="post">
<input type="text" name="code" />
<input type="text" name="path" />
<input type="submit" value="Add code" />
</form>
Of course this script is only for adding, if you need to edit/delete records you should rewrite script according your needs

Categories