Trying to do a simple calculation with a button - javascript

For a project, I'm trying to make a type of calculator. Where I'm having trouble with is changing my button value to what I want the calculation output to be
here is a small portion of my html because it's a big table but I'm trying to make a button like this one for all of them...
<td><span>2</span></td>
<td><input type="text" id="round[2][score]" ></td>
<td><input type="text" id="round[2][rating]" ></td>
<td><input type="text" id="round[2][slope]" ></td>
<td><input type="button" onclick="calculate1()" id="round[2][handicap]" Value="Press"></td>
</tr>
here is the function I made for the calculations:
function calculate1()
{
round2score = document.getElementById('round[2][score]').value;
round2rating = document.getElementById('round[2][rating]').value;
round2slope = document.getElementById('round[2][slope]').value;
document.getElementById("round[2][handicap]").innerHTML = round2score - round2rating;
}
again, my goal is to change the "press" to the calculated value.

Instead of using InnerHTML, to set the button value use the following:
document.getElementById("round[2][handicap]").value = String(round2score - round2rating);
This will set the value of the button, which is the text displayed.

Related

How do I validate radiobuttons using a javascript function?

I have a computing assignment to do.
I've done most I'm just stuck on this task:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/
function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert

jquery get next input element value in <td>

I have some piece of an html table which reads like
<table>
<tr>
<td>
<input type="text" class="myclass" name="first_ele[]" value="100" />
</td>
<td>
<input type="text" class="anotherclass" name="secon_ele[]" value="" />
</td>
</tr>
</table>
I have a piece of jquery that will get the value of the element that contains class "myclass" on keyup and I am getting the proper value.
I need to get the value of the next input element.
FYI , The table gets rows added dynamically.
My issue is I don't know how to point to the next available input element.
my jquery to get the element which has the class "myclass" is as follows.
$('.tInputd').keyup(function(){
var disc = $(this).val();
});
your help is greatly appreciated.
Try
$('.myclass').on('keyup', function () {
var disc = $(this).closest('td').next().find('input').val();
});
or
$('.myclass').on('keyup', function () {
var disc = $('.anotherclass').val();
});

Using mapping in javascript

I want a javascript function for mapping checkbox id with the value of someother field in grails
i have a gsp page with checkbox and cost field as follows
<td>
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="${testUnitInstance.id}" />
</td>
<td>
<g:textField name="cost" maxlength="20" required="" id="${testUnitInstance.id}" />
</td>
i want a javascript function with mapping between checked checkbox id with cost field
you need a on change function for the check box and add intital for the id to diffrentiate it the cost text field,since intital follows ID later on you extract that ID and find the corresponding cost field.
"c_${testUnitInstance.id}"
example
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="c_${testUnitInstance.id}" onChange="FindCost('c_${testUnitInstance.id}')"/>
<g:javascript>
function FindCost(chckboxname){
console.log("check Status:"+$("#"+chckboxname).prop("checked"));
var arrayOfchckBoxId = chckboxname.split("_"); //parse the two parts of the name after _
var commnidforcheckandcost = arrayOfchckBoxId[1];
var initialname = arrayOfchckBoxId[0];
var currentCheckbox = "#"+chckboxname ;
console.log("ID:"+arrayOfchckBoxId[1]);
console.log("Name:"+currentCheckbox);
if(initialname == 'c'){
//display the corresponsing cost text field.
$("#"+commnidforcheckandcost").show() //display the cost with a give id like checkbox
}
</g:javascript>
i guess this should resolve your problem for more help see ,the javascript console debug.
You can do as below
<td>
<g:checkBox type="checkbox" class="select_all" name="counTestUnit" id="checkbox${testUnitInstance.id}" onclick="mapCheckAndField(${testUnitInstance.id})"/>
</td>
<td>
<g:textField name="cost" maxlength="20" required="" id="textField${testUnitInstance.id}" />
</td>
<script>
function mapCheckAndField(testUnitId)
{
//we know that now checkboxId is "checkbox"+testUnitId
//and corresponding textField id is "textField"+testUnitId
//Simply you will get the value of checkbox corresponding textField value as below
$("#textField"+testUnitId).val()
}
</script>

jquery multiply 2 textboxs then show the solution

I have this code that is not working. I am trying to multiply 2 textboxs and show the solution, but it doesn't show anything when I click. The code I have so far is this... what can be wrong with the code below?
<script type="text/javascript">
$('#AddProduct').click(function() {
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val() = totalPrice;
});
</script>
<form name="form" method="post" action="">
<table>
<tr>
<td><input type="text" name="income" id="income" /></td>
<td><input type="text" name="debt" id="debt" /></td>
<td><input type="text" id="solution" name="solution" /> </td>
</tr>
</table>
</form>
Your jQuery needs to be:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val()) * parseInt($('#income').val()); // you can't multiply strings
$('#solution').val(totalPrice); // This is how you use .val() to set the value.
});
This is the way that you'd set the value of the solution textbox:
$('#solution').val(totalPrice);
Also, do you actually have an element with an id of 'AddProduct' on your page?
var totalPrice = $('#debt').val() * $('#income').val();
$('#solution').val(totalPrice);
Demo
After, you add jquery to your page as below
<script src="http://code.jquery.com/jquery-latest.js"></script>
you can do the following:
$('#AddProduct').click(function() {
var totalPrice = parseInt($('#debt').val(),10) * parseInt($('#income').val(),10);
$('#solution').val(totalPrice);
});
You have to tell it you want the value of the input you are targeting.
And also, always provide the second argument (radix) to parseInt. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.
Providing 10 assumes you are wanting a base 10 number.

HTML variable causing error in CGI file

I am having problem printing a particular variable from my cgi file. I receive this variable, called totalCost from my webpage and then try to print it, but nothing happens. All the other variables can be received successfully from the webpage and printed out on another webpage via my cgi file, except for this one..i've checked for case sensitivity but that didnt help
The code in html...
<tr> <td colspan=3 padding=2><b> Total = $ </b> <input type= "text" id="totalCost" disabled= true name= "totalCost" size ="5" maxlength="5" value= 0.00 /> <td> <tr>
the computeCost function
<script type= "text/javascript">
function computeCost(){
var apples= document.getElementById("appleQty").value;
var oranges=document.getElementById("orangeQty").value;
var bananas=document.getElementById("bananaQty").value;
var totCostTemp=0.69*apples + 0.59*oranges + 0.39*bananas;
document.getElementById("totalCost").value= totCostTemp;
}
</script>
In cgi file, which I write using Perl, I receive my variable in this manner:
my ($appleQty, $orangeQty, $bananaQty, $user, $cardType, $c) = (param("appleQty"), param("orangeQty"), param("bananaQty"), param("user"), param("cardType"), param("totalCost"));
then try to print out in this manner..
print header;
print start_html("Receipt"),
print h3("Fruit Store: Order Summary"),
table({-border => 2} ,caption("Your Receipt"),
Tr([th("Name:").td($user),th("Payment Method:").td($cardType),th("Fruit Type").td("Quantity"), th("Apple").td($appleQty), th("Oranges").td($orangeQty), th("Bananas").td($bananaQty), th("Total Cost:").td($c)]));
print end_html;
Please note...all variables except totalCost get printed correctly. totalCost is not printed at all in my resultant webpage...I think this has to do with the fact that I did some computation and perhaps did not store it properly in the id. But I dont know how to resolve that..
thank you for advising!
Disabled fields don't get posted. So you simply need to modify the field to make it readonly. Like :
<input type="text" id="totalCost" readonly="true" name="totalCost" size ="5" value="0.00" />
If you don't like the color of the readonly field, you can use a CSS to modify it like :
<style>
input[readonly=true] {
color:silver;
}
</style>
Or for better CSS compatibility :
<style>
.disabled {
color:silver;
}
</style>
<input type="text" id="totalCost" readonly="true" name="totalCost" size ="5" value="0.00" class="disabled" />
You may also use hidden fields, but you don't have to change your current code.
If the <input> element is never enabled, then it will not be sent to the server when the form is posted.
If you don't want the user to be able to update the field, then don't use an ordinary "text" <input>. Put a <span> there to hold the value, and update an enabled "hidden" <input> instead.
function computeCost(){
var apples= document.getElementById("appleQty").value;
var oranges=document.getElementById("orangeQty").value;
var bananas=document.getElementById("bananaQty").value;
var totCostTemp=0.69*apples + 0.59*oranges + 0.39*bananas;
document.getElementById("totalCost").value= totCostTemp;
document.getElementById('totalCostView').innerHTML = '$' + totCostTemp;
}
and the page would look like:
<td>
<span id='totalCostView'>$0.00</span>
<input type='hidden' id='totalCost' name='totalCost' value='0.00'>
</td>

Categories

Resources