Sum dynamic values from input text and radio - javascript

I'm trying to sum the value of an input text changing dynamically with a radio that also changes dynamically. I'm doing something right but also something wrong because it doesn't sum when I want. The sum should show everytime the input text changes and not randomly disappear then you click a radio, just sum them.
the fiddle http://jsfiddle.net/7tFhx/
and the code
<form id="myForm" accept-charset="UTF-8">
<button type="button" class="btn-tt btn-primary btn-lg" disabled>1. Elige el color</button></br>
<label>
<input class="calc" id="fb1" type="radio" name="fb" value="10">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb2" type="radio" name="fb" value="15">
<img src="img/02.jpg"/>
</label>
</br>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>2. Elige las medidas</button></br>
<div class="row">
<div class="col-xs-2">
ancho (cm.)
<input id="ancho" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
alto (cm.)
<input id="alto" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
cantidad
<input id="cantidad" type="text" class="form-control" placeholder="1">
</div>
</div>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>3. Posición mecanismo</button></br>
<label>
<input class="calc" id="fb3" type="radio" name="fb1" value="20">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb4" type="radio" name="fb1" value="35">
<img src="img/02.jpg"/>
</label>
<div>
Total: <span id="price">0</span>€
</div>
</form>
js:
$(function(){
var mecanismoMedida = ['100','200'];
var mecanismoPrecio = ['50','80'];
$('#ancho').on('input',function(){
var j = 1, i = 0;
value = parseInt(($("#ancho").val() / 8) + 1);
for(i = 0; i < mecanismoMedida.length; i++){
if($("#ancho").val() >= mecanismoMedida[i] && $("#ancho").val() <
mecanismoMedida[j]){
value += mecanismoPrecio[i];
break;
} else {
j++;
}
}
$("#price").text(this.value + value);
});
$('#myForm input[type="radio"]').on('change', function () {
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function () {
sum += parseInt(this.value);
});
$("#price").text(sum);
});
});

If it's a simple sum you're after, you can simply run an update code on the keyup and change events of all input elements:
$("input").change(function(){update();}).keyup(function(){update();});
To update them, first you need to check and see which one of the two radio buttons are checked and get its value:
function update(){
var p = 0;
for(var i = 0; i < $(".calc").val(); i++)
{
if($($(".calc")[i]).prop("checked") == true)
{
p += parseInt($($(".calc")[i]).val());
}
}
After that, simply parse the values of the textboxes to integers and add them to the value of the radio button. I created a custom function to do this, because if the boxes are empty, parsing them returns NaN:
p = parseInt(p);
p += parseInt(val2($("#ancho")));
p += parseInt(val2($("#alto")));
p += parseInt(val2($("#cantidad")));
p = parseInt(p);
$("#price").html(p);
}
function val2(elm){
if(isNaN(parseInt($(elm).val())))
return 0;
else
return parseInt($(elm).val());
}
JSFiddle

Related

Radio button selection when building HTML form

I have a simple HTML form that is used for bookings. Once completed it submits the fields via e-mail which can then be automatically uploaded into my Access database with VBA.
The process works fine if there is just text in the form but I want to include radio button choices as well. The problem is that it doesn't include an indication as to which button has been chosen.
The body of the e-mail, if "text" was entered into the text box and choice2 was selected would be:
text
Choice1
Choice2
Choice3
What I would like it to be is:
text
Choice2.
Can this be done?
A simplified version of my code so far is:
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
str += elem[i].value + "\r\n";
}
}
return str;
}
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
You need to check if the element is checked.
And since you're adding it in the same loop as the text field you also need to make sure the element that has to be checked is actually a radio button:
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
But: In your snippet everything is added to the TO field of the mail, is that intended?
function displayRadioValue() {
var ele = document.getElementsByName('Choice');
for (j = 0; j < ele.length; j++) {
if (ele[j].checked)
document.getElementById("result").innerHTML = ele[j].value;
}
}
function btnClick() {
var link = "mailto:username#domain.com" +
"&subject=" + escape("Radio button trial") +
"&body=" + escape(buildForm());
window.location.href = link;
}
function buildForm() {
var str = "";
var elem = document.getElementById('RBT').elements;
for (var i = 1; i < elem.length; i++) {
if (elem[i].type != "button") {
if(elem[i].type != "radio" || elem[i].checked) {
str += elem[i].value + "\r\n";
}
}
}
return str;
}
<html>
<head>
<title>Radio button trial</title>
</head>
<body>
<form id="RBT" name="RBT">
<fieldset>
<p></p>
<legend>Complete the form and\or choose an option</legend><br>
<div>
<label for "text1">Text1</label><br>
<input id="text1" name="text1"><br>
<input type="radio" id="radio1" name="Choice" value="Choice1" checked onclick="displayRadioValue()">
<label for="radio1">Choice1</label><br>
<input type="radio" id="radio2" name="Choice" value="Choice2" onclick="displayRadioValue()">
<label for="radio2">Choice2</label><br>
<input type="radio" id="radio3" name="Choice" value="Choice3" onclick="displayRadioValue()">
<label for="radio3">Choice3</label><br>
<br></div>
<div id="result" name="result" value="result"></div>
</fieldset>
</form>
<BUTTON type=submit onclick="btnClick()" />
<FONT size=5 bold>Submit choice</FONT>
</BUTTON>
</body>
</html>

JavaScript function not working as desired

I'm working with HTML, JavaScript and CSS. The function objective is to create a border-radius attribute in a div element(id="surface"), and assign the value typed in inputs texts(class="chars_1") to it.
HTML
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div class="input_wrapper" id="input_wrapper_bl">
<input type="text" id="input_bl" class="chars_1" value="0" onkeypress="changeSize()">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
JavaScript Function
function changeSize(){
var surface = document.getElementById("surface");
var inputs = document.getElementsByClassName("chars_1");
var total = 0;
for(var x = 0; x == 3; x++){
total += Number(inputs[x].value);
}
surface.style.borderRadius = String(total)+"px";
}
First I selected both elements and assigned it to these 2 variable "surface" and "inputs". "total" being used in the "for structure" to go through every input element and select every value, and afterward convert to Number to the "total" variable.
The idea is to assign to the border-radius attribute the total variable value, which will be converted to a string so it can be recognized as a value.
Have a border
Fix the for loop for (var x = 0; x < inputs.length; x++) {
Here is an upgraded version
const changeSize = (e) => {
const tgt = e.target; // which input
if (tgt.classList.contains("chars_1")) { // ah, one of those
let total = [...document.querySelectorAll(".chars_1")].reduce(
(sum, input) => {
const val = input.value;
sum += val.trim() === "" || isNaN(val) ? 0 : +val; // only add if a number
return sum;
}, 0);
console.log(String(total) + "px")
document.getElementById("surface").style.borderRadius = String(total) + "px";
}
};
window.addEventListener("load", () => { // when page loads
document.getElementById("container").addEventListener("input", changeSize);
});
#surface {
border: 3px solid black;
}
<div id="container">
<div class="input_wrapper" id="input_wrapper_tl">
<input type="text" id="input_tl" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_tr">
<input type="text" id="input_tr" class="chars_1" value="0">
</div>
<div class="input_wrapper" id="input_wrapper_br">
<input type="text" id="input_br" class="chars_1" value="0">
</div>
<div class="input_wrapper " id="input_wrapper_bl ">
<input type="text" id="input_bl " class="chars_1" value="0">
</div>
<div id="surface">
<textarea id="code" readonly="readonly"></textarea>
<div id="options">
<input type="checkbox" checked="true" id="opt_webkit">
<label for="opt_webkit"> Webkit</label>
<input type="checkbox" checked="true" id="opt_gecko">
<label for="opt_gecko"> Gecko</label>
<input type="checkbox" checked="true" id="opt_css3">
<label for="opt_css3"> CSS3</label>
</div>
</div>
for(var x = 0; x == 3; x++)
that loop doesn't even execute,
change x==3 on x<3 or whatever you want to achive.
And I guess you must have border to change it's radious

Get Radio Button Value into another function in javascript

Here is my radio buttons' code:
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>
and I want to get value of button in following script audio src, so by clicking on radio button I can switch between media folder:
function PlayVerse(surat,n) {
var aud=document.getElementById("myaudio");
aud.src= "http://data.quranacademy.com/AUDIOS/Media-/01_"
+TxtFormat(surat,"000")
+"_"
+TxtFormat(n,"000")
+".mp3";
}
var x = document.getElementsByTagName("IMG");
var i;
for (i = 0; i < x.length; i++) {
x[i].style = 'display: inline-block; '
+'border: 1px solid #ddd; '
+'border-radius: 4px; padding: 5px;';
}
Try something like this with plain javascript
function PlayVerse(){
var radio = document.getElementsByName('sp');
var check;
for (var i = 0, length = radio.length; i < length; i++)
{
if (radio[i].checked)
{
console.log(radio[i].value);
check = radio[i].value;
break;
}
}
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
if you want to do something by clicking on radio button it can help you
window.onload=function(){
(function (){
var radios = document.getElementsByName('sp');
radios.forEach(function(radio){
radio.onclick = function(){
alert(this.value);
//do something
}
})
})();
}
Red color
Yelow color
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myRadioRed").value;
//document.getElementById("demo").innerHTML = x;
var radios = document.getElementsByName('colors');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
document.getElementById("demo").innerHTML = radios[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
}
</script>
<input type="radio" name="colors" value="red" id="myRadioRed" onchange="myFunction()" checked="checked" />Red color
<input type="radio" name="colors" value="yellow" id="myRadioYellow" onchange="myFunction()" />Yelow color
<p id="demo"></p>
function PlayVerse() {
var selected_radio_button_value = getRadioButtonValue("sp");
alert(selected_radio_button_value);
}
function getRadioButtonValue(elementName) {
var array1 = document.getElementsByName(elementName), rValue = null;
array1.forEach(function(element) {
if( element.checked ) {
rValue = element.value;
return true;
}
});
return rValue;
}
<div class="col-md-6 alert alert-success" dir="rtl" >Select an Option</br>
<label class="radio">
<input type="radio" name="sp" id="sp1" value="1" checked><span style="margin-right: 30px;">Option-1
</span></label></br>
<label class="radio-inline">
<input type="radio" name="sp" id="sp2" value="2"><span style="margin-right: 30px;">Pption-2
</span></label>
</div>
<button type = "button" onclick="PlayVerse();">Get Radio button value </button>
here you can get value of radio button using javascript i have created an function which will give you value of selected radio button you can store that value in variable and access it anywhere you want you can do it in both way
Here is how you can get value of radio button which one is checked. Get all NodeList by getElementsByName and iterate over each one and check if it is checked.
function getVal(elementName) {
var radios = document.getElementsByName(elementName), rValue = null;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
rValue = radios[i].value;
break;
}
}
console.log(rValue);
}
<div class="col-md-6 alert alert-success" dir="rtl" >
Select an Option <br>
<label class="radio">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp1" value="1" checked>
<span style="margin-right: 30px;">Option-1</span>
</label><br>
<label class="radio-inline">
<input type="radio" onchange="getVal('sp')" name="sp" id="sp2" value="2">
<span style="margin-right: 30px;">Option-2</span>
</label>
</div>

Output form within html page

I want to print the submitted input elements within the same page below the html form. The checked checkbox elements should all be printed. The image element can be avoided.
The function does not seem to be working.
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = y;
var b = document.getElementByName("passwords").value;
document.getElementById("display1").innerHTML = y;
var c = document.getElementByName("gender");
var i;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i] checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementByName("cities").value;
document.getElementById("display3").innerHTML = e;
}
<form name="myForm">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit" onSubmit="validateform(myForm);">
</fieldset>
<p id="display"></p>//display the values submitted within the html page
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>
getElementsByName - plural and when accessing the first, use [0] like
document.getElementsByName("cities")[0].value
missing a dot in d[i].checked
move the onSubmit="validateform(myForm);" to the form tag and do onSubmit="return validateForm(this);" and add return false;
validateForm misspelled in event handler (lower case f)
y missing
ans not defined
function validateForm(myForm) {
var a = document.getElementById("fname").value;
document.getElementById("display").innerHTML = a;
var b = document.getElementsByName("passwords").value;
document.getElementById("display1").innerHTML = a;
var c = document.getElementsByName("gender");
var i, ans;
for (i = 0; i < c.length; ++i) {
if (c[i].checked)
document.getElementById("display1").innerHTML = c[i].value; //looping through radio buttons
}
var d = document.getElementsByName("hobbies");
for (i = 0; i < d.length; ++i) {
if (d[i].checked)
ans = ans + d[i].value; //looping through checkboxes and adding to display in display 2 id.
}
document.getElementById("display2").innerHTML = ans;
var e = document.getElementsByName("cities")[0].value;
document.getElementById("display3").innerHTML = e;
return false; // normally when error but here to stay on page
}
<form name="myForm" onSubmit="return validateForm(this);">
<fieldset>
<legend>Personal Details</legend>
Name:
<input type="text" id="fname" <br>Password:
<input type="password" name="password" id="passwords" />
<br>Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female</input>
<br>Hobbies:
<input type="radio" name="hobbies" value="Reading" />Reading
<input type="radio" name="hobbies" value="Writing" />Writing</input>
<br>City:
<select name="cities" />
<option>Surat</option>
<option>Ahmedabad</option>
<option>Rajkot</option>
<option>Vadodra</option>
</select>
<br>Image:
<input type="file" accept="image/*" value="image" style="margin:0px 10px 10px 100px; margin:absolute;" />
</form>
<br>
<input type="Submit" value="Submit">
</fieldset>
<p id="display"></p><!-- display the values submitted within the html page -->
<p id="display1"></p>
<p id="display2"></p>
<p id="display3"></p>

How to calculate the total value of each section separately: Jquery

I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});

Categories