Can't get if/else function to work with radio buttons - javascript

I have looked all over this site (and Google) for an answer to my problem but I can only seem to find bits and pieces, nothing specific.
I am primarily playing around with JavaScript and HTML but am not trying to use jquery right now.
So, with that said, this is what I'm trying to do: I would like the user to enter two numbers, select an operation (add, subtract, multiply, divide) out of a list of four radio buttons, and then click a button which is linked to a function that does the math and then presents it in a text box on the page. How would I do this using only HTML and JavaScript? I have gotten everything to work up until the point I add the radio buttons.
The code is as follows:
<script>
function operationForm (form) {
var x = document.operationForm.getElementById("numberOne");
var y = document.operationForm.getElementById("numberTwo");
var operation;
var answer;
if (document.operationForm.addSelect.checked === true) {
answer = x + y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.subtractSelect.checked === true) {
answer = x - y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.multiplySelect.checked === true) {
answer = x * y;
document.operationForm.answerBox.value = answer;
} else(document.operationForm.divideSelect.checked === true) {
answer = x / y;
document.operationForm.answerBox.value = answer;
}
}
</script>
<h1>Let's calculate!</h1>
<form name="operationForm">
<p>
<label>Enter two numbers, select an operation, and then click the button below.
<p>
<label>Number One:
<input type="text" name='numbers' id="numberOne">
<br>
<br>Number Two:
<input type="text" name='numbers' id="numberTwo">
<p>
<input type="radio" name="operations" id="addSelect" value=''>Add
<input type="radio" name="operations" id="subtractSelect" value=''>Subtract
<input type="radio" name="operations" id="multiplySelect" value=''>Multiply
<input type="radio" name="operations" id="divideSelect" value=''>Divide
<label>
<p>
<input type="button" value=" Calculate " onClick='operationForm(form);'>
<p>
<label>Your answer is:
<input type="text" name="answerBox">
If anyone has any fixes or can point me in the right direction of the correct syntax for handling radio buttons, functions linking to them, and onClick events linking to those functions, it would be extremely appreciated.

Consider replacing the <input type="button" value=" Calculate " onClick='operationForm(form);'> with <input type="button" value=" Calculate " onClick='operationForm();'>. Next change the function operationForm to accept no parameters. Then add id to your input answer box. Next for each if statement in the function use the elementById function to get the radios and the answerBox. For example, the first if should be
if (document.getElementById("addSelect").checked) {
answer = x + y;
document.getElementById("answerBox").value = answer;
}

This works:
JavaScript:
<script type="text/javascript">
function operationForm(){
var form = document.forms['operation_form'];
var x = form['numberOne'].value*1;
var y = form['numberTwo'].value*1;
var operation = null;
var answer = null;
if (form['addSelect'].checked == true) {
answer = x + y;
} else if (form['subtractSelect'].checked == true) {
answer = x - y;
} else if (form['multiplySelect'].checked == true) {
answer = x * y;
} else if (form['divideSelect'].checked == true) {
answer = x / y;
}
form['answerBox'].value = answer;
}
</script>
HTML:
<form name="operation_form">
<label>Enter two numbers, select an operation, and then click the button below.</label>
<br/>
<label>Number One:</label><input type="number" name='numberOne' />
<br/>
<br/>Number Two:</label><input type="number" name='numberTwo' />
<br/>
<input type="radio" name="operations" id="addSelect" value='' />Add
<input type="radio" name="operations" id="subtractSelect" value='' />Subtract
<input type="radio" name="operations" id="multiplySelect" value='' />Multiply
<input type="radio" name="operations" id="divideSelect" value='' />Divide
<br/>
<input type="button" value=" Calculate " onclick="operationForm();" />
<br/>
<label>Your answer is:</label><input type="text" name="answerBox">
</form>
Fixes between this and your example:
There are a ton of things wrong with the code you provided. I will update this answer shortly with as many as I can remember.
Update:
Please remember this is meant to be helpful and not punishing. So keep in mind that while listening to the attached feedback, I want you to learn this stuff.
Notes on your HTML:
1.) The biggest problem is none of the <label> elements have closing</label> tags.
Although, none of your html elements have any closing tags.
This will group all of the elements inside one big parent <label>.
So when the browser auto-closes the unclosed tags at the end of the document, this causes a hodgepodge of mixed up child elements. Close your elements.
2.) The first two text boxes have the same name="numbers" attribute. You can only do that with radio type inputs.
3.) Your <form> name="" attribute can NOT have the same name as the JavaScript function you are trying to call. They are stored in the same browser namespace so it causes an error.
Notes on your JavaScript:
1.) Your checked === true is an exact comparison. This will almost never evaluate to be truthful. Use checked == true, or better yet, just use if( my_element.checked ){}. Sometimes .checked will equal a string like this: .checked = 'checked'. So even though 'checked'==true it will never be truthful for 'checked'===true. The === means Exactly Equal. So only true===true.
2.) Your var x = document.opera.. ... .mberOne"); will store the whole <input> element into the x variable. You need to have ...mberOne").value; so just the value of the <input> is stored, not the whole html element.
3.) The only object that has a getElementById() method is the document. You can't use that from a document form object.
4.) You have to convert your x any y input values to numbers. If not, 5 + 5 will give you 55 instead of 10 because they are treated as strings. I multiplied them by * 1 to do that. I also changed the <input type='text' attribute to type='number' just to be safe.
5.) You can assign your answerBox.value just one time at the end of the function instead of doing it once per if(){} bracket. It will work the same but it's just much more readable.
6.) I used the syntax of form['numberOne'] instead of form.numberOne but they both work the same. It is referencing the element name (not necessarily the id) as it exists inside the form. <form> is the only object that lets you do this, whereas a <div> or <p> does not.

Related

Replace input value by variable and

I'm trying to make a sort of questionnaire/quiz in javascript for my website. The questionnaire is spread on 5 pages, each page has a question. I want to use the GET method so the URL of each page looks something like that:
(I must keep the GET method because I want to use for something else).
First question: http://website.com/quiz/first?q=1
Second question: http://website.com/quiz/second?q=133
Third question: http://website.com/quiz/third?q=133
Fourth question: http://website.com/quiz/fourth?q=1332
Fifth question: http://website.com/quiz/fifth?q=13324
The user lands on the first page --> get a radio input form --> checks one --> gets redirected to the second page --> etc...
The ?q= is a variable containing the answers, for example ?q=133 means the user picked the following answers:
In the first question, he checked the radio input of the value 1
In the second question, he checked the radio input of the value 3
In the third question, he checked the radio input of the value 3
(so 133 means the user check the 1 for the first question, 3 for the second, 3 for the third.)
I managed to make the variables work:
answPre: gets the previous answer from the form GET (?q=1).
answCurrent: gets the radio input checked from the current page.
urlVal: an combination of the two (answPre+answCurrent)
so I'd like urlVal to be the value that gets transferred from a page to the other.
But I don't want to have both urlVal and the "q" value (name of checked radio) in the url.
What's the right thing to do?
can I hide the "q" value from the URL?
or can I "overwrite" the q value and put instead urlVal?
I'm lost and would appreciate any help, thanks for your help and your time!
function displayRadioValue() {
// var pageURL = window.location.href;
var fakeURL="website.com/quiz/first?q=1"
var answPre = fakeURL.substr(fakeURL.lastIndexOf('=') + 1); //get the previous page's answer.
//get the current page's answer
var ele = document.getElementsByName('q');
for(j = 0; j < ele.length; j++) {
if(ele[j].checked)
var answCurrent= document.getElementById("demo2").innerHTML = ele[j].value;
}
var array = [answPre,answCurrent]; //combine answPre + answNew
var urlVal = "";
var i;
for (i = 0; i < array.length; i++) {
urlVal += array[i];
}
document.getElementById("demo1").innerHTML = answPre;
document.getElementById("demo3").innerHTML = urlVal;
//document.getElementById("fquiz").submit();// Form submission
}
<html>
<body>
<h2>second.html</h2>
<b>answPre: </b><span id="demo1"></span><br>
<b>answCurrent: </b><span id="demo2"></span><br>
<b>urlVal: </b><span id="demo3"></span><br>
<!-- <b>final answNew: </b><span id="demo4"></span><br> -->
<hr>
<form id="fquiz" method="GET" action="third.html">
<p>Who are you going with?</p>
<input type="radio" name="q" value="1" id="yes"
onClick="javascript: displayRadioValue()">Solo<br>
<input type="radio" name="q" value="2" id="no"
onClick="javascript: displayRadioValue()">Couple<br>
<input type="radio" name="q" value="3" id="no"
onClick="javascript: displayRadioValue()">Family with kids<br>
<input type="radio" name="q" value="4" id="no"
onClick="javascript: displayRadioValue()">Group of friends<br>
<p>(then it takes you to third.html with hopefully this url: ../third.html?q=XX where XX is urlVal)
</form>
</body>
</html>
I've made a few changes to your code to modernize it a bit.
I moved the binding of the event handlers to the JavaScript from the HTML. Generally speaking I like to keep my HTML about the structure and the JavaScript about the behavior.
I added code to grab the step from the URL in addition to the previous answers.
I used querySelector to retrieve the selected radio button, using the :checked pseudo-selector.
I used join('') on the array of answers to make it easier to read.
In the HTML, I used <p> elements for everything that needed to be in one line, rather than tacking a <br> at the end of each line. That's just a personal preference.
I wrapped the radio buttons and their text in <label> elements. This helps in accessibility and to give a larger target for people to click on (clicking on the entire label checks the radio, rather than just the radio itself).
I also changed the name of the URL parameter to urlVal rather than q, but I'm not sure I understood that part of your question. I'm not using the form submission process at all with this code, relying instead on changing the location directly...
Do note that running the code here on Stack Overflow won't redirect correctly, since of course there's nothing at example.com/quiz/second listening, and Stack Snippets are sandboxed anyway. You'll need to adjust the code for your specific use in any case.
// Use JavaScript to attach event handlers to HTML elements.
document.querySelectorAll('input[name="q"]').forEach(el => el.addEventListener('click', displayRadioValue));
function displayRadioValue() {
// var pageURL = window.location.href;
var fakeURL = "example.com/quiz/first?q=1"
var step = fakeURL.substring(fakeURL.lastIndexOf('/') + 1, fakeURL.indexOf('?'));
var answPre = fakeURL.substr(fakeURL.lastIndexOf('=') + 1); //get the previous page's answer.
//get the current page's answer
// The :checked pseudo-class makes it easier to find the checked radio button
var el = document.querySelector('input[name="q"]:checked');
var answCurrent = document.getElementById("demo2").innerHTML = el.value;
var array = [answPre, answCurrent]; //combine answPre + answNew
// The join method is easier to use than looping.
var urlVal = array.join('');
document.getElementById("demo1").innerHTML = answPre;
document.getElementById("demo3").innerHTML = urlVal;
switch (step) {
case 'first': step = 'second'; break;
case 'second': step = 'third'; break;
case 'third': step = 'final'; break;
default: return;
}
location.href = `example.com/quix/${step}?urlVal=${urlVal}`;
}
.form-group { margin: 0; }
<h2>second.html</h2>
<!-- <br> is a presentational element; better just to split up lines with paragraphs -->
<p class="form-group"><b>answPre: </b><span id="demo1"></span></p>
<p class="form-group"><b>answCurrent: </b><span id="demo2"></span></p>
<p class="form-group"><b>urlVal: </b><span id="demo3"></span></p>
<!-- <p class="form-group"><b>final answNew: </b><span id="demo4"></span></p> -->
<hr>
<form id="fquiz" method="GET" action="third.html">
<p>Who are you going with?</p>
<!-- <br> is a presentational element; better just to split up lines with paragraphs -->
<!-- Always use <label> elements to label form fields -->
<!-- IDs must be unique to a document. They did not appear relevant here. -->
<p class="form-group"><label><input type="radio" name="q" value="1">Solo</label></p>
<p class="form-group"><label><input type="radio" name="q" value="2">Couple</label></p>
<p class="form-group"><label><input type="radio" name="q" value="3">Family with kids</label></p>
<p class="form-group"><label><input type="radio" name="q" value="4">Group of friends</label></p>
<p>(then it takes you to third.html with hopefully this url: ../third.html?q=XX where XX is urlVal)</p>
</form>

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

User input from text box and radio buttons reiterated in an alert, showing undefined? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Basically what I'm attempting to do is a mad lib story with user input. I've gotten to the stage where I need to show an alert with each input, alert("hello "+name+". You've chosen "+userinput+", etc)
My alert is showing up, but the information is not collecting from the textboxes/radio buttons. It is simply showing undefined.
This is what I have so far..
The purpose of this step is to add the code to the new function so that it will create our story.
Add JavaScript statements to your function to collect all the information from each form element.
Display the user’s information in one alert function.
For Example: ”Hello [name], your story values are [title], [vegetable], [adjective], [number #1], [number #2]”
function beginstory() {
alert("welcome "+name+". you have chosen: "+title+" "+hobby+" "+adjective+" "+number1+" ");
var name=(document.getElementById('username').value);
var title = document.getElementById("storytitle").value;
var hobby = document.getElementById("hobby").value;
var adjective = document.getElementById("adjective").value;
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var trex = document.getElementById("trex").value;
var steg = document.getElementById("steg").value;
var diplod = document.getElementById("diplod").value;
var crazy = document.getElementById("crazy").value;
var charming = document.getElementById("charming").value;
var curious = document.getElementById("curious").value;
var he = document.getElementById("he").value;
var she = document.getElementById("she").value;
var ze = document.getElementById("ze").value;
var jurassic = document.getElementById("jurassic").value;
var colonial = document.getElementById("colonial").value;
var twenty = document.getElementById("twenty").value;}
<form id="story" action="">
What is your name? <input type="text" name="storyelements" id="username"><br>
What is the title of your story? <input type="text" name="storyelements" id="storytitle"><br>
Name a hobby: <input type="text" name="storyelements" id="hobby"><br>
Name an adjective trait: <input type="text" name="storyelements" id="adjective"><br>
Name a number greater than one: <input type="text" name="storyelements" id="number1"><br>
Name another number greater than one: <input type="text" name="storyelements" id="number2"><br>
Choose a dinosaur: <input type="radio" name="dinosaur" id="trex" checked="checked">Tyrannosaurus Rex
<input type="radio" name="dinosaur" id="steg">Stegosaurus
<input type="radio" name="dinosaur" id="diplod">Diplodocus<br>
Choose a personality trait: <input type="radio" name="trait" id="crazy" checked="checked">Crazy
<input type="radio" name="trait" id="charming">Charming
<input type="radio" name="trait" id="curious">Curious<br>
Choose your preferred pronoun: <input type="radio" name="pronoun" id="he" checked="checked">He
<input type="radio" name="pronoun" id="she">She
<input type="radio" name="pronoun" id="ze">Ze<br>
Choose an era: <input type="radio" name="era" id="jurassic" checked="checked">Jurassic
<input type="radio" name="era" id="colonial">Colonial
<input type="radio" name="era" id="twenty">The 1920s<br>
<!-- BUTTONS -->
<input type="button" onclick="beginstory()" name="storytime" value="Start Your Story!"></button><br>
<input type="reset" name="clearform" value="Clear Form">
</form>
Well, you might try defining the variables BEFORE you display them.
As is, you are trying this:
alert("welcome "+name+". you have chosen: "+title+" "+hobby+" "+adjective+" "+number1+" ");
var name=(document.getElementById('username').value);
var title = document.getElementById("storytitle").value;
...
See how you are telling it to display, for example, 'name'... and then in the very next line telling it what name should mean?
Try flipping that around.
...
var colonial = document.getElementById("colonial").value;
var twenty = document.getElementById("twenty").value;}
alert("welcome "+name+". you have chosen: "+title+" "+hobby+" "+adjective+" "+number1+" ");
By putting the alert at the end of the function instead of the beginning, you have defined the variables, and THEN told it where to display them.
Should work better for ya.
** EXPANDED **
OK... to grab the buttons that get selected:
All form elements will have a name or an id. These are used to pass information to the server in name=value pairs whenever the form is submitted.
Most people prefer id for most things, but on radio buttons specifically, you should have a name set; this allows you to have two or more buttons return their value under the same identifier:
<label>Male<input type="radio" name="gender" value="male"></label>
<label>Female<input type="radio" name="gender" value="female"></label>
That doesn't work with id's because id's need to be unique.
You can then create a variable and load it with the radio button itself:
var myButton = document.getElementByName('gender');
This returns BOTH radio buttons, because they both have the same name. It return them in an array, and to access them, you simply use array notation:
var maleButton = myButton[0]; // These are stored in the order they are found in
var femaleButton = myButton[1];// in the HTML
NOTE: document.getElementById('youridhere') returns a single value instead of an array, since id's are always unique... but we can't use it here, since these are not using id's.
You can then access the members of these objects just like you would any other:
alert("The value of maleButton is " + maleButton.value);
Should alert "male".
If that was the only data you needed out of the object, you could have grabbed that originally, however, and saved some typing:
var myValue = document.getElementByName('gender')[0].value;
Hope that helps!

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

How do I execute a JavaScript function from clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
<script language="Javascript">
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex)
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex)
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex)
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex)
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex)
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}};
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="var currency = KWD">
<input type="button" value="USD" OnClick="var currency = USD">
<input type="button" value="GBP" OnClick="var currency = GBP">
<input type="button" value="EUR" OnClick="var currency = EUR">
<input type="button" value="CAD" OnClick="var currency = CAD">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="showMeArea.value=finddivid(mktprc,trdval);">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="30">
</html>
If you run this html in your browser you should see what I am trying to achieve.
It is far from complete but here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started 4 days ago!) so would like any like of help that can be offered.
Thanks in advance of your comments.
The first request requires that you put the currency into the actual script, and I would recommend using a setter function:
<script language="Javascript">
var currency; // you might want to set this at a default just in case
function setCurrency(val) { currency = val; } // Setter function
function finddivid(marketprice,tradevalue) {
Then call it in your button click:
<input type="button" value="KWD" onClick="setCurrency('KWD');">
As for the second request, I'd say you have the concept down well enough, but you don't have the method exactly right. First your inputs will need an id attribute:
<input name="mktprc" id="mktprc" input type="number">
<input name="trdval" id="trdval" input type="number">
The name attribute is used for posting values, the id attribute is used by javascript to find elements within a page. Using jQuery would make retrieving these elements easy, but I'll show both the jQuery and the standard JavaScript method of doing this:
jQuery:
<input type="button" value="Calculate" OnClick="$('#showMeArea').val(finddivid($('#mktprc'),$(#'trdval')));">
The $('#id') selects an element. The method .val() sets the value.
Note for the jQuery purists: Yes, there are much better/sophisticated ways to accomplish this with jQuery, but this answer is targeted to my perception of OP's JavaScript capability.
Standard Javascript:
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value = finddivid(document.getElementById('mktprc'),document.getElementById('trdval'));">

Categories

Resources