JavaScript and getting the value of radio button - javascript

I tried to create an online calculation form using javascript, everything is ok except radio buttons.
Scenario:
x(select list) =
item1 - value="11.2"
item2 - value="7.6"
item3 - value="7"
y=(input number)
z=(input number)
coverkind=(radio button)
if 1 selected >> coverkind = z*800
if 2 selected >> coverkind = ((y/16)+1)*8*z
totalprice= (x*y*z)+(1000*z)+coverkind
my work till now:
<html>
<head>
<script type="text/javascript">
function getselectionPrice() {
var elt = document.getElementById("selectionone");
var selectionPrice = elt.options[elt.selectedIndex].value;
var y = document.getElementById("y").value;
var z = document.getElementById("z").value;
var ser = (selectionPrice * y * z);
var dz = z*1000;
var coverkind = document.getElementById("cover").value;
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}
var finalPrice = ser + dz;
document.getElementById("totalPrice").value = finalPrice;
}
</script>
</head>
<body>
<div>
<form action="" id="calcform" onsubmit="return false;">
<div>
<div>
<fieldset>
<label>select</label>
<select id="selectionone" name='selectionone' onChange="getselectionPrice()">
<option value="11.2">1</option>
<option value="7.6">2</option>
<option value="7">3</option>
</select>
<br/>
<p>y
<input type="text" id="y" onchange="getselectionPrice()" />
</p>
<p>z
<input type="text" id="z" onchange="getselectionPrice()" />
</p>
<label>cover</label>
<input type="radio" name="cover" value="hard" />hard
<br />
<br>
<input type="radio" name="cover" value="soft" />soft
<br>
<br>
<br/>The new calculated price:
<INPUT type="text" id="totalPrice" Size=8>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="getselectionPrice()" />
</div>
</form>
</div>
</body>
</html>
If I remove the coverkind from js, the rest works fine. I googled about getting value from radio button and nothing found very relevant to this situation.
firebug error panel :
TypeError: document.getElementById(...) is null
var coverkind = document.getElementById("cover").value;

If you can use jQuery, you can get the value of the checked radio button in one line.
var Val = $("input[name=cover]:checked").val();

Here is the solution of your problem.
First give a same id to your radio buttons.
The checked property will tell you whether the element is selected:
<input type="radio" id="cover" name="cover" value="hard" checked="checked" />hard
<br />
<br>
<input type="radio" id="cover" name="cover" value="soft" />soft
and in JavaScript function, you can get it.
var coverkind = null;
if (document.getElementById('cover').checked)
{
coverkind = document.getElementById('cover').value;
}
if (coverkind == 'soft') {
var SizePrice = (z * 800);
} else {
var SizePrice = ((y / 16) + 1) * 8 * z;
}

You can use the output tag if you want or something else for your output. (a <p> element for example). Just make sure you give anything you want to access in your Javascipt an 'id' value.
You'll need to create a new file and call it something like 'script.js'. Google how to include this script in your html document.
Some of the things you'll need to use in your script:
document.getElementById(str) Returns an object representing an html
element with an id of 'str'
parseFloat(str) Takes a string 'str' and return the float value
.value This is a read/write property of an input text box object
that contains the text value
.checked ..and a property of an input radio button object.
When you hit a wall refer to the great google ;) Put all that together and you should be on the right track.

Related

Convert a checkbox value into a live url when checked

I am creating a form where the visitor chooses items they wish to see by clicking relevant checkboxes.
At this time I have the url's of the items as the value of the checkbox and these appear when clicking a Request button.
I would like the url that appears to be live (a href etc), so they just need to click on the link as opposed to copying and pasting into a browser address.
If possible I would like to have the checkbox value to be the item, which then converts to the url onClick. This is so that a right click will not show the url which will be in a separate java file.
This is not urgent, but eventually the results will be imported into a csv/excel file at the site as opposed to sending the results as an email.
Any help would be greatly appreciated.
function displayResult() {
var se = document.getElementById("myEmailList"),
send = document.getElementById("send"),
x = document.getElementById("mySelect"),
l = [],
list = x.querySelectorAll(":checked");
for (i = 0; i < list.length; i++) {
l.push(list[i].value);
var fn = document.getElementById('item_1').value;
document.getElementById('links').value = 'https://example.com';
var fn = document.getElementById('item_2').value;
document.getElementById('links').value = 'https://bbc.co.uk';
var fn = document.getElementById('item_3').value;
document.getElementById('links').value = 'https://google.com';
var fn = document.getElementById('item_4').value;
document.getElementById('links').value = 'https://itv.com';
}
send.href = "mailto:" + l.join(", <br>");
se.innerHTML = l.join(", <br>");
}
<form>
Select items required:
<fieldset id="mySelect">
<input type="checkbox" id="item_1" name="item_1" value="item_1">
Item 1 <br>
<input type="checkbox" id="item_2" name="item_2" value="item_2">
Item 2 <br>
<input type="checkbox" id="item_3" name="item_3" value="item_3">
Item 3 <br>
<input type="checkbox" id="item_4" name="item_4" value="item_4">
Item 4 <br>
</fieldset>
<button type="button" onClick="displayResult()">Request</button>
<a id="send" href="mailto:">Send email</a>
<div id="myEmailList">
<br><br>
<textarea id="links" style="width:300px; "type="text" rows="4"></textarea>
So, you want the form to send the user to the relevant places?
<form>Select your place:
<fieldset id="mySelect">
<input type="checkbox" value="https://www.bbc.co.uk">Item 1
<br>
<input type="checkbox" value="https://google.com">Item 2
<br>
<input type="checkbox" value="email3#domain.com">Item 3
<br>
<input type="checkbox" value="email4#domain.com">Item 4
<br>
</fieldset>
...
</form>

How to manipulate value taken from form

I am taking value from the user inside the form and doing calculations inside new variable by using those values which user input inside the form but I cannot figure out why my code is not working.
function click() {
var l = document.getElementById('l');
var b = document.getElementById('b');
var a = document.getElementById('area');
var area = l.value * b.value;
a.innerHTML = "The ans is " + area;
}
<form>
<label>Length of the triangle: </label>
<br>
<input id="l" type="text" placeholder="Length">
<br>
<label>Base of the triangle</label>
<br>
<input id="b" type="text" placeholder="Base">
<br>
</form>
<p id=area></p>
<button type="button" onclick="click()">Click:</button>
I think i have done everything fine then why on chrome it doesnt show the correct ans.Please help on thsi one
The problem is that inline handlers have a very peculiar scope chain. They're surrounded inside two withs: one for the document, and one for the element on which the inline handler exists. For example, with
<button id="button" onclick="<<CODE HERE>>">
When clicked, the effect will be similar to as if the following was executed:
with (document) {
with (button) {
<<CODE HERE>>
}
}
When you reference click inside one of these handlers, it will first try to find a click property on the element, and it finds one: it refers to HTMLButtonElement.prototype.click:
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button
id="button"
onclick="console.log(click === button.click, click === HTMLButtonElement.prototype.click)"
>Click:</button>
As a result, clicking the button results in HTMLButton.prototype.click being called on that button, which, here, does nothing, which is why you're not seeing any results, and not even an error message.
Either use a different variable name:
function handleClick() {
var l = document.getElementById('l');
var b = document.getElementById('b');
var a = document.getElementById('area');
var area = l.value * b.value;
a.innerHTML = "The ans is " + area;
}
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button onclick="handleClick()"
>Click:</button>
Or, even better, avoid inline handlers entirely, since they behave so weirdly - attach the listener properly using Javascript instead. Using addEventListener also lets you avoid global variable pollution, which is inelegant and can lead to bugs and messy code.
document.querySelector('button').addEventListener('click', () => {
var l = document.getElementById('l');
var b = document.getElementById('b');
var a = document.getElementById('area');
var area = l.value * b.value;
a.textContent = "The ans is " + area;
});
<form>
<label>Length of the triangle: </label><br>
<input id="l" type="text" placeholder="Length"><br>
<label>Base of the triangle</label><br>
<input id="b" type="text" placeholder="Base"><br>
</form>
<p id=area></p>
<button>Click:</button>

Trying to run a program that calculates the needed grade on a final exam to get their desired overall grade

I am trying to run a program that allows a user to input their current overall grade grade (f), their desired overall grade (dg), and the weight of their final exam (g), and would ideally return their needed grade on the final exam to achieve their desired grade.
I have the equation, but am not sure why it is not returning a result on the screen. Can anyone tell me why?
<!DOCTYPE html>
<html>
<title>ffdfsdfdsfdsf</title>
<head>
<script>
function blahBlah
() {
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = document.getElementById ('f').value
var f = (f - f *(4 - f)) / f
}
</script>
</head>
<h1>
f</h1>
<body>
<p>fe: <input id="cg" min="1" max="120"
onchange="blahBlah"</p>
<p>f: <input id="dg" min="3" max="11"
onchange="cf"</p>
<p>f: <input id="wof" min="3" max="11"
onchange="f"</p>
<p><button>Submit</button></p>
<h2 id="f"></h2>
</body>
</html>
Like I said, ideally there are three forms. Once the user completes these inputs, a pop up of their needed grade on the final would pop up under the submit button.
You had some syntax errors which I have corrected in this snippet, namely you needed to make it a string when you were setting innerHTML (thought you should probably use innerText), your <input> tags weren't closed, and you need to invoke your function with () in your onchange attributes.
function computeGrade() {
var cg = document.getElementById("cg").value;
var dg = document.getElementById("dg").value;
var wof = document.getElementById("wof").value;
var ng = (dg - cg * (100 % -wof)) / wof;
document.getElementById("ng").innerHTML = "Needed_grade: " + ng + "%";
}
<h1> Class Calculator</h1>
<p>Current grade: <input id="cg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Desired grade: <input id="dg" min="1" max="120"
onchange="computeGrade()"></input></p>
<p>Final weight: <input id="wof" min="1" max="100"
onchange="computeGrade()"</input></p>
<p><button>Submit</button></p>
<h2 id="ng"></h2>

How to show jquery dialog with radio buttons when checkbox is checked and post value in textbox

I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)

How can I read the value of a radio button in JavaScript?

<html>
<head>
<title>Tip Calculator</title>
<script type="text/javascript"><!--
function calculateBill(){
var check = document.getElementById("check").value;
/* I try to get the value selected */
var tipPercent = document.getElementById("tipPercent").value;
/* But it always returns the value 15 */
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>
<body>
<h1 style="text-align:center">Tip Calculator</h1>
<form id="f1" name="f1">
Average Service: 15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />
Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />
<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>
<br />
Total Bill: <p id="bill"></p>
</body>
</html>
I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.
In HTML, Ids are unique. Try changing the id attributes to tipPercent1, tipPercent2, etc.
Both radio buttons have the same ID - this is incorrect in HTML, as IDs should be unique. The consequence is that document.getElementById cannot be used.
Try document.getElementsByName and loop through the resulting array to find out which one is checked and what its value is.
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
First of all, id's are required to be unique identifiers, so giving two elements the same id will make problems. document.getElementById("tipPercent") after all tries to get one element, so which of those two different input elements should it return?
Second, you can only check if a radio input is checked or not, so you will need to loop through all those inpud fields and check which one is checked to get the current value.
You have two equal ids "tipPercent". getElementById returns only one first result
You should use different ids for each radio. Try something like follows:
<script type="text/javascript">
//a variable that will hold the index number of the selected radio button
for (i=0;i<document.f1.tipPercent.length;i++){
if (document.document.f1.tipPercent[i].checked==true)
var tipPercent= document.f1.tipPercent[i].value;
}
</script>
You may want to change the calculateBill() function with the following:
function calculateBill() {
var tipPercent = 0;
var check = document.getElementById("check").value;
var radioElements = document.getElementsByName("tipPercent");
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked)
tipPercent = parseInt(radioElements[i].value);
}
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
Note the use of document.getElementsByName(), as Oded suggested in another answer.
You should also remove the id attribute from your radio buttions:
<input type="radio" name="tipPercent" value="15" />
<input type="radio" name="tipPercent" value="20" />
The following is a screenshot showing that the above function works fine with the 20% radio button:
How can I read the value of a radio button in JavaScript? http://img695.imageshack.us/img695/6214/tipcalc.png
The id of an element has to be unique, so you can't have two elements with the same id.
When you try to get all radio buttons as a single element, you will get one of them. Which one you get is entirely up to how the browser choose to handle the incorrect id's that you have set. You could get either of the elements, or null, depending on the implementation. In this case you happen to use a browser that gets the first element.
Give the elements their own id:
Average Sevice: 15%<input type="radio" id="tipPercent15" name="tipPercent" value="15" />
<br />
Excellent Sevice: 20%<input type="radio" id="tipPercent20" name="tipPercent" value="20" />
Getting the value attribute from the element will only get the value that you have specified for each of them. Instead you used the checked attribute:
var tipPercent;
if (document.getElementById("tipPercent15").checked) tipPercent = 15;
if (document.getElementById("tipPercent20").checked) tipPercent = 20;

Categories