How to select any check box in multiple and submit data - javascript

I have written code in xhtml for submitting checkboxes data,resetting the checkboxes data..
my form data is
<div class="outer">
<div class="pg15outer">
<div class="pgleft">
<p class=" pg2text"><img src="images/icon_assess.png" alt="images" /></p>
</div>
<div class="pgrgt pg2text">
<p class=""><span class="activespan">Self Assessment 3</span></p>
</div>
</div>
<p class="text">Try to answer the following questions without referring to your notes. If you find this difficult then consult your notes and make sure you can answer the questions.</p>
<div id="questionsNo_1_1">
<!-- questionsNo_chapterNo_quesNo-->
<p class="text" id="question1">1. An objective of record keeping is to ensure that a client of an accountable institution can be fully identified and located.</p>
<!--<li><label for="ques11"><javascript></label></li>-->
<p class="text">
<input type="checkbox" value="Yes" id="ques11" name="radiobutton" class="option_1" />
<label for="ques11">True</label>
<span class="hide" id="ans_1_1">Answer: True</span>
<span id="rite11" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong11" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
<p class="text">
<input type="checkbox" value="No" id="ques12" name="radiobutton" class="option_2" />
<label for="ques12">False</label>
<span id="rite12" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong12" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
</div>
<div id="questionsNo_1_2">
<!-- questionsNo_chapterNo_quesNo-->
<p class="text" id="question2">2. The records that an accountable institution is required to maintain and retain may be kept in either paper or electronic form.</p>
<p class="text">
<input type="checkbox" value="No" id="ques13" name="radiobutton" class="option_1" />
<label for="ques13">True</label>
<span id="rite13" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong13" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
<p class="text">
<input type="checkbox" value="Yes" id="ques14" name="radiobutton" class="option_2" />
<label for="ques14">False</label>
<span class="hide" id="ans_1_2">Answer: False</span>
<span id="rite14" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong14" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
</div>
<div id="mainalign">
<span class="chk-btn button" onclick="" id="_submit">Submit</span>
<span class="jumble-rst button" onclick="reset_fu(3)" style="margin-left:1%">Reset</span>
<span class="button" onclick="checkans()">Answers</span>
</div>
</div>
<p class="pg-no1">16</p>
in this, There are two questions each contains two check boxes , I want to select only one checkbox at a time , In this code two checkboxes are selecting.
And for submitting and resetting I write functions ,resetting is not working,
<script>
function check(numQues) {
for (var i = 1; i <= numQues; i++) {
for (var j = 1; j <= 4; j++) {
document.getElementById("rite" + i + j).style.display = "none";
document.getElementById("wrong" + i + j).style.display = "none";
if (document.getElementById("ques" + i + j).checked) {
var result = document.getElementById("ques" + i + j).value;
if (result == 'yes')
{
document.getElementById("rite" + i + j).style.display = "inline";
document.getElementById("wrong" + i + j).style.display = "none";
} else {
document.getElementById("rite" + i + j).style.display = "none";
document.getElementById("wrong" + i + j).style.display = "inline";
}
}
}
}
}
function reset_fu(numQues) {
for (var i = 1; i <= numQues; i++) {
for (var j = 1; j <= 4; j++) {
document.getElementById("ques" + i + j).checked = "";
document.getElementById("rite" + i + j).style.display = "none";
document.getElementById("wrong" + i + j).style.display = "none";
document.getElementById("ans1").style.display = "none";
document.getElementById("ans2").style.display = "none";
}
}
}
function checkans() {
document.getElementById("ans1").style.display = "inline";
document.getElementById("ans2").style.display = "inline";
}
</script>
How to reset the checked checkboxes, only one check box has to select in each question

Here is an easy solution
$(document).ready(function(){
$('#questionsNo_1_1 input:checkbox').click(function() {
$('#questionsNo_1_1 input:checkbox').not(this).prop('checked', false);
});
$('#questionsNo_1_2 input:checkbox').click(function() {
$('#questionsNo_1_2 input:checkbox').not(this).prop('checked', false);
});
});
Here is the fiddle
As I don't have the CSS classes that you have defined the styling won't apply

Related

Adding and removing numbers from the total box onchange

I am trying to add and remove the price when the check box is checked and unchecked. I am using an event listener function but it is not working how I want it to. How will I be able to click on either of the check boxes to add to the total and remove when unchecked?
HTML:
window.addEventListener('load', function() {
'use strict';
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
var total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
if (checkbox.checked) {
total += parseFloat(checkbox.dataset.price);
form.total.value = total;
var boxTotal = parseFloat(total);
boxTotal = boxTotal.toFixed(2);
form.total.value = boxTotal;
} else {
form.total.value -= this.value;
}
}
});
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Because you're summing up all checkboxes associated prices on change, you shouldn't have the } else { form.total.value -= this.value; - not only does this refer to the form (which doesn't have a .value), you also don't care at all about the unchecked prices, because they don't affect final value after a change event anyway.
You can select only the checked checkboxes in your query string with the :checked psuedo-selector - this will let you leave out the if (checkbox.checked) part.
You also might consider coming up with the total number once, and then assigning to the input's value once, rather than on every iteration:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
let total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]:checked');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
total += Number(checkbox.dataset.price);
}
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Also, to be a bit more functional, you might use Array.prototype.reduce to calculate the total, rather than a for loop:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
const total = Array.prototype.reduce.call(
form.querySelectorAll('input[data-price][type=checkbox]:checked'),
(a, checkbox) => a + Number(checkbox.dataset.price),
0
);
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>

How to add new option to select if radiobutton is changed using jQuery

I try to add new "items" to a given <select> using jQuery.
If one of the both possibiities (Countries) is checked, the "select-Box" below should change the list <options>.
This is my code:
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
This code won`t run. Why?
I believe what you want is change option for combobox depending on the selected radio button. What you need to do is to clear the combobox options first before adding new options.
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
} else if(val == "ger") {
for (var i = 1; i < 5; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
}
});
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<div id="country">
<h2>Land</h2>
<form id="selectPowerCost" name="selectPowerCost">
<fieldset>
<div class="col col-md-12" id="selectCountry">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label> <input class="left-20" id="radio-1" name="radio-1" type="radio" value="aut">
</div><!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label> <input class="left-20" id="radio-2" name="radio-1" type="radio" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select class="selectpicker" id="selectCosts" name="selectCosts" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
</body>
</html>
You only check if the country Austria is checked and not if Germany is checked.
Also i would add $("#selectCosts").empty(); before the loop to empty the items inside the list.
EDIT
You could also replace this part:
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
With this suggestion made by #Taufik Nur Rahmanda:
$('#selectCosts').append('<option value="'+i+'">Option '+i+'</option>');
$("input:radio[name=radio-1]").change(function() {
//alert ($(this).val());
if ($(this).val() == "aut" || $(this).val() == "ger") {
$("#selectCosts").empty();
for (i = 18; i < 21; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Option " + i
}));
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="country">
<h2>Land</h2>
<form name="selectPowerCost">
<fieldset>
<div id="selectCountry" class="col col-md-12">
<!-- Österreich -->
<div class="radio pull-left" style="margin-top: -5px; min-width:150px;">
<label for="radio-1">Österreich<span class="country-aut"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-1" value="aut">
</div>
<!-- Deutschland -->
<div class="radio pull-left left-10" style="min-width:150px;">
<label for="radio-2">Deutschland<span class="country-ger"> </span></label>
<input class="left-20" type="radio" name="radio-1" id="radio-2" value="ger">
</div>
</div>
</fieldset>
</form>
</div>
<div id="stromkostenProKW">
<h2>Stromkosten pro KWh</h2>
<div class="pull-left" style="margin-top: -5px">
<form>
<select id="selectCosts" name="selectCosts" class="selectpicker" title="Wählen Sie Ihre Stromkosten pro KWh">
</select>
</form>
</div>
</div>
Hey Guys/Girls/Developer!
Thx a lot for your support.
I solved my Problem. All suggestions are working fine.
I had included a "bootstrap-select.min.js" which made some conflicts and result in problems. As I excluded this .js-File everything works fine.
Thank you very much!
Here is the code I am using (only JS):
function init() {
$("input:radio[name=radio-1]").change(function() {
var val = $(this).val();
$('#selectCosts').find('option').remove().end();
if (val == "aut") {
for (i = 16; i < 22; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
} else if(val == "ger") {
for (var i = 26; i < 33; i++) {
$('#selectCosts').append($('<option>', {
value: i,
text: "Kosten pro KWh: " + i + " ct"
}));
}
}
});
}
document.addEventListener('DOMContentLoaded', init);

How to get selected check box value to a variable in script

I have a html form content with two check boxes like
<p class="text">
<input type="checkbox" value="Yes" id="ques11" name="radiobutton" class="option_1" />
<label for="ques11">True</label>
<span class="hide" id="ans1">Answer: True</span>
<span id="rite11" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong11" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
<p class="text">
<input type="checkbox" value="No" id="ques12" name="radiobutton" class="option_2" />
<label for="ques12">False</label>
<span id="rite12" class="hide"><img class="imgsize" src="images/ans_correct.png"/></span>
<span id="wrong12" class="hide"><img class="imgsize" src="images/ans_wrong.png"/></span> </p>
for this i have written code to get the checkboxes
$(function(){
$('#_submit').on('click', function(){
completedata = 'selected_';
$('input[type="checkbox"]').each(function(){
var quesNo = $(this).closest("div[id^='questionsNo_']").attr('id').split('_');
var chapterId = quesNo[1];
var questionId = quesNo[2];
var optionId = $(this).attr('class').split('_')[1];
var currentAns = $(this).val();
completedata += 'choose'+','+chapterId + ',' + questionId + ',' + optionId + ',' + currentAns + '_';
completedata = completedata.substr(0, completedata.length - 1) + '_selectedEnd';
if(completedata == "selected_selectedEnd"){
document.getElementById("selids").innerHTML="";
}
else {
$('#selids').text(completedata);
}
In this line i have to get which checkbox is checked, how to get that using this script. Please help me how to do that.
var optionId = $(this).attr('class').split('_')[1];
i want which check box is clicked based on class="option_1" or class="option_2".
Try this:
$("input[name='radiobutton']").click(function(){
if($(this).is(':checked'))
{
// checked
}
else
{
// unchecked
}
});

How to append auto-incremented number for label text

I am implementing an extend form function, in which there is a label text (marked in html) that I hope to include a number to increment.
So every time when a form is extended/cloned, the label text in the extended form shows Student 1, Student 2... accordingly. Can I be advised how to do that?
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />
To answer the question directly, you just need to find the appropriate <label> and update the innerHTML (see below).
However, what you are doing here can be achieved using the new HTML5 template element without having to hide <span> elements. Additionally, you have to remember that when you remove a student, the counter isn't going to decrease, nor are the already added students going to update. If you want that kind of functionality, you may want to look into a Javascript MVVM, like Angular.
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
// Find the label here and update the innerHTML appropriately
newField.querySelector(".col-lg-12 label").innerHTML = "Student " + counter;
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />

Cannot read property 'Value'

I just literally spent most of my day trying to fix this issue.
A little background: I'm designing a mutli-step form, one of the steps is to choose between two options (both are radio buttons).
So for example, step 1 is to choose the gender "male" or "female" and the second step is to enter something in the text input.
The problem I have is that when I choose a gender, it doesn't go to the second step. I also had an issue where it did go to the second step but the value returned was "unidentified".
$('#gpadding input:radio').addClass('input_hide');
$('label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
var gender, fname, lname;
function _(x) {
return document.getElementById(x);
}
function next1() {
gender = _("gender").value;
_("step1").style.display = "none";
_("step2").style.display = "block";
}
function next2() {
fname = _("firstname").value;
lname = _("lastname").value;
_("step2").style.display = "none";
_("show_all_data").style.display = "block";
_("display_gender").innerHTML = gender;
_("display_fname").innerHTML = fname;
_("display_lname").innerHTML = lname;
}
<div class="step" id="step1">
<h3>Gender</h3>
<div>
<div class="gender-box">
<div id="gpadding">
<input type="radio" name="gender" id="gender" value="m" />
<label for="malereg"><img src="images/icons/male-register.png" /><span>MALE</span></label>
<input type="radio" name="gender" id="gender" value="f" />
<label for="femalereg"><img src="images/icons/female-register.png" /><span>FEMALE</span></label>
</div>
</div>
<button onclick="next1()">Next</button>
<button id="bstep" class="md-close">Close</button>
<div class="clearfix"></div>
</div>
</div>
<div class="step" id="step2">
<h3>Name</h3>
<div>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<button onclick="next2()">Next</button>
<button id="bstep" class="md-close">Close</button>
<div class="clearfix"></div>
</div>
</div>
<div class="step" id="show_all_data">
<h3>Complete</h3>
<span id="display_gender"></span> <br />
<span id="display_fname"></span> <br />
<span id="display_lname"></span> <br />
<button onlick="submitForm()">Register</button>
<button id="bstep" class="md-close">Close</button>
</div>
You cannot use <div> inside a <label>.
Make sure the ID
selectors you're targeting they actually exist.
You can wrap all you need inside a label without the need to use for and id attributes:
function _(x) { return document.getElementById(x); }
function _n(x) { return document.getElementsByName(x); } //Needed to get elements by Name
var gender, input;
function next1() {
var radio = _n("gender"); // get the elements by Name !!
for (var i=0, j=radio.length; i<j; i++) { // Loop all radio buttons
if (radio[i].checked) { // If one is Checked...
gender = radio[i].value; // All fine
_("step1").style.display = "none";
_("step2").style.display = "block";
break; // and exit the loop.
}
}
if(!gender) return alert("Please select a gender"); // If no value, alert something
}
function next2() {
input = _("input").value; // Use the right ID !!!!!
if(!input) return alert("Please enter your name");
_("step2").style.display = "none";
_("show_data").style.display = "block";
_("display_gender").innerHTML = gender;
_("display_input").innerHTML = input;
}
label{display:block;}
#step1, #step2m #show_data{
background:#eee;
width:200px;
padding:30px;
}
#step2, #show_data{display:none;}
<div id="step1">
<label>
<input type="radio" name="gender" value="m">
<img src="images/icon/male.png" />
<span>MALE</span>
</label>
<label>
<input type="radio" name="gender" value="f">
<img src="img/icon/female.png">
<span>FEMALE</span>
</label>
<button onclick="next1()">Next</button>
</div>
<div id="step2">
<label>
Enter your name:
<input type="text" id="input" name="input">
</label>
<button onclick="next2()">Next</button>
</div>
<div id="show_data">
<p id="display_gender"></p>
<p id="display_input"></p>
</div>
Perhaps change your code to:
function next1() {
var gender_controls = document.getElementsByName("gender");
gender = gender_controls[0].checked ? gender_controls[0].value : gender_controls[1].value;
_("step1").style.display = "none";
_("step2").style.display = "block";
}

Categories

Resources