Bind radio selection to variable to use in equation - javascript

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");
....
};

Related

How to set data range based on radio button selected

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.

Attempting to retrieve a <select>'s .value with jQuery

So I have this HTML Code/Javascript,
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell');
spellSelect.setAttribute('name', 'spell');
spellLabel.setAttribute('for', 'spell');
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 1;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
And am trying to retrieve the .value of the <select id="spell"> options. However, the console returns an undefined, instead of vanish or teleport.
Can anyone point me in the right direction for this?
Well:
Id should be unique so I added spellSelect.setAttribute('id', 'spell' + spellNumber); ( + other rows)
Also multipleSpell = $("#spell" + spellCheck).val();
And console.log(multipleSpell); is called only once at the begining -> you should change it to function too
`
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell' + spellNumber);
spellSelect.setAttribute('name', 'spell' + spellNumber);
spellLabel.setAttribute('for', 'spell' + spellNumber);
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 0;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell" + spellCheck).val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
More info here.
Edited:
Well, i see you are trying to get all select values. Why not try this?
function generateYaml() {
var spellCheck = 1;
var selects = $("select").each(function (index, element) {
var value = $(element).val()
console.log("The value at index %d is %s", index, value);
spellCheck++
});
}
This way you iterate over all the selects, and get their values inside the loop. Try it here (open the developer console):https://darkcyanpointlessbooleanvalue--parzibyte.repl.co/

Superscripts and subscripts in HTML input

I am making a small JavaScript web app that deals with chemical formulas, so I need to allow users to input superscripts. The easiest thing for users would be having the text editor switch to superscript when they press ^. How can I do this with an HTML textarea?
Borrowing from the function in adeneo's answer
Check this fiddle here : fiddle
Usage : To type a superscript , press ^ --> type in the superscript --> press Esc , the superscript will then appear in the textarea.
$(document).ready(function() {
var temp = {}; // store keypresses here
var current_value = "";
$("#text_area").keydown(function(e) {
temp[e.which] = true;
});
$('#text_area').keyup(function(e) {
if (e.keyCode == 27 && current_value != "") {
var length_1 = current_value.length;
var length_without_sup = length_1 - 5;
var substr_superstring = $('#text_area').val().substr(length_without_sup);
var current_text_2 = current_value + substr_superstring;
current_text_2 = current_text_2 + "</sup>";
$('#text_area').val(current_text_2);
$('#text_area').superScript();
}
var flag_shift = false;
var flag_super = false;
for (var key in temp) {
if (key == 16) {
flag_shift = true;
} else if (key == 54) {
flag_super = true;
}
}
if (flag_shift == true && flag_super == true) {
var current_text = $('#text_area').val();
current_text_2 = current_text.substr(0, current_text.length - 1);
current_text_2 = current_text_2 + "<sup>";
$('#text_area').val(current_text_2);
current_value = hide_superscript_tag();
}
delete temp[e.which];
});
});
function hide_superscript_tag() {
var current_value = $('#text_area').val();
current_value_2 = current_value.substr(0, current_value.length - 5);
$('#text_area').val(current_value_2);
return current_value;
}
$.fn.superScript = function() {
var chars = '+−=()0123456789AaÆᴂɐɑɒBbcɕDdðEeƎəɛɜɜfGgɡɣhHɦIiɪɨᵻɩjJʝɟKklLʟᶅɭMmɱNnɴɲɳŋOoɔᴖᴗɵȢPpɸqrRɹɻʁsʂʃTtƫUuᴜᴝʉɥɯɰʊvVʋʌwWxyzʐʑʒꝯᴥβγδθφχнნʕⵡ',
sup = '⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ᴬᵃᴭᵆᵄᵅᶛᴮᵇᶜᶝᴰᵈᶞᴱᵉᴲᵊᵋᶟᵌᶠᴳᵍᶢˠʰᴴʱᴵⁱᶦᶤᶧᶥʲᴶᶨᶡᴷᵏˡᴸᶫᶪᶩᴹᵐᶬᴺⁿᶰᶮᶯᵑᴼᵒᵓᵔᵕᶱᴽᴾᵖᶲqʳᴿʴʵʶˢᶳᶴᵀᵗᶵᵁᵘᶸᵙᶶᶣᵚᶭᶷᵛⱽᶹᶺʷᵂˣʸᶻᶼᶽᶾꝰᵜᵝᵞᵟᶿᵠᵡᵸჼˤⵯ';
return this.each(function() {
this.value = this.value.replace(/<sup[^>]*>(.*?)<\/sup>/g, function(x) {
var str = '',
txt = $.trim($(x).unwrap().text());
for (var i = 0; i < txt.length; i++) {
var n = chars.indexOf(txt[i]);
str += (n != -1 ? sup[n] : txt[i]);
}
return str;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text_area">
</textarea>
I would recommend leveraging an existing solution. Take a look at MathQuill.
Regarding creating your own such system from scratch, there is no simple solution. You would need to do independent research and experimentation and return to Stack Overflow with more specific questions.

how to display the previous user input along with the new input

I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {

Javascript Dynamic Fieldset and sum

I am using a script that adds a fieldset to my form but I am having one glitch that I can not figure out and would appreciate any insight you can provide.
Here is the trouble:
The duplication of the fieldset works great.
I have another script which is creating a sum of the fields named "unitPrice" in the original fieldset. When I add a new fieldset with the new unitPrice fields do not get calculated into the sum. I am sure they are being renamed but what name would I use and how do I write it into the calculation so that I have a total of all of the unitPrice fields?
Thanks for your help.
Here is the Fieldset script:
<script>
function insertAfter(newElement, targetElement)
{
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
{
parent.appendChild(newElement);
}
else
{
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
// Suffix + Counter
var suffix = ':';
var counter = 1;
// Clone nearest parent fieldset
function cloneMe(a)
{
// Increment counter
counter++;
// Find nearest parent fieldset
var original = a.parentNode;
while (original.nodeName.toLowerCase() != 'fieldset')
{
original = original.parentNode;
}
var duplicate = original.cloneNode(true);
// Label - For and ID
var newLabel = duplicate.getElementsByTagName('label');
for (var i = 0; i < newLabel.length; i++)
{
var labelFor = newLabel[i].htmlFor
if (labelFor)
{
oldFor = labelFor.indexOf(suffix) == -1 ? labelFor : labelFor.substring(0, labelFor.indexOf(suffix));
newLabel[i].htmlFor = oldFor + suffix + counter;
}
var labelId = newLabel[i].id
if (labelId)
{
oldId = labelId.indexOf(suffix) == -1 ? labelId : labelId.substring(0, labelId.indexOf(suffix));
newLabel[i].id = oldId + suffix + counter;
}
}
// Input - Name + ID
var newInput = duplicate.getElementsByTagName('input');
for (var i = 0; i < newInput.length; i++)
{
var inputName = newInput[i].name
if (inputName)
{
oldName = inputName.indexOf(suffix) == -1 ? inputName : inputName.substring(0, inputName.indexOf(suffix));
newInput[i].name = oldName + suffix + counter;
}
var inputId = newInput[i].id
if (inputId)
{
oldId = inputId.indexOf(suffix) == -1 ? inputId : inputId.substring(0, inputId.indexOf(suffix));
newInput[i].id = oldId + suffix + counter;
}
}
// Select - Name + ID
var newSelect = duplicate.getElementsByTagName('select');
for (var i = 0; i < newSelect.length; i++)
{
var selectName = newSelect[i].name
if (selectName)
{
oldName = selectName.indexOf(suffix) == -1 ? selectName : selectName.substring(0, selectName.indexOf(suffix));
newSelect[i].name = oldName + suffix + counter;
}
var selectId = newSelect[i].id
if (selectId)
{
oldId = selectId.indexOf(suffix) == -1 ? selectId : selectId.substring(0, selectId.indexOf(suffix));
newSelect[i].id = oldId + suffix + counter;
}
}
// Textarea - Name + ID
var newTextarea = duplicate.getElementsByTagName('textarea');
for (var i = 0; i < newTextarea.length; i++)
{
var textareaName = newTextarea[i].name
if (textareaName)
{
oldName = textareaName.indexOf(suffix) == -1 ? textareaName : textareaName.substring(0, textareaName.indexOf(suffix));
newTextarea[i].name = oldName + suffix + counter;
}
var textareaId = newTextarea[i].id
if (textareaId)
{
oldId = textareaId.indexOf(suffix) == -1 ? textareaId : textareaId.substring(0, textareaId.indexOf(suffix));
newTextarea[i].id = oldId + suffix + counter;
}
}
duplicate.className = 'duplicate';
insertAfter(duplicate, original);
}
// Delete nearest parent fieldset
function deleteMe(a)
{
var duplicate = a.parentNode;
while (duplicate.nodeName.toLowerCase() != 'fieldset')
{
duplicate = duplicate.parentNode;
}
duplicate.parentNode.removeChild(duplicate);
}
</script>
Here is the script I am using for the calculation:
<script type="text/javascript">
function myFunction(){
var the_fields = document.getElementsByName("unitPrice");
var the_sum = 0;
for (var i=0; i<the_fields.length; i++){
if (the_fields[i].value != ""
&& !isNaN(the_fields[i].value))
{
the_sum += Number(the_fields[i].value);
}
}
document.repairform.sum.value = (the_sum.toFixed(2));
}
</script>
I guess that you need to call "myfunction" each time a new field is being added.
When someone loads your page , the "myfunction" calculate the sum of the "existing" fields at the current. When you duplicate the fields you need to re-call "myfunction" so it will update the sum according to the new duplicated fields.

Categories