I have an html table, which is structured like this:
<body>
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>
</body>
I can iterate over the checkboxes using the code below and push the checked rows into an array:
saveButton.onclick = function(){
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++){
if (checkedRows[i].checked){
checkedRowIndexes.push(i);
}
}
console.log(checkedRowIndexes);
}
But how would I go about iterating over the table and push the color (2ยบ col) instead, using javascript?
Thank you!
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++) {
if (checkedRows[i].checked) {
checkedRowIndexes.push(i);
selectedColors.push(checkedRows[i].nextElementSibling.innerText);
}
}
console.log(checkedRowIndexes, selectedColors);
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>
Related
If searched keyword matches I am able to show the matched input text and its related div with category name. Now what I am trying is to search over category names as well.
If searched keyword matches with the category name this div should visible. also if searched keyword matches with the input names this is also visible with its category name.
$('.bar-input').on('keyup', function() {
var search_input = $(this).val().toLowerCase();
var tags = $('.wrap label');
var count = tags.length;
var text_input = $(this).val().length;
var category = $('.category-type');
// // searching for tags
for (i = 0; i < count; i++) {
if (!search_input || tags[i].textContent.toLowerCase().indexOf(search_input) > -1) {
tags[i].parentNode.style['display'] = 'block';
} else {
tags[i].parentNode.style['display'] = 'none';
}
}
// If no tags found category will be hidden
$(".category").not(".stcw-screen").map(function() {
let flag = true;
$(this).find('.wrap').map(function() {
if ($(this).css("display") != "none") {
flag = false;
}
});
if (flag) {
$(this).css("display", "none");
} else {
$(this).css("display", "block");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-name">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div><div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div><div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div><div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>
To do what you require you can loop through each category and first determine if the .category-type matches the search term using a case-insensitive implementation of :contains and then display that section with all options visible, or if not you can look at each option in turn using the same :icontains() selector and show them individually.
The logic would look something like this:
// case-insensitive :contains implementation (credit: https://stackoverflow.com/a/8747204/519413)
jQuery.expr[':'].icontains = (a, i, m) => $(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
var $categories = $('.category');
var $types = $('.category-type');
$('.bar-input').on('input', function() {
var search_input = $(this).val().toLowerCase().trim();
if (search_input.length == 0) {
// no search term entered, reset state to show all items
$('.wrap label').add($types).show()
return;
}
$categories.each((i, category) => {
let $cat = $(category);
let $type = $cat.find('.category-type').hide();
let $labels = $cat.find('.wrap label').hide();
if ($type.is(`:icontains("${search_input}")`)) {
// match on category type, show category-type and all child options
$type.add($labels).show();
} else {
// no match on category, show only if match on child option
let $matches = $labels.filter(`:icontains("${search_input}")`).show();
$type.toggle($matches.length > 0);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="bar-input" type="text" placeholder="search">
<div class="category">
<div class="category-type">
<h5>Country</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">America</label>
</div>
<div class="wrap">
<label><input type="checkbox">France</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Sports</h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">Football</label>
</div>
<div class="wrap">
<label><input type="checkbox">Cricket</label>
</div>
</div>
</div>
<div class="category">
<div class="category-type">
<h5>Operating system </h5>
</div>
<div class="options">
<div class="wrap">
<label><input type="checkbox">linux</label>
</div>
<div class="wrap">
<label><input type="checkbox">windows</label>
</div>
</div>
</div>
I saw lots of similar question where you can extract the values of Checkboxes based on the check uncheck and add them to URL, but if we have different categories of checkbox group, separate them with &.
Example:
$(document).ready(function() {
var swapRelation = "";
$("input[type=checkbox]").click(function(e) {
var seasoning = "",
parentRelation = "",
tempArray = [];
$("input:checked").each(function() {
tempArray.push($(this).attr("name").replace(/\s/g, ''));
parentRelation = $(this).closest(".wrapper").find('.catName').text().trim();
parentRelation = parentRelation.replace(/\s/g, '');
});
if (tempArray.length !== 0) {
seasoning += `${parentRelation}=` + tempArray.toString();
// if (swapRelation == parentRelation) {
// // seasoning+=`&${parentRelation}=`+tempArray.toString();
// seasoning += `${parentRelation}=` + tempArray.toString();
// }else {
// }
//tempArray = [];
swapRelation = parentRelation;
}
console.log("example.com?" + seasoning);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="catName">Fruits</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="apple" id="input-5">
<input class="input__field" type="checkbox" name="banana" id="input-6">
<input class="input__field" type="checkbox" name="mango" id="input-7">
</div>
</div>
<div class="wrapper">
<div class="catName">Vaegs</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Okra" id="input-8">
<input class="input__field" type="checkbox" name="Patato" id="input-9">
<input class="input__field" type="checkbox" name="Tamato" id="input-10">
</div>
</div>
<div class="wrapper">
<div class="catName">Rivers</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Ganga" id="input-11">
<input class="input__field" type="checkbox" name="yamuna" id="input-12">
<input class="input__field" type="checkbox" name="thames" id="input-13">
</div>
</div>
Expected Result on multiple Selections:
URL?Fruits=banana,mango&Vegs=okra,patato&Rivers=ganga,whateverSelected
You can use URLSearchParams to build your query string.
var usp = new URLSearchParams();
document.querySelectorAll('.wrapper').forEach((wrapperDiv)=> {
var category = wrapperDiv.querySelector('.catName').textContent;
var checkedBoxes = wrapperDiv.querySelectorAll('input[type="checkbox"]:checked');
var values = Array.from(checkedBoxes, cb=>cb.name).join('');
usp.append(category,values);
});
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>
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 ");
}
}
I create a div and its css id like this.
<div id="r1" class="ansbox"></div>
<div id="r2" class="ansbox"></div>
<div id="r3" class="ansbox"></div>
<div id="r4" class="ansbox"></div>
<div id="r5" class="ansbox"></div>
<div id="r6" class="ansbox"></div>
<div id="r7" class="ansbox"></div>
<div id="r8" class="ansbox"></div>
<div id="r9" class="ansbox"></div>
<div id="r10" class="ansbox"></div>
is there a way to create this div using looping statement. Anyone help me..
I would recommend using some javascript (without jquery) for performance:
var toAdd = document.createDocumentFragment();
for(var i=0; i < 11; i++){
var newDiv = document.createElement('div');
newDiv.id = 'r'+i;
newDiv.className = 'ansbox';
toAdd.appendChild(newDiv);
}
document.appendChild(toAdd);
This way you only make one append(), only 1 reflow, and you don't need jQuery.
To append it to a jQuery selector:
$('sel').append(toAdd);
Or a dom element:
document.getElementById('sel').appendChild(toAdd);
Suppose you have following div where you will insert new divs:
<div id="target">
<!-- all divs will append here -->
</div>
jQuery:
for(var i =1; i<= 10; i++){
$('#target').append($('<div/>', { id: 'r' + i, 'class' : 'ansbox'}))
}
or
for(var i =1; i<= 10; i++){
$('#target').append('<div id="r'+ i +'" class="ansbox"></div>')
}
I will go for first approach.
Related refs:
.append()
Here's one option:
for(var i = 0; i <=10; i++) {
$('<div id="r'+i+'" class="ansbox"></div>').appendTo("target");
}
<div class="ibox-content" id="location-div">
<div class="row">
<div class="col-sm-12">
<button id="addlocation" type="button" class="btn btn-w-m btn-primary pull-right">Add new location</button>
</div>
</div>
<div class="row" style="margin-top:10px;">
<div class="col-sm-2">
<label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px;" value="1"></span></label>
</div>
<div class="col-sm-10">
<input type="text" name="" class="form-control ">
</div>
</div>
</div>
Here I want to add a dynamic row by adding 1 to each new entry this will solve your problem
<script>
$(document).ready(function(){
var inno = document.getElementById("locval").value;
for(var start = 1; inno >= start; start+=1)
{
start;
}
$("#addlocation").click(function(){
$("#location-div").append('<div class="row" style="margin-top:10px;"><div class="col-sm-2"><label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px" value="'+start+++'"></span> </label></div><div class="col-sm-10"><input type="text" name="" class="form-control "></div></div>');
});
});
</script>
I would recommend using simple javascript loop (without jquery) for performance:
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};
console.log(container);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Answer</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};