Getting all child input elements within a div - javascript

I am trying to get all the values of the input fields. The issue is all of the <input type=radio/> are dynamic and can increase or decrease at any time.
So I am starting with the main DI and going from there. The problem I have now is I am not getting the input radio buttons values.
So here are the steps I am intending to accomplish:
If any radio button is selected, pass its value to the checkbox value,
If the radio button is selected and the checkbox is not selected, do not pass to the checkbox value
I am looking for a solution in JavaScript only - do not use jQuery
Here is my jsFiddle code
HTML
<div style="display: block;" id="mymainDiv" class="fullFloat">
<input type="hidden" value="1" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">UPS<a class="fRight" onclick="localG('10',false,0,false,'UPS','1','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_UPS"><div class="loadingcheckout"></div></div>
<div id="Price_UPS">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11098" id="deliveryMethodId_1" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
UPS Ground (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="UPS_11098">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="UPS">
</div>
<input type="hidden" value="2" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">Standard<a class="fRight" onclick="localG('20',false,0,false,'Standard','2','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_Standard"><div class="loadingcheckout"></div></div>
<div id="Price_Standard">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11117" id="deliveryMethodId_2" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
Standard Delivery - 2-3 Day Delivery at Ground Rate (Order by 9:30 PM EST)
</span>
<div class="wrapRight">
<div id="Standard_11117">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="Standard">
</div>
<input type="hidden" value="3" id="startIdxShMdeCarWisevId" name="startIdxShMdeCarWise">
<div class="subTitle">FedEx<a class="fRight" onclick="localG('190',false,0,false,'FedEx','3','$');" href="javascript:void(0);">Show Prices</a></div>
<div style="display:none;" id="Wheel_FedEx"><div class="loadingcheckout"></div></div>
<div id="Price_FedEx">
</div>
<div class="wrapLeft wrapClear">
<div class="wrapleft">
<label class="">
<input type="radio" value="11088" id="deliveryMethodId_3" name="deliveryMethodId" class="section" data-mask="" data-rev="" data-rel="false" data-carrier="">
<span>
FedEx Ground (Order by 8:00 PM EST)
</span>
<div class="wrapRight">
<div id="FedEx_11088">
</div>
</div>
</label>
</div>
<input type="text" value="1" id="FedEx">
</div>
</div>
<input type="checkbox" name="shipmode" id="shipmode" value="" onclick="getpref('mymainDiv');">Get Value
JS Code
This executes when the checkbox is clicked:
function getpref(val) {
var wr = document.getElementById(val);
childElements = wr.childNodes;
//alert(childElements);
for(var i = childElements.length-1; i>=0; i--){
var elem = childElements[i];
console.log(elem.id);
if(elem.id && elem.id.indexOf(val+'_')==0){
elem.style.display = 'block';
}
}
//alert(val);
}

You can directly access input nodes in your DIV with getElementsByTagName
function getpref(val) {
var divNode = document.getElementById(val);
var inputNodes = divNode.getElementsByTagName('INPUT');
for(var i = 0; i < inputNodes.length; ++i){
var inputNode = inputNodes[i];
if(inputNode.type == 'radio') {
//Do whatever you want
if(inputNode.checked) {
//Do whatever you want
}
}
}
}
Example: http://jsfiddle.net/88vp0jLw/1/

You can use getElementsByName to get you all of the radio buttons by name='deliveryMethodId' and then go from there:
function getpref(val) {
var radioButtons = document.getElementById(val).getElementsByName("deliveryMethodId");
for(var i = radioButtons.length-1; i>=0; i--)
{
var radioButton = radioButtons[i];
if(radioButton.checked)
console.log(radioButton.id + " is selected ");
}
}

Related

How to get the checked radio button in JS?

I have seen that this works for most of users, but for some reason it doesn't for me. I use Google Chrome.
radioBut = document.querySelector(".rad-design")
getColor = function(){
for (i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i)
}
}
Html
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design"></div>
</label>
</div>
</form>
The selector should be document.querySelectorAll to get inputs as array and you should target to .rad-input class which is the input and not .rad-design which is the label. Also you should use checked for the inputs to make the input checked, its not check. Also you cannot set checked to two inputs with same name. If thats done only the last input with that name will be checked.
Working Fiddle
const radioBut = document.querySelectorAll(".rad-input")
getColor = function () {
for (i = 0; i < radioBut.length; i++) {
if (radioBut[i].checked) {
console.log(radioBut[i])
}
}
}
<form id="rad">
<div class="radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" checked name="colList">
<div class="rad-design">One</div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" name="colList">
<div class="rad-design">Two</div>
</label>
</div>
<button type="button" onclick="getColor()">getColor</button>
</form>
document.querySelector returns just one element not an array/list, so in the for loop at i<radioBut.length radioBut.length is undefined, you need to use document.querySelectorAll() instead.
Also I noticed you have selected the div and not the input and you have a couple of syntax errors.
Maybe this can help you:
const radioBut = document.querySelectorAll(".rad-input")
const getColor = function(){
for (let i=0; i<radioBut.length; i++){
if (radioBut[i].checked){
console.log(radioBut[i].value)
}
}
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>
Another options is to use the form element functionality
const form = document.getElementById('rad');
const getColor = function(){
return form.colList.value;
}
console.log(getColor())
<form id = "rad">
<div class = "radioAll">
<label class="rad-label">
<input type="radio" class="rad-input" value='A' name="colList">
<div class="rad-design"></div>
</label>
<label class="rad-label">
<input type="radio" class="rad-input" value='B' name="colList" checked>
<div class="rad-design"></div>
</label>
</div>
</form>

How to replace HTML Tags using Javascript or JQuery without any Class name or ID

Please help me replacing below html code
Original Code
<div class="multiAttType">
<input type="radio" id="Radio7_1" value="Google">
<label for="Radio7_1" class="radioChoice">Google</label>
</div>
<div class="multiAttType">
<input type="radio" id="Radio7_2" value="Bing">
<label for="Radio7_2" class="radioChoice">Bing</label>
</div>
On PageLoad It Should Be Changed To
<div class="multiAttType">
<input type="radio" id="Radio7_1" value="Google">
<span class="sameclass">Google Link 1</span>
</div>
<div class="multiAttType">
<input type="radio" id="Radio7_2" value="Bing">
<span class="sameclass">Bing Link 2</span>
</div>
You can achieve this using :contains() selector in jquery.
Example : $('label:contains("Google")')
Now use replaceWith function from jquery to replace the html content.
Updated the code snippet to replace the html content on page load.
function replaceHtml(){
$('label:contains("Google")').replaceWith('<span class="sameclass">Google Link 1</span>')
$('label:contains("Bing")').replaceWith('<span class="sameclass">Bing Link 2</span>')
}
$(document).ready(function(){
//calling the replace function on page load
replaceHtml();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiAttType">
<input type="radio" id="Radio7_1" value="Google">
<label for="Radio7_1" class="radioChoice">Google</label>
</div>
<div class="multiAttType">
<input type="radio" id="Radio7_2" value="Bing">
<label for="Radio7_2" class="radioChoice">Bing</label>
</div>
<button onclick="replaceHtml()">Replace</button>
this is a static way
window.onload = function() {
var multAtt = document.getElementsByClassName('multiAttType');
for (var i = 0; i < multAtt.length; i++) {
var children = multAtt[i].children;
for (var j = 0; j < children.length; j++) {
if(children[j].innerHTML == 'Google' && children[j].tagName == 'LABEL') {
multAtt[i].removeChild(multAtt[i].children[j]);
multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Google Link 1</span>');
} else if ( children[j].innerHTML == 'Bing' && children[j].tagName == 'LABEL') {
multAtt[i].removeChild(multAtt[i].children[j]);
multAtt[i].insertAdjacentHTML('afterend', '<span class="sameclass">Bing Link 2</span>');
}
}
}
}
<div class="multiAttType">
<input type="radio" id="Radio7_1" value="Google">
<label for="Radio7_1" class="radioChoice">Google</label>
</div>
<div class="multiAttType">
<input type="radio" id="Radio7_2" value="Bing">
<label for="Radio7_2" class="radioChoice">Bing</label>
</div>

JQuery - Allow Specific 2 Checkboxes to be Selected

I only want 1 checkbox to be selected - UNLESS its checkbox 3 AND 4 - then I want to allow these 2 checkboxes to be selected. This is the only time I want 2 checkboxes allowed.
I have a working example of only allowing 1 checkbox. see the jsfiddle...
https://jsfiddle.net/rbla/s1setkfe/3/
I need to allow #3 and #4 to be selected
$(function() {
$('#submit').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must check at least one reason.");
return false;
}
});
});
// No more than 1 checkbox allowed
var limit = 1;
$('input.sing-chbx').on('change', function(evt) {
if ($("input[name='choice[]']:checked").length > limit) {
this.checked = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="formname" method="post" autocomplete="off" id="update">
<div class="group" style="margin:0.5em 0;">
<div>
<div id="one">
<input type="checkbox" class="sing-chbx" id="choice" name="choice[]" value="01">
<label>One</label><br/>
</div>
<div id="two">
<input type="checkbox" class="sing-chbx" name="choice[]" value="02">
<label>Two</label><br/>
</div>
<div id="three">
<input type="checkbox" class="sing-chbx" name="choice[]" value="03">
<label>Three</label><br/>
</div>
<div id="four">
<input type="checkbox" class="sing-chbx" name="choice[]" value="04">
<label>Four</label><br/>
</div>
<div id="five">
<input type="checkbox" class="sing-chbx" name="choice[]" value="05">
<label>Five</label><br/>
</div>
</div>
</div>
<input type="submit" id="submit" value="Confirm Submission">
</form>
I have created a fiddle for you demonstrating my solution.
I changed the way you're handling this to be more visual to the user with what is happening by actually disabling the other checkboxes.
I added new classes to all of the checkboxes that only allow one selection, and added a separate class to the checkboxes that allow two selections.
After that you just need to check the class of the clicked checkbox, and disable the others depending on whether or not it was a select-one or select-two checkbox:
var canOnlySelectOne = $(this).hasClass("select-one");
if (canOnlySelectOne) {
$(".sing-chbx").not(this).attr("disabled", this.checked);
} else if ($(this).hasClass("select-two")) {
if ($(".select-two:checked").length > 0) {
$(".select-one").attr("disabled", true);
} else {
$(".select-one").attr("disabled", this.checked);
}
}
We simply enable/disable the other checkboxes based on whether or not the clicked one (this) is checked or not. If the checkbox has a class of select-two then we check if any of the select-two checkboxes are checked, and act accordingly.
Instead of preventing user to check - just uncheck prev selection
You have 3 cases: 03 is clicked, 04 is clicked, something else clicked
Here is the updated code:
$(function() {
$('#submit').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must check at least one reason.");
return false;
}
});
});
// No more than 1 checkbox allowed except 3 & 4
$('input.sing-chbx').on('change', function(evt) {
var me = $(this).val();
$('input.sing-chbx').each(function(ix){
var el = $(this);
if(el.val()!= me) {
if(me == "03") {
// case 1: me == '03' - disable all but '04'
if( el.val() != "04") {
el.prop('checked', false);
}
} else if(me == "04") {
// case 2: me == '04' - disable all but '03'
if(el.val() != "03") {
el.prop('checked', false);
}
} else {
// otherwise disable all
el.prop('checked', false);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="formname" method="post" autocomplete="off" id="update">
<div class="group" style="margin:0.5em 0;">
<div>
<div id="one">
<input type="checkbox" class="sing-chbx" id="choice" name="choice[]" value="01">
<label>One</label><br/>
</div>
<div id="two">
<input type="checkbox" class="sing-chbx" name="choice[]" value="02">
<label>Two</label><br/>
</div>
<div id="three">
<input type="checkbox" class="sing-chbx" name="choice[]" value="03">
<label>Three</label><br/>
</div>
<div id="four">
<input type="checkbox" class="sing-chbx" name="choice[]" value="04">
<label>Four</label><br/>
</div>
<div id="five">
<input type="checkbox" class="sing-chbx" name="choice[]" value="05">
<label>Five</label><br/>
</div>
</div>
</div>
<input type="submit" id="submit" value="Confirm Submission">
</form>

How to loop through the form which has random elements

I am trying to loop through the form which has label inside random elements and check if the label matches with the given label name and if matches, I am adding a class to that element. But I am not able get it working, how can I do this?
Here's what I have tried.
Form which has labels inside random elements like div
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>
Jquery code:
$("#grtform").each(function(){
var matchLable = "Currency due"
var lable = $(this).find('label').text();
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
You need loop through lables, not against form
$("#grtform lable").each(function(){ // selecting all labels of form
var matchLable = "Currency type"
var lable = $(this).text(); // changed here too
if(matchLable == lable){
$(this).addClass('matchFound');
}
});
In above code, this refers to currently iterating label.
After trimming a bit
$("#grtform lable").each(function(){ // selecting all labels of form
if($(this).text() == "Currency type"){
$(this).addClass('matchFound');
}
});
You can also use following way :-
var allLables = document.querySelectorAll("#grtform lable");
for(var i = 0; i < allLables.length; i++){
var matchLable = "Currency type";
var lable = allLables[i].innerText; // changed here too
if(matchLable == lable){
allLables[i].classList.add("matchFound");
}
}
<form id="grtform">
<div id="section-1">
<lable>Currency type</lable>
<input type="text" name="currencyType">
</div>
<div id="section-2">
<lable>Currency rate</lable>
<input type="text" name="currencyRate">
</div>
<lable>Currency of country</lable>
<input type="text" name="currencyCountry">
<div id="section-3">
<div class="formData">
<lable>Currency due</lable>
<input type="text" name="currencyDue">
</div>
</div>
</form>

how to store the checked value from checked box and radio box in local storage

I am using JQuery Mobile
I want to display the value in another page which i get from local storage
It Should been check which is been checked in page1
In HTML5:-
<div data-role="page" id="page1">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" value="One" name="one" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" value="None" name="one" checked="checked" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="Two" id="radio-choice-h-2a" value="On" checked="checked" class="custom2">
<label for="radio-choice-h-2a">On</label>
<input type="radio" name="Two" id="radio-choice-h-2b" value="Off" class="custom2">
<label for="radio-choice-h-2b">Off</label>
</fieldset>
</form>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" name="checkbox-h-2c" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2a" value="on" class="custom2">
<label for="radio-choice-h-2a">Steward</label>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2b" value="off" class="custom2">
<label for="radio-choice-h-2b">Guest</label>
</fieldset>
</form>
</div>
</div>
</div>
In Jquery:-
function getRadioCheckedValue(radio_name)
{
var oRadio = $("input[type='radio']");
for(var i = 0; i < oRadio.length; i++)
{
if(oRadio[i].checked)
{
//return oRadio[i].value;
localStorage.setItem("mode", oRadio[i].value);
}
}
return '';
}
function showSelectedNames(){
var count = $("#checkid input:checked").length;
var str = '';
for(i=0;i<count;i++){
if(i == count-1){
str += $("#checkid input:checked")[i].value;
localStorage.setItem("level", str);
}
else{
str += $("#checkid input:checked")[i].value+',';
localStorage.setItem("level", str);
}
}
//alert("You selected----"+str);
}
Now Plz help me out how to set the value in Page 2 which is been checked in Page1
The simplest way is to store values of checkboxes and radio buttons into an array and then save it to localStorage. However, note that localStorage doesn't accept arrays, so you need to JSON.stringify() before saving it into localStorage and then JSON.parse() to convert it back into a readable array.
Here is how you can collect values of all checkboxes and radio buttons, store them and then read them on next page.
$(document).on("pagebeforehide", "[data-role=page]", function () {
// variables
var elements = [],
id = '',
value = '';
// push values of checkboxes and radio buttons into an array
$("[type=checkbox], [type=radio]", this).each(function () {
id = $(this)[0].id;
value = $(this).prop("checked");
elements.push({
"id": id,
"value": value
});
});
// convert array into a string
// in order store it into localStorage
localStorage["values"] = JSON.stringify(elements);
});
$(document).on("pagebeforeshow", "[data-role=page]", function () {
// active page
var active = $.mobile.activePage;
// parse array of checkboxes and radio buttons
var read_array = JSON.parse(localStorage["values"]);
// check/uncheck checkboxes and radio buttons
$.each(read_array, function (e, v) {
var check_id = "#" + v.id,
check_value = v.value;
$(check_id, active).prop("checked", check_value).checkboxradio("refresh");
});
});
Note: elements id should be the same on other pages.
Demo

Categories