using one function for multiple entries javascript - javascript

im trying to take multiple inputs from a user with different element id's and run them through one if else function. here is my code:
Enter the grade and number of credits for course 1:
<input type="text" id="lettergrade1" onchange="lettergrade[0]=numgrade(this.value)";>
<input type="text" id="credithour1" onchange="credhour[0]";>
etc... this extends down to lettergrade 5. I have to run them through the function numgrade (without using a for loop). how do I run these through the same if else construct without making 5 different ones (how can I make one statement that will work for 5 diffferent id's)?

Iterate through the elements and bind them to the onchange callback:
var $ = document;
var lettergrade = [];
[].slice.call($.querySelectorAll('.lettergrade')).forEach(function(el, index) {
el.onchange = function() {
numgrade(index, this.value);
}
});
function numgrade(index, value) {
lettergrade[index] = value;
$.getElementById('output').innerText = JSON.stringify(lettergrade);
}
<input type="text" class="lettergrade" id="lettergrade1" placeholder="1">
<input type="text" class="lettergrade" id="lettergrade2" placeholder="2">
<input type="text" class="lettergrade" id="lettergrade3" placeholder="3">
<input type="text" class="lettergrade" id="lettergrade4" placeholder="4">
<input type="text" class="lettergrade" id="lettergrade5" placeholder="5">
<output id="output"></output>

Related

How can I access these form values?

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

Javascript get value of current number input field

I am trying to make a shopping cart. Now i want to update the price of the item when the amount is changed, but when there are more than one items the onchange method only reacts on the first one. They have the same name. I can give them an other name but how will i then get the name of that input field.
I hope someone can help me with this.
Thanks in advance.
function updatePrice() {
var element = this;
console.log(element.value);
}
Your onchange event should iterate over all input fields.
If you give your fields a common identifier (a data-id attribute or a class name), then the process is quite trivial:
document.body.addEventListener("change", ()=> calc());
function calc(){
let items = document.querySelectorAll(".inp");
let total = 0.0;
for (let i = 0; i < items.length; i++) {
total += parseFloat(items[i].value);
}
document.querySelector(".result").value = total.toFixed(2);
}
calc();
<input type="text" class="inp" value="10.00">
<input type="text" class="inp" value="15.00">
<input type="text" class="inp" value="50.99">
<p>Result: <input type="text" class="result" value="00.00"></p>

Javascript replace string with values from dom object

Im trying to make a formula dynamic and also the input fields. First problem is to change the (c1 + d2) into values like (1 + 2) depending on what is the value in input. consider that tdinput is dynamic so I can add as many as I can and formula can change anytime.
<input class="tdinput" type="text" data-key="c1">
<input class="tdinput" type="text" data-key="d2">
<input type="text" data-formula="(c1 + d2)">
<script>
$('.tdinput').on('change', function() {
var key = $(this).attr('data-key');
$('[data-formula*="+key+"]').each(function() {
//now here goes to change the data-formula by inputted values
//calculate using eval()
});
});
</script>
You need to make a more modular approach with this.
And make good use of the javascript jquery api you're using.
When a variable is defined by data-something-something you can access it by jQuerySelectedElement.data('something-something')
Now, eval is evil, but when you sanitise your input variables(in this case by parseInt) you should be relatively save from xss inputs etc..
What happens is, all the variables are inserted as an property in an object t.
then eval will call and and access all the objects in t and do the calculation.
Only requirement is that you define all the variables not as just c2, but as t.c2 in your key definition properties.
have a look below at the play with the data properties and the eval.
When using eval ALWAYS make sure you only eval 'safe' data! Don't eval strings if you plan to safe user input! you open your site for XSS attacks then.
$('[data-formula]').on('keyup', function() {
var $this = $(this);
var formulaName = $this.data('formula');
var $output = $('[data-formula-name="'+formulaName+'"]');
var formula = $output.data('formula-calc');
var t = {};
var keys = [];
$select = $('[data-formula="'+formulaName+'"]');
$select.each(function(index,elem) {
var $elem = $(elem);
var key = $elem.data('key');
t[key] = parseFloat($elem.val());
keys.push(key);
if(isNaN(t[key])) {
t[key]=0;
}
});
for(var c=0;c<keys.length;c++) {
formula = formula.replace(new RegExp(keys[c],'g'),'t.'+keys[c]);
}
var result = 0;
eval('result = '+formula)
$output.val(result)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
sum:
<input class="tdinput" type="text" data-formula="sum" data-key="c1">
<input class="tdinput" type="text" data-formula="sum" data-key="d2">
<input type="text" data-formula-name="sum" data-formula-calc="(c1 + d2)" disabled>
<BR/>
xor
<input class="tdinput" type="text" data-formula="pow" data-key="c1">
<input class="tdinput" type="text" data-formula="pow" data-key="d2">
<input type="text" data-formula-name="pow" data-formula-calc="(c1 ^ d2)" disabled>
<BR/>
sub
<input class="tdinput" type="text" data-formula="sub" data-key="c1">
<input class="tdinput" type="text" data-formula="sub" data-key="d2">
<input type="text" data-formula-name="sub" data-formula-calc="(c1 - d2)" disabled>
<BR/>
silly
<input class="tdinput" type="text" data-formula="silly" data-key="c1">
<input class="tdinput" type="text" data-formula="silly" data-key="d2">
<input type="text" data-formula-name="silly" data-formula-calc="(c1 / d2 * 3.14567891546)" disabled>
You can use eval().
Logic
Fetch formula and save it in string
Get all valid keys
Replace keys with value in formula
Use eval() to process it
Sample
JSFiddle
$("#btnCalculate").on("click", function() {
var $f = $("input[data-formula]");
var formula = $f.data("formula");
formula.split(/[^a-z0-9]/gi)
.forEach(function(el) {
if (el) {
let v = $("[data-key='" + el + "']").val();
formula = formula.replace(el, v);
}
});
var result = eval(formula);
console.log(result)
$f.val(result)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input class="tdinput" type="text" data-key="c1">
<input class="tdinput" type="text" data-key="d2">
<br/>
<input type="text" data-formula="(c1 + d2)">
<button id="btnCalculate">calculate</button>
Reference
Eval's alternate for string calculation.
Why using eval is not a good idea

Change multiple hidden fields on radio selection

My app is based on Python 3.4 and Flask, but I need to use JavaScript to dynamically change the values of hidden fields. I am not familiar with JavaScript and I don't know why my code isn't working.
In one of my templates I have a very simple payment form that allows the user to select a single bundle of credits using radio buttons (I stripped out the CSS and form action):
<form>
<input id="amount" value="price_list.price1" type="radio" name="amount">
<input id="amount" value="price_list.price2" type="radio" name="amount">
<input id="amount" value="price_list.price3" type="radio" name="amount">
<input id="amount" value="price_list.price4" type="radio" name="amount">
<input id="item_name" type="hidden" name="item_name" value="">
<input id="item_description" type="hidden" name="item_description" value="">
<input id="custom_int1" type="hidden" name="custom_int1" value=0>
<input id="payment" type=submit value=Payment>
</form>
The "price_list.price1" fields refer to a dynamic price, set by the system. This changes hourly, but each of the entries point to a given number of credits.
Due to the requirements of the payment processor I use, I need to change three hidden fields depending on the selection made namely item_name, item_description and custom_int1 (which represents x number of credits bought).
I referenced the following answers:
Dynamically Change Multiple Hidden Form Fields
Setting a form variable value before submitting
Jquery Onclick Change hidden parameter and submit
What I ended up with is an attempt to use jQuery to change the values. The code is as follows:
<script>
$("#amount").change(function () {
// Get a local reference to the JQuery-wrapped select and hidden field elements:
var sel = $(this);
var set_name = $("input[name='item_name']");
var set_description = $("input[name='item_description']");
var set_creds = $("input[name='custom_int1']");
// Get the selected option:
var opt = sel.children("[value='" + sel.val() + "']:first");
// Set the values
if (opt.value=={{ price_list.price1 }}) {
set_name.value = '1 Credit';
set_description.value = '1 Credit';
set_creds.value = 1;
} else if (opt.value=={{ price_list.price5 }}) {
set_name.value = '5 Credits';
set_description.value = '5 Credits';
document.getElementById('custom_int1').value = 5;
} else if (opt.value=={{ price_list.price10 }}) {
set_name.value = '10 Credits';
set_description.value = '10 Credits';
set_creds.value = 10;
} else if (opt.value=={{ price_list.price25 }}) {
set_name.value = '25 Credit';
set_description.value = '25 Credit';
set_creds.value = 25;
} else if (get_amount.value=={{ price_list.price50 }}) {
set_name.value = '50 Credits';
set_description.value = '50 Credits';
set_creds.value = 50;
};
});
</script>
I added the script at the bottom of my template right before the <body> tag.
The script does not work to change the hidden fields at all. Any and all help would be greatly appreciated.
Element id's should be unique (amount). Names can be the same. So fix HTML:
<input id="amount1" value="price_list.price1" type="radio" name="amount" />
<input id="amount2" value="price_list.price2" type="radio" name="amount" />
<input id="amount3" value="price_list.price3" type="radio" name="amount" />
<input id="amount4" value="price_list.price4" type="radio" name="amount" />
Fix script:
$(document).ready(function () {
$('[type=radio]').click(function () { //click is right event
//console.log(this.id);//for test purpose
var set_name = $("input[name='item_name']");
var set_description = $("input[name='item_description']");
var set_creds = $("input[name='custom_int1']");
switch (this.id) {//"this" is the element clicked
case 'amount1':
set_name.val('1 Credit');//not set_name.value='...'
set_description.val('1 Credit');
set_creds.val(1);
break;
case 'amount2':
set_name.val('5 Credits');
set_description.val('5 Credits');
set_creds.val(5);
break;
case 'amount3':
set_name.val('10 Credits');
set_description.val('10 Credits');
set_creds.val(10);
break;
case 'amount4':
set_name.val('25 Credits');
set_description.val('25 Credits');
set_creds.val(25);
break;
default:
set_name.val('');
set_description.val('');
set_creds.val(0);
break;
}
});
});
`
The change event is called for all radio buttons, that are changed. To get only the button that is checked, use:
$("#amount:checked").change(function () {
//
}

How to retrieve the value from a radio button in javascript?

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

Categories

Resources