Calculations based on radio button choices - javascript

I am using a MEAN stack for my web project. The front end is a simple registration form that asks for several user inputs. For example, it says "how many products are you buying?" The next question is a radio button. It says is this product large or small? My question is the following: the calculation to get the cost of the order is #products*42+(12 if large is selected) or #products*42+(0 if small is selected). How do I code this in javascript(I am using node in my backend). In other words, how do I tell my calculation code that when user selects a radio button you need to add a following number and how do I pass on the number of products typed to my formulas? I have started by assigning value=1 for small and value=2 for large radio button option. Just a general example would be helpful as I can code the details and update the formulas once I get around this problem. Thank you

If you want to do the calculation on the client side and the elements are in an HTML form like:
<h1>Radio Buttons</h1>
<form name="catch-radio" method="post">
<div class="input">
<span class="label">How many products are you buying?</span>
<input id="product-count" type="text" name="product_count" value="0"/>
<br/>
<span class="label">Is this product large or small?</span>
<br/>
<span class="label">Large</span>
<input type="radio" name="product-size" value="12" checked="checked"/>
<br/>
<span class="label">Small</span>
<input type="radio" name="product-size" value="0"/>
</div>
</form>
<div>
<h2>Cost of order:</h2>
<p id="calculation"></p>
</div>
with an input for the number of products (with an id of 'product-count') and radio buttons corresponding to the product size (named 'product-size'), you can calculate the cost and output it to an element on the page (with an id of 'calculation') by adding event handlers to the form fields to register a change in the form, and then from those handlers calling a function to perform the calculation and update the page accordingly like so:
// Cost is the count of products purchased multipled by 42 then added
// to 12 in the case that the product is large, and zero in the case
// that the product is small
function calculate_cost() {
let count = parseInt(document.getElementById('product-count').value);
if (count > 0) {
let size = 0;
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
if (document.getElementsByName('product-size')[i].checked) {
size = parseInt( document.getElementsByName('product-size')[i].value);
break;
}
}
let cost = count * 42 + size
document.getElementById('calculation').innerHTML = cost;
}
}
// handlers for form input change
// call calculate_cost() on change
// note that the text input is an on-change event but for radio buttons
// an onclick handler is needed for each button
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
document.getElementsByName('product-size')[i].onclick = function() {
calculate_cost();
}
}
document.getElementById('product-count').onchange = function() {
calculate_cost();
}
I put up a quick demo of this on CodePen here: http://codepen.io/P1xt/pen/yOKqXP/
The particularly interesting bit is that for the radio buttons, you need to add a click handler for each button separately (and it must be a click not a change handler, and to figure out which radio is currently selected, you need to explicitly check each one to see if it's 'checked'.
Note: If you're looking to do your calculations on the server-side, you'd need to submit the form, then collect the product-count and product-size from the submitted form elements in order to perform the calculation.

Why not use 0 and 12 as the values for the radio buttons, then the backend can just add the selected value?

Related

Is there a way to uncheck a checkbox if it's counter equals to 0 with JavaScript or PHP?

help me out on this one if it's possible.
I have a product page and, on this page, people will be able to select a color to remove from the package and select how many items from determined kind they'll buy.
Example: I'm selling blouses and i have'em in 6 colors, red, blue, purple, yellow, orange and green, the customer would be able to choose one between those 6 or none of them and, they must fill some boxes with some infos, like, how many small blouses, or how many large blouses, etc.
But my website will be mainly accessed by old fellas, so, i can't just do my thing and hope for the best like some would, i need to make this site really easy and almost out of the box to use it.
Heres a printscreen of my web page
-> printscreen: http://prntscr.com/ptdyu2
Anyway, i need to uncheck everybox that has a 0 or smaller number in front of it.
Is there a way for doing this?
function(checkbox_validator){
var checkbox0 = document.getElementsByName(tmcp_checkbox_0_0_quantity)
if (checkbox0 != True){
//This is how much i've progressed on this part, only came until this point
}
}
Sure it is possible. I created you a little example. Basically you will add a event listener for change on the input text fields. If the user types a number, or the value will change somehow, the event listener is getting triggered.
Based on the value you will set the specific checkbox checked or unchecked.
var input = document.getElementById('inputItem1');
var checkbox = document.getElementById('checkItem1');
input.addEventListener("input", update);
function update()
{
//Now update the selector
if (input.value > 0 )
{
checkbox.checked = true;
}
else
{
checkbox.checked = false;
}
}
<form>
<input name="input" value="0" id="inputItem1">
<input type="radio" id="checkItem1" name="checkItem1" value="">
</form>

How to disable check box per day and fetch the selected values using Angular.js?

I have one table where some dynamic drop down list is present for 7 days. I have also + button implementation which can create more row dynamically for a day.
For each row I have check box. Here I need for each day user can only check up-to two check box and other will remain disable.
In my case after checked from 2 check box from total table other are becoming disable but here I need to disable per day.
My all working code is present inside: plunkr.
There you can find one Edit button; I need when user will click on edit button the stored data (clicked on store button) will again set on the required field with check box.
My all code is here.
Is this what you require, it's a little hard to understand your question:
So instead of your disabled function:
$scope.chk =[];
$scope.isDisabled = function(dayName) {
var count = 0;
if ($scope.chk[dayName]) {
for (var prop in $scope.chk[dayName]) {
if ($scope.chk[dayName][prop]) count++;
}
}
return count++ === 2;
};
Note the line above the disabled function. And then your html:
<td>
<input type="checkbox"
name="{{d.day_name}}"
value="true"
ng_model="chk[d.day_name][$index]"
ng-checked="answerIsSelected($parent.$index, $index)"
ng-click="toggleAnswerSelected($parent.$index, $index)"
ng-disabled="isDisabled('{{d.day_name}}')" />
</td>
Plunk here: Plunky McPlunk
Seems to do as you ask, disable after 2 goes.
Check this additional link: More insight
For further info

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

Adding total of checked Radio Buttons

UPDATE
If you try the form on this link http://jsfiddle.net/Matt_KP/BwmzQ/ the fiddle and select the top right £40 radio button then see the order total at the bottom it says £40. Then if you select the £75 the order total changes to £75 but then if you go back and check the £40 again the order total is £75 + £40 when it should just be £40 for the radio button that is checked.
UPDATE END
I have a section with Radio buttons where only certain radio buttons can be checked if others are selected. So say if a user selected one Radio Button but then selected another the first Radio Button would become unselected as they cannot have both selected.
Also I am using a custom attribute in the radio buttons called data-price which holds the value of each radio button that needs to be added toghther.
The problem is when a user selects a Radio Button the total shows fine but then if the user selects another radio button that can't have the previous one selected it adds the total onto the previous one where it should only add the Radio Buttons that are checked. It is kind of like caching the totals I think.
This is what I am using to total the checked Radio Buttons:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input:radio').change(function(){
var total = 0.0;
$('input:radio:checked').each(function(){
total += parseFloat($(this).data('price'));
});
$('#total').val(total.toFixed(2));
});
})
</script>
I think the majority of your issues can be circumvented with some new HTML....
Your crazy jQuery code to limit the input is ridiculous.. you have name, value, and your data-price attributes... splitting each radio set up by item seems a little overkill to me..
Here is a limited example (as per our discussion in the chat).
http://jsfiddle.net/CZpnD/ <- here is the example you can work from..
the main things to look at are how I used the same radio name for each "block" of options, and how I loop through all options when a single option is changed to get the new total (not the most efficient but it works).
and for the love of pete use labels!
HTML is build to do this.
<form name="myform">
<input type="radio" name="foo" value="10" /> foo
<input type="radio" name="foo" value="30" /> bar
</form>
If you give radio buttons the same name then only one can be selected.
Further more when you get the radio element the .value property represents the value of the currently checked radio button
var myform = document.forms.myform;
var radio = myform.elements.foo;
var price = radio.value;
Note that radio is a RadioNodeList which is only returned by elements[name]
Example
However it turns out that browser support for RadioNodeList is appaling so you have to do it manually. Or use the RadioNodeList polyfill
for (var i = 0, len = radio.length; i < len; i++) {
var el = radio[i];
if (el.checked) {
var price = el.value;
break;
}
}

jQuery prepopulate form fields from select box and calculate results

I am building a calculator form to allow people to calculate the cost of running electrical appliances. They can select an appliance, as an example, from a dropdown list and this should prepopulate the text fields with the figures necessary for the calculation. Here is the form:
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<label>Appliance</label>
<select id="list" >
<option value="select">Select</option>
<option value="dishwasher">Dishwasher</option>
<option value="iron">Iron</option>
</select>
<label>Watts</label> <input name="watts" /><br>
<label>Hours</label> <input name="hours" /> <br>
<label>Price</label> <input name="price" /> <br>
<label>Number</label> <input name="number" /> <br>
<label>Total</label> <input name="total" value="" id="total"></input>
</form>
When a user selects an appliance I want the input fields to be filled something like this:
case 'dishwasher':
$('input[name="watts"]').val('1200');
$('input[name="hours"]').val('20');
$('input[name="price"]').val('10');
$('input[name="number"]').val('1');
Then do some calculation on the figures:
kilowatts = watts / 1000;
kwhours = kilowatts * hours;
costpounds = kwhours * price / 100;
total = costpounds * number
and put the total into the total field in the form, the idea is to also allow the user to change the figures, or even just add their own, in the form and the total updates accordingly. I can get all the individual bits to work, but don't know jquery well enough to put it all together. Help would be greatly appreciated. Thanks!
Here is some javascript / jquery to get you started. There are more efficient ways, but those are very confusing for someone just learning.
//when the document is finished being rendered, this fires
$(document).ready(function(){
//if the user changes the value in the select dd, this fires.
$('#list').change(function(e){
changeInputValues(this.val());
});
// standard JS function to set the input values with defaults for a given drop down. your idea ;)
function changeInputValues(ddValue){
//put your Case 'dishwasher' code here, one case for each Drop down value
//$('input[name="watts"]').val('1200');
//$('input[name="hours"]').val('20');
//$('input[name="price"]').val('10');
//$('input[name="number"]').val('1');
//recalculate the figures
recalculate();
};
// when someone changes an input, but not the Drop Down, we have that on already.
$('input').not('select').change(function(e){
recalculate();
});
function recalculate(){
// get the current values, then do your math
//var currentWatts = $('input[name="watts"]').val();
//var currentHours = $('input[name="hours"]').val();
//....
//var total = 0;
// do more math... whatever you want
//set the 'visible' value
$('input[name="total"]').val(total)
};
});
So basic structure is 2 functions.
Called when the "appliance" select is changed. Takes all the values of the item selected by grabbing the id like $(this)find('selected').attr('id')*. Once you have the id of the select appliance you can use it to pull the correct values from your appliance arrays and then it's easy to $(this).find('name_of_filed').text("value from the array") with a little for each loop.
called when any other field is onChanged (or you can make an update button in case it's annoying to have it constantly updating while you are making multiple changes). Also called at the end of function 1. Takes all the values from the fields, does calculation, inserts into "total" field.
you can certainly break this down much further to smaller pieces if you want it to be more easily edited in the future and to reuse any of this code but if it's going to be a one of then I wouldn't bother splitting it much more than this.
I can get a lot more specific if need be but I figure it's better for you to try and figure specifics out to learn as you go and we here at SO can answer specific questions as you go.
*may not be actuall correct code. I'm lazy and you will learn more this way! ;)

Categories

Resources