How do you make it calculate using JavaScript/jQuery based on condition:
on radio button 'change' event.
if user clicks "Yes" or "N/A", the value of text boxes with default values next to it will be added and reflected in Total
HTML:
<form>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point1" class="score" value="3">
</fieldset>
<fieldset>
<input type="radio" name="remark[]" value="Yes" class="answer">Yes
<input type="radio" name="remark[]" value="No" class="answer">No
<input type="radio" name="remark[]" class="answer">N/A
<input type="text" name="point2" class="score" value="2">
</fieldset>
Total<input type="text" name="total" class="result">
</form>
Vanilla Javascript
Note: these scripts associate with forms that have the class name calc
This script will associate with the form, so if you have multiple instances each form will calculate separately.
Basically for each form select all input's with a value of 'Yes' which are checked, then find the score for that field set and add it to the total
(Demo)
(function(){
"use strict";
function calculate() {
var forms = document.querySelectorAll('.calc'), form, i;
for (i = 0; form = forms[i]; i++) {
var total = 0;
var inputs = form.querySelectorAll('input[value="Yes"]:checked'), input, x;
for (x = 0; input = inputs[x]; x++) {
total += parseFloat(input.parentElement.lastElementChild.value);
}
form.lastElementChild.value = total;
}
}
calculate();
var inputs = document.querySelectorAll('.calc input'), input, x;
for(x = 0; input = inputs[x]; x++) {
input.onchange = calculate;
}
})();
jQuery
If you would like to use jQuery, this is the same script converted to jQuery
(Demo)
(function(){
"use strict";
function calculate() {
$('.calc').each(function(){
var total = 0;
$('input[value="Yes"]:checked', this).each(function(){
total += parseFloat($('input.score', this.parentElement).val());
});
$('input.result', this).val(total);
});
}
calculate();
$('.calc input').on('change', calculate);
})();
Not sure if I understand correctly, but first you'll need a few changes in your markup, radio groups should have different name so it'll be like remark[0] for first group and remark[1] for the second and so on. The "N/A" radios don't seem to have a value so I've added value="NA" to them. So your HTML will look like:
<form>
<fieldset>
<input type="radio" name="remark[0]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[0]" value="No" class="answer" />No
<input type="radio" name="remark[0]" value="NA" class="answer" />N/A
<input type="text" name="point1" class="score" value="3" />
</fieldset>
<fieldset>
<input type="radio" name="remark[1]" value="Yes" class="answer" />Yes
<input type="radio" name="remark[1]" value="No" class="answer" />No
<input type="radio" name="remark[1]" value="NA" class="answer" />N/A
<input type="text" name="point2" class="score" value="2" />
</fieldset>Total
<input type="text" name="total" class="result" />
</form>
Then we just listen to radio's onchange and if Yes or N/A is selected for each group, we have it's value to the total. I used parseInt on values since they're string and it seemed the values were supposed to work as numbers. (2+3 should be 5 and not 23).
$('form input[type=radio]').on('change', function() {
var total = 0;
$('form fieldset').each(function(i) {
var point = parseInt($(this).find('input[type=text]').val());
var val = $(this).children('[name="remark[' + i + ']"]:checked').val();
if(val == "Yes" || val == "NA")
total += point;
});
$('input[name="total"]').val(total);
});
jsfiddle DEMO
Related
I'm trying to change the URL when I select radio button.
I have found an answer that works for 'select' form elements, but if I apply it to my radio buttons it lists out all the options instead of the one that is selected
My JS
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
So if I select radio1, instead of the URL being displayed as:
/?foo=1
I get:
/?foo=1&foo=2&bar=1&bar=2
How would I modify this to work with radio buttons?
Hi friend you can use if condition when pushing parameters to like below
$('.unitfiltercontrol').change(function(){
var params =[];
$('.unitfiltercontrol').each(function(){
$this=$(this);
if ($(this).prop("checked")) { //get the values of only checked radio buttons
if(!$this.val()=='') params.push($this.data('param')+'='+encodeURIComponent( $this.val() ));
}
});
$('#urlDisplay').text(window.location.href+('?'+params.join('&'))); //print to div for testing
});
Radio button in your case make single selection , so no need to loop each radio , just get in the change the value and data for current clicked , then create object using data-param as key , after that loop thorough keys and create and array of key + values as below ; snippet :
let values = {};
$('.unitfiltercontrol').change(function(e){
let data = $(this).data('param');
let value = this.value;
values[data] = value;
let params = [];
let keys = Object.keys(values);
for(inc = 0; inc < keys.length ; inc ++) {
let key = keys[inc];
params.push(key+'='+encodeURIComponent(values[key]))
}
$('#urlDisplay').text(window.location.href+('?'+params.join('&')));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
My HTML:
<form>
<input id="radio1" type="radio" value="1" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio2" type="radio" value="2" name="foo" data-param="foo" class="unitfiltercontrol">
<input id="radio3" type="radio" value="1" name="bar" data-param="bar" class="unitfiltercontrol">
<input id="radio4" type="radio" value="2" name="bar" data-param="bar" class="unitfiltercontrol">
</form>
<div id="urlDisplay"></div>
<div id="urlDisplay">
</div>
function add_option(){
var tot_option=parseInt($('#tot_option').val());
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var opt="<input type='text' id='opt"+tot_option+"' onblur='chk(this.value,'"+par+"')' name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(ivalue,rad){
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk(this.value,'radio1')" id="opt1" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" onblur="chk(this.value,'radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>
i have multiple input type and one radio button in front of every input i want to remove disabled from radio if my input type have some value if it has no value then add disabled attribute to radio. its working fine in first two input but after that its not working
there were some flaws in your code,
1 you are sending this.value here as a string onblur='chk(this.value,'"+par+"')
2 in this onblur function call there is a problem while sending par as a parameter,
so here I Modified your code a bit and now this is working
function add_option(){
var tot_option=parseInt($('.totalOption').length);
tot_option++;
$('#tot_option').val(tot_option);
var par="'radio"+tot_option+"'";
var onBlur = 'onblur=chk('+ par.toString() +')';
var opt="<input type='text' id='opt"+tot_option+"' class='totalOption' " + onBlur + " name='answers[]' style='width:80%;' onfocus='add_option()'> <input type='radio' id='radio"+tot_option+"' required disabled name='canswer' value='"+tot_option+"'><br><br>";
document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
element.removeAttribute("onfocus");
});
$('#new_option').append(opt);
}
function chk(rad){
if(event.relatedTarget == null)
return;
var SelctedTarget = Number(event.relatedTarget.id[event.relatedTarget.id.length - 1]) - 1;
var ivalue = $('#opt' + SelctedTarget).val();
if(ivalue!=''){
$('#'+rad).removeAttr('disabled');
}else{
$('#'+rad).attr('disabled','disabled');
$('#'+rad).removeAttr('checked','checked');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" style='width:80%;' onblur="chk('radio1')" id="opt1" class="totalOption" name="answers[]">
<input type="radio" id="radio1" disabled required name="canswer" value="1"><br><br>
<input type="text" id="opt2" class="totalOption" onblur="chk('radio2')" style='width:80%;' name="answers[]" onfocus="add_option()">
<input type="radio" id="radio2" required disabled name="canswer" value="2"><br><br>
<span id="new_option"></span>
basically the below code creates a order total in the id="total" span depending on which checkbox/radio buttons are selected. The total is changed by the value of the checkbox/radio buttons however i was wondering if there's any other way to change the total without using the inputs value because its needed in the next part of the form. Maybe another input attribute? I'm just not sure how to go about it.
All help will be greatly appreciated, thank you!
<form action="cart.php" method="post" name="builder">
<input checked="checked" type="radio" name="term" value="12" onclick='check_value(this, 1)' />
<input type="radio" name="term" value="24" onclick='check_value(this, 2)' />
<input type="radio" name="term" value="36" onclick='check_value(this, 3)' />
<input type="checkbox" name="cid[]" value="2" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="3" onclick='check_value(this, "")' />
<input type="checkbox" name="cid[]" value="4" onclick='check_value(this, "")' />
Total Order: $<span id="total">36</span>
</form>
function check_value(curElem, id) {
// calculate Total
var total = 0;
var controls = document.getElementsByTagName('input');
for (var i = 0; i < controls.length; i++) {
if ((controls[i].type === 'radio' || controls[i].type === 'checkbox') && controls[i].checked) {
total = total + parseFloat(controls[i].value);
}
}
document.getElementById("total").innerHTML = total;
//alert("Total: " + total);
}
if you really want to use another attribute, use it
use an attribute of your choice, say nval and access it as controls[i].getAttribute("nval")
otherwise,
you can create plenty of hidden input fields in the page, for each checkbox to hold your value. and use these hidden fields to compute total.
So i have checkboxlist
<input type="checkbox" name="colorc" value="black" />Black<br/><br>
<input type="checkbox" name="colorc" value="brown" />Brown<br/><br>
<input type="checkbox" name="colorc" value="white" />White<br/><br>
<input type="button" id="btnClick" value="Color Change"></button>
and when i press button, checkmark moves to next checkbox, the same i want if we have two checkmarks, but without using JQuery, clear JS. Thanks
I guess this would do:
document.getElementById("btnClick").onclick = function(){
var checkBoxes = document.getElementsByName("colorc");
var checked = checkBoxes[checkBoxes.length - 1].checked;
for(var i = checkBoxes.length-1; i > 0; --i){
checkBoxes[i].checked = checkBoxes[i-1].checked;
}
checkBoxes[0].checked = checked;
}
Demo: http://jsfiddle.net/t231c0ga/1/
The current checked input can be selected as:
input[name=colorc]:checked
The next input can be gotten using the general sibling selector (~):
input[name=colorc]:checked ~ input[name=colorc]
Change your inputs from checkboxes to radio buttons, and use this code. If there's no next input, it defaults to the first input:
document.getElementById('btnClick')
.addEventListener('click',function() {
var next=
document.querySelector(
'input[name=colorc]:checked ~ input[name=colorc]'
) ||
document.querySelector('input[name=colorc]');
next.checked= true;
});
<input type="radio" name="colorc" value="black" checked/>Black<br/><br>
<input type="radio" name="colorc" value="brown" />Brown<br/><br>
<input type="radio" name="colorc" value="white" />White<br/><br>
<input type="button" id="btnClick" value="Color Change"></button>
I have a code like this and I want to compare in a loop the attribute values of name with user entered input stored in variable "user". How can I do this?
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
See this answer for an example of how to loop through radio buttons in native javascript, quoted here for convenience:
<html>
<head>
<script>
var userChoice;
var setUserChoice = function(event) {
event.preventDefault();
var choices = event.target.userChoice;
for (var i =0; i < choices.length; i++) {
if (choices[i].checked) {
userChoice = choices[i].value;
}
}
event.target.choice.value = userChoice;
}
window.onload = function() {
var form = document.getElementById('userInput');
form.addEventListener('submit', setUserChoice, false);
};
</script>
</head>
<body>
<form id="userInput">
<input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
<input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
<input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
<input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
<input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
<input type="submit" value="Enter" /></br>
<output name="choice"></output>
</form>
</body>
</html>
You can compare tha values like in this fiddle: http://jsfiddle.net/5wd8p/
HTML
<form action="demo.html" id="myForm">
<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>
<input type="submit" value="Submit">
</form>
JQuery
$(function () {
// Handler for .ready() called.
var user = "three"; //default value: depends on youur code..
//Loop through each radio element of the DOM
$("input[type=radio]").each(function(){
//Compare values of the "name" attribute and the user var
if (user == $(this).attr("name")){
alert("Same: " + $(this).attr("name"));
}else{
alert("Different: " + $(this).attr("name"));
}
});
});
try this:
document.getElementsByName(user)[0]