On a webpage I give the user the option of hiding table elements (which contain checkboxes) like this:
mytable.style.display = 'none'; //the table and the enclosed textbox is hidden
I am now trying to find all of the tables that are not hidden like this:
var frm = document.forms[0];
var arrayDisposals;
var intCount;
var arrayDisposals = new Array();
for (i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox" && frm.elements[i].name.substr(0, 3) == "Del") {
if ('none' != frm.elements[i].style.display) {
{
arrayDisposals.push(frm.elements[i].id + '|' + frm.elements[i].checked)
}
}
}
The problem is that the second IF statement does not work i.e. all elements are added to the array. How do I only add checkboxes that are not hidden?
If you were looking for a jQuery solution this should suffice. Use .map()
var arrayDisposals = $('input[type="checkbox"][name*="Del"]:visible').map(function(){
return this.id+ "|" + this.checked
}).get();
Use attribute selector to find checkboxes and where the name contains "Del" and :visible to check if it is not hidden.
DEMO
Related
I currently have a dynamically generated checkbox which when clicked creates a table. Multiple selections can be selected on my checkbox and I store this in an array. I have a loop for storing different selections e.g 1st, 2nd and 3rd checked selections.
Checkbox
option_one
option_two
options_three
The problem I am facing is, if I select the options in ascending order like 1>2>3 the tables are generated correctly:
Table_One
Table_two
Table_Three
However if I I select in a descending order, or I mix it up, option_one always ends up being passed as the first selection even when this isn't true.
My code:
$(document).on("change", ".tbl_list", function () {
var tbls = [];
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
var tbl2Name = " ";
var tbl3Name = " ";
var tblName = " ";
for (i = 0; i < tbls.length; i++) {
if (i === 0) {
tblName = tbls[i];
}
if (i == 1) {
tbl2Name = tbls[i];
}
if (i == 2) {
tbl3Name = tbls[i];
}
}
$("#table").html(tblName);
Where tbl_list is the checkbox class-name and tbl[] is the name. So why does tblName always assume the value of the first object in the checkbox list?
Lets break this down a bit, every time one of your checkboxes changes you create a brand new array
$(document).on("change", ".tbl_list", function () {
var tbls = [];
Then you loop through all the checked checkboxes filling this list
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
jquery .each will iterate over all the checkboxes which are checked, it does this in the order they appear in the DOM, not in the order you happen to have checked them in (why would it? how would it know?)
If you want to preserrve the order that you checked them in then you need to maintain a persistant list, and push a new item to the end of the list when checked, and remove an item when unchecked.
$(".checkbox").change(function() {
if(this.checked) {
//push into array
else {
//remove from array
}
});
Cant you just check which checkbox has been selected and add its value to an array this way you can keep the order.
After the suggestions I made a few amendments and it now works as intended.
var tbls = [];
$(document).on("change", ".tbl_list", function () {
if (this.checked){
tbls.push($(this).val());
console.log(tbls);
var tbl2Name = " ";
var tbl3Name = " ";
var tblName = " ";
for (i = 0; i < tbls.length; i++) {
if (i === 0) {
tblName = tbls[i];
}
if (i == 1) {
tbl2Name = tbls[i];
}
if (i == 2) {
tbl3Name = tbls[i];
}
}
}
$("#table").html(tblName);
window.sessionStorage.setItem("tblN", tblName);
window.sessionStorage.setItem("tblN2", tbl2Name);
window.sessionStorage.setItem("tblN3", tbl3Name);
this the javascript code I am using to access the values but every time this runs all hidden fields become visible why?
function PopulateTableComboBox(ID) {
var myValues = new Array();
var startsWith = "TABLE=";
for (var index = 0; index < document.getElementsByTagName("input").length; index++) {
if (document.getElementsByTagName("input")[index].type = 'hidden' && document.getElementsByTagName("input")[index].id.substring(0, startsWith.length) === startsWith) {
myValues.push(document.getElementsByTagName("input")[index].value);
}
}
}
even the viewsate's hidden fields are effected to the point where the asp.net buttons turn into square box with text in it. I have attached a before and after picture
You are using = instead of ==
Your code
document.getElementsByTagName("input")[index].type = 'hidden'
Change it to
document.getElementsByTagName("input")[index].type == 'hidden'
I have a JavaScript program that isn't properly functioning. For some reasons before it appends what it is actually getting from the checked radio box it appends three times with noting in the append except the styling. I'm not sure what I'm doing wrong.
$(document).delegate('#add-owner', 'pageinit', function () {
loadOwners();
$('#add-owner-save').bind('click', function () {
var permission = $('#editing-permissions option:selected').text();
var selection = $("input[type='radio']:checked") || [];
if (selection.length > 0) {
for (var i = 0; i < selection.length; i++) {
console.log($('#label-' + selection[i].id).find('.owner-name').text());
console.log($("input[type='radio']:checked").val());
$('.display-owners').append('<div class="ui-grid-a"><div class="ui-block-a">' + $('#label-' + selection[i].id).find('.owner-name').text() + '</div><div class="ui-block-b" style="text-align:right">' + permission + '</div></div>');
}
$('.display-owners').trigger('create');
}
$('.display-owners').show();
$('#add-owner').dialog('close');
$('input[name=contribute-radio]').attr('checked', false).checkboxradio("refresh");
return false;
});
});
I think the problem is that I have multiple radio areas on this page. How do I specify that I just want these radio buttons are the ones I want it to checked?
This code:
... + $('#label-' + selection[i].id).find('...
should be like this:
... + $('#label-' + selection[i].attr('id')).find('...
because what you have in selection array are jQuery objects, not DOM elements objects.
Thanks Esalija for pointing out my assumption was not correct.
Since said you have multiple sets of radio buttons, the selector you're using is finding all of them on the page so that is why you have multiple "checked" radio buttons.
This:
var selection = $("input[type='radio']:checked") || [];
To this:
var selection = $("input[name='radioset1']:checked") || [];
Then just name each radio set different and replace "radioset1" with the set you need for this one.
I want to do a javascript function that check the unchecked checkbox. My function nowadays, check all the unchecked checkbox, and I need that just check a specific GridView unchecked checkbox
function checar() {
var el = document.getElementsByTagName("input");
for (var i = 0; i < el.length; i++) {
if (el[i].type == "checkbox") {
el[i].checked = true;
}
}
}
You want to first limit the scope of your search for elements. One way to do so would be to use getElementById
function checar() {
var grd = document.getElementById("<%=grd.ClientID%>"); // <-- Add this line
var el = grd.getElementsByTagName("input"); // <-- change the scope of this to grd
//rest of your code here.
}
Sample using divs, but you'll get the idea I think: http://jsfiddle.net/8LRkk/
Edited to include setting the specific Grid ID.
To get at all of the checkboxes of a particular gridview, you need to grab checkboxes whose ClientID contain the portion of the gridview's ClientID as well since all controls have an id which is "stacked".
Your function should work as a base, it just needs to have an added check in it:
function checar() {
var el = document.getElementsByTagName("input");
// Get the client id of the gridview from ASP here
var gvID = '<%= this.myGridview.ClientID %>';
for (var i = 0; i < el.length; i++) {
// Call the id of the checkbox and check to see if it
// contains the client id of the gridview at the same time
if (el[i].type == "checkbox" && el.id.indexOf(gvID) != -1) {
el[i].checked = true;
}
}
}
I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS