How to set data range based on radio button selected - javascript

I need to make the min and max variables change depending on the radio button checked. Currently my HTML looks like
<input type="radio" name="type" class="frequency" value="0">
<label for="0">1960-2099</option>
<input type="radio" name="type" class="frequency" value="1">
<label for="1">Other range, e.g. 1970-2000</option>
And the js to generate the year range looks like
$(".frequency").click(function(){
var $msd = $("#startDate");
var $month = $("#startMonth");
var $year = $("#startYear");
min = 1960
max = 2099
$('select').change(function () {
var val = "01/" + $month.val() + "/" + $year.val();
$msd.val(val);
});
select = document.getElementById('startYear');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
var $mfd = $("#finalDate");
var $monthf = $("#finalMonth");
var $yearf = $("#finalYear");
$('select').change(function () {
var val = "01/" + $monthf.val() + "/" + $yearf.val();
$mfd.val(val);
});
selectf = document.getElementById('finalYear');
for (var i = min; i<=max; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
selectf.appendChild(opt);
}
});

if you want to make changes in min and max value depending on the radio button click then see if my solution works for you or not.
<script>
$(document).ready(function() {
$(".frequency").click(function() {
let val = $(this).val();
let min = 0;
let max = 0;
if (val == 0) {
// 0 for 1960-2099
// code goes here
// assign value to min and max variable here
}
if (val == 1) {
// 1 for Other range or whatever the range you want
// code goes here
// assign value to min and max variable here
}
});
});
</script>

Add an event to the Event Listener, then:
$(".frequency").click(function(event){
var $msd = $("#startDate");
var $month = $("#startMonth");
var $year = $("#startYear");
let min;
let max;
if (event.target.value === 0) {
min = 1960
max = 2099
} else {
min = 1970
max = 2000
}
I don't know Jquery, but it's pretty straightforward also in plain JS.

Related

Javascript combined value sliders

The solutions I have found are jQuery and can't understand them yet.
Anyways, I have a couple of sliders and I want to make it so that their combined max values are always less than a predefined value (variable called available in this case). So that when I change a slider, the max values of the other sliders change.
var available = 10;
var max = 0;
var old = 0;
window.onload = function () {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++) {
//Define all sliders?
sliders.item(i).max = available;
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
sliders.item(i).addEventListener("input", function(){
updateSliders();
Slider(this);
})
}
}
function updateSliders() {
var sliders = document.getElementsByTagName("input");
var numSliders = sliders.length;
for (i = 0; i < numSliders; i++)
{
document.getElementById(sliders.item(i).id + "val").innerHTML = sliders.item(i).value;
document.getElementById(sliders.item(i).id + "max").innerHTML = sliders.item(i).max;
}
};
function Slider(active) {
//Get weird set thingy of all sliders
var sliderObject = document.getElementsByTagName("input");
var numberSliders = sliderObject.length;
var total = 0;
//Work out what is being displayed
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
total += parseInt(value);
}
for(i=0;i<numberSliders;i++)
{
var value = sliderObject.item(i).value;
max = available - value;
if(sliderObject.item(i) != active)
{
console.log("total = " + total);
console.log("old = " + old);
var difference = total - old;
console.log("Difference = " + difference);
sliderObject.item(i).max = sliderObject.item(i).max - (total - old);
}
}
old = total;
}
<div class="sliderContainer">
<input id="slider1" type="range" value=0> <span id="slider1val">0</span>/<span id="slider1max">0</span>
<br>
<input id="slider2" type="range" value=0> <span id="slider2val">0</span>/<span id="slider2max">0</span>
<br>
<input id="slider3" type="range" value=0> <span id="slider3val">0</span>/<span id="slider3max">0</span>
<br> </div>
It kinda works, but the numbers it displays are wrong or something?
Thanks for your time.
One thing you need to change is the order of function calls executed on input event. Slider(this) should be first.
Here is your fixed code: https://codepen.io/kejt/pen/xgoqeX

.innerHTML += id, no duplicates

Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?
.innerHTML += id;
If you need some more details here's a code dump of the relevant code:
Javascript
function findTotal() {
var items = new Array();
var itemCount = document.getElementsByClassName("items");
var total = 0;
var id = '';
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
if (document.getElementById(id).checked) {
total = total + parseInt(document.getElementById(id).value);
document.getElementById(id).parentNode.classList.add("active");
document.getElementById(id).parentNode.classList.remove("hover");
document.getElementById('display').innerHTML += id;
} else {
document.getElementById(id).parentNode.classList.remove("active");
document.getElementById(id).parentNode.classList.add("hover");
}
}
console.log(total);
document.getElementById('displayTotal').value = total;
}
HTML
<label class="hover topping" for="c4">
<input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>
Note: many more label classes
Previous answer should do it. Here your code (see comment "clear container"
Additionally I have simplified your code a bit. Readability greatly increased.
Maybe you should switch to jQuery in general, much simpler for your example.
var displayElement = document.getElementById('display'),
displayTotalElement = document.getElementById('displayTotal');
function findTotal() {
var items = [],
itemCount = document.getElementsByClassName("items"),
total = 0,
id = '';
// clear container
displayElement.innerHTML = "";
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
var element = document.getElementById(id),
elementsParent = element.parentNode;
if (element.checked) {
total = total + parseInt(element.value, 10);
elementsParent.classList.add("active");
elementsParent.classList.remove("hover");
displayElement.innerHTML += id;
} else {
elementsParent.classList.remove("active");
elementsParent.classList.add("hover");
}
}
console.log(total);
displayTotalElement.value = total;
}
Reset the text before the loop:
document.getElementById('display').innerHTML = '';
At the moment you're just always adding to whatever's already thereā€¦

Bind radio selection to variable to use in equation

I have a radio group that I am using to select between different options and change what is being presented to the user:
$(document).ready(function () {
$("input[name='status']").click(function() {
console.log("changed");
if ($("input[name='status']:checked").val() == '36')
$(".output2").html("4.36%" + "<span class=\"expandedTermsText\"> APR<\/span>");
if ($("input[name='status']:checked").val() == '48')
$(".output2").html("4.74%" + "<span class=\"expandedTermsText\"> APR<\/span>");
if ($("input[name='status']:checked").val() == '60')
$(".output2").html("4.94%" + "<span class=\"expandedTermsText\"> APR<\/span>");
else if ($("input[name='status']:checked").val() == '72')
$(".output2").html("5.30%" + "<span class=\"expandedTermsText\"> APR<\/span>");
});
});
And I have another function that I am using to display the result from equation but have the choice of APR set as a hard coded value:
$(document).ready(function () {
$(function () {
$("body").on("blur", "#vehiclePrice,#estimatedTaxesAndFees,#downPayment,#manufacturerRebate,#tradeInValue,#amtOwedOnTrade,#extendedWarranty,#gapInsurance,#serviceContract", function () {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#vehiclePrice').val()) || 0;
var input2 = parseInt($('#estimatedTaxesAndFees').val()) || 0;
var input3 = parseInt($('#downPayment').val()) || 0;
var input4 = parseInt($('#manufacturerRebate').val()) || 0;
var input5 = parseInt($('#tradeInValue').val()) || 0;
var input6 = parseInt($('#amtOwedOnTrade').val()) || 0;
var input7 = parseInt($('#extendedWarranty').val()) || 0;
var input8 = parseInt($('#gapInsurance').val()) || 0;
var input9 = parseInt($('#serviceContract').val()) || 0;
var sum=input1 + input2 - input3 - input4 - input5 + input6 + input7 + input8 + input9;
$('.total').text('$'+sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
var principle = parseInt($('#vehiclePrice').val()) || 0;
var apr = .0530;
var months = 72;
var perMonth = sum*(apr/12)/(1-Math.pow((1+(apr/12)),-months)).toFixed(2);
$('.perMonth').text('$'+perMonth.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
};
var output_total = $('#total');
});
});
What I need is to have these two variable:
var apr = .0530;
var months = 72;
Bound to the radio changes which are represented with clicks since I am displaying the radio choices as buttons.
I have the fiddle here:
Fiddle
The clicks aren't working in the fiddle but they are working on my local... I'm just trying to figure out a way to make the formula dynamic so that when I click the radios it will update the var apr = .0530; var months = 72; accordingly.
Any help would be appreciated.
if i missunderstand you, then sorry!
you can bind these values as attriutes to your radios like:
<input type="radio" value="...." name="status" apr="0.0530" months="72"/>
...etc
then you get it using $("input[name='status']:checked").attr("apr").....
UPDATE as per your comment, i would do it then this way:
var updateTotal = function () {
....
var apr = $("input[name='status']:checked").attr("apr");
var months = $("input[name='status']:checked").attr("months");
....
};

How do I make the Values of JavaScript Equation Submit through a form?

I have a script that adds all items based on a form and then subtracts the smallest one of those items to create a new total. I want to be able to return the results in a form.
JavaScript:
var prices = [];
function remove(arr,itm){
var indx = arr.indexOf(itm);
if (indx !== -1){
arr.splice(indx,1);
}
}
function calculateSectedDues(checkbox, amount) {
if (checkbox.checked === true) {
prices.push(amount);
} else {
remove(prices, amount);
}
var total = 0;
for (var i = 0, len = prices.length; i < len; i++)
total += prices[i];
var min = prices.slice().sort(function(a,b){return a-b})[0];
if(typeof min === 'undefined') min = 0;
var withDiscount = total - min;
var discountAmount = withDiscount - total;
//document.grad_enroll_form.total.value = total;
document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}
HTML:
<label><input type="checkbox" onclick="calculateSectedDues(this,5)" name="Scarf"> <span>Scarf</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,10)" name="Hat"> <span>Hat</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,20)" name="Jacket"> <span>Jacket</span><label><br>
<span id="value">Total: $0<br>Discount: $0<br>New total: $0</span>
You will notice that there are 3 different totals. All I want to submit through the form is the final total. The form is fully functioning and works great, I just want to include these results with the form.
& Here is a link to it in action:
http://jsfiddle.net/danielrbuchanan/yjrTZ/5/
To answer your comment (and question):
In your form, add a field <input type="hidden" name="finalTotal">
Then have your function calculateSectedDues end with: document.getElementById('finalTotal').value=withDiscount;
Together it could look like (a little re-factored, look at what I did with 'value'):
function calculateSectedDues(checkbox, amount) {
if (checkbox.checked) {
prices.push(amount);
} else {
remove(prices, amount);
}
var total = 0, i = 0, len = prices.length;
for (; i < len; i++) {
total += prices[i];
}
var min = prices.slice().sort(function(a,b){return a-b})[0];
if(typeof min === 'undefined') min = 0;
var withDiscount = total - min;
var discountAmount = withDiscount - total;
//document.grad_enroll_form.total.value = total;
document.getElementById('value').innerHTML = "Total: $"+total+'<br>'
+ "Discount: $"+discountAmount+'<br>'
+ "New total: $"+withDiscount+'<br>';
//set hidden input value
document.getElementById('finalTotal').value = withDiscount;
}
Once you submit this form, the post-data the server receives will contain a value called 'finalTotal' containing the value of 'withDiscount'.
Just never do (especially TRUST) this in real life when money is involved; anyone can post whatever they want!!

Change variable value when option is selected, return previous value when not selected anymore

I need to update the value of a variable (which I called "tot" in the example) according to what option of a dropdown menu is selected. If I select option 1 or 2 tot must be increased of 10, if I select option 3 variable "tot" must NOT be increased. If i select option 1, and then I change my mind and select option 3 the value of Tot must be restored.
Here's the html of the select
<select name='hello' id='hello'>
<option>Select an option...</option>
<option id='one'>One</option>
<option id='two'>Two</option>
<option id='three'>Three</option>
</select>
And here's the jquery script I wrote. I guess I didn't understand the functioning of .change function, because it doesn't work as I expected.
var extra = 0;
var tot = 0;
$(document).ready(function () {
$('#hello').change(function(){
if($('#one').is(':selected')) {
extra = 10;
}
else if($('#two').is(':selected')) {
extra = 10;
}
else if($('#three').is(':selected')) {
extra = 0;
}
tot = tot + extra;
});
});
Or (if I've understood what you're after correctly)....
var tot = 120; //some number picked at random
var helloed = false; // flag for whether incremented
$(document).ready(function(){
$("#hello").change(function(){
var sel = $(this).find(":selected").attr("id")
if (sel == "one" || sel =="two" ) {
if (!helloed) {
tot += 10;
helloed = true;
}
} else { // 'three' selected
if (helloed) {
tot -= 10;
helloed = false;
}
}
alert ("Tot is now " + tot);
});
});
If there were more options I'd go for a switch rather than an IF but that will do for this example
var extra = 0;
var tot = 0;
var initialTot = tot;
$(document).ready(function () {
var previous = 0;
var selected = 0;
$('#hello').change(function(){
if($('#one').is(':selected')) {
previous = selected;
selected = 1;
extra = 10;
}
else if($('#two').is(':selected')) {
previous = selected;
selected = 2;
extra = 10;
}
else if($('#three').is(':selected')) {
previous = selected;
selected = 3;
extra = 0;
}
tot = tot + extra;
if(previous === 1 && selected === 3) {
tot = initialTot;
}
});
});

Categories