getting the names of elements in JS/jQuery - javascript

I have some checkbox inputs like so:
<input type="checkbox" name="1" class="filter"/>
<input type="checkbox" name="2" class="filter"/>
...etc...
I'm trying to write a function where any time a checkbox is selected, it generates a string with all the names concatenated. Here's what I have so far:
$('.filter').click(function(event){
var filters = $('.filter').toArray();
var fstr = "";
for (f in filters)
{
fstr = fstr+","+f.name;
}
alert(fstr);
});
The names keep coming up as 'undefined', though (i.e. the alert returns ,undefined,undefined,undefined,undefined,undefined,undefined). How do I access the names?

Here's how it's meant to be done:
$('.filter').click(function (event)
{
var fstr = '';
$('.filter[name]').each(function ()
{
fstr += ',' + $(this).attr('name');
});
alert(fstr);
});

You can use .map() to get what you're after, like this:
$('.filter').click(function(event){
var names = $('.filter').map(function () {
return $(this).attr("name");
}).get().join(',');
alert(names);
});
Just change $('.filter') to $('.filter:checked') if you want a list containing only the checked ones.

$('.filter').click(function(event){
var filters = $('.filter').toArray();
var fstr = "";
for (f in filters)
{
fstr = fstr+","+filters[f].name;
}
alert(fstr);
});
Why are you doing it that way anyway?
$('.filter').click(function(event){
var str = '';
$('.filter').each(function () {
str += $(this).attr('name') +",";
});
alert(str);
});

(function($filters) {
$filters.click(function(event) {
var filters = $filters.toArray();
var fstr = [];
for (var i = filters.length - 1; i > -1; --i) {
fstr.push(filters[i].name);
}
fstr = fstr.join(",");
alert(fstr);
}
})($('.filter'));

Try $(f).name.

How about $(elem).attr("name")?

I'm thinking the convert to array is your problem, try:
var filters = $('.filter');
for(var nI = 0; nI < filters.length; nI++)
filters.eq(nI).attr('name');

Related

How to remove array element if one key match?

Basically its dataSource for kendo grid default data is selVal ,If any key from selval is matching with dtoVal i want to delete everything
from selVa, is it possible implement with below code its not deleting selVal elements from array. Any idea ?
ctrl.js
$scope.handleControlOwnerCancel = function(){
this.ctrlOwnerModal.close();
var dtoVal = $scope.controlDTO.controlOwners;
var selVal = $scope.selectedOwners;
for (var i = 0; i < dtoVal.length; i++) {
for (var j=0; j<selVal.length; j++) {
if (dtoVal[i].workerKey !== selVal[j].workerKey) {
$scope.selectedOwners = $scope.controlDTO.controlOwners;
controlOwnersDataSource();
}
}
}
};
It will be better to use angular.forEach instead of using for loop. Also you said
If any key from selval is matching with dtoVal i want to delete
everything from selVa
But inside the loop you are checking with !==. I don't know which one is exactly your requirement. But you can try doing this:
$scope.handleControlOwnerCancel = function(){
this.ctrlOwnerModal.close();
//var dtoVal = $scope.controlDTO.controlOwners;
//var selVal = $scope.selectedOwners;
var match = 0;
angular.forEach($scope.selectedOwners, function(val, key){
angular.forEach($scope.controlDTO.controlOwners, function(val2, key2){
if(val.workerKey==val2.workerKey){
match++;
}
})
})
if(match>0){
$scope.selectedOwners = $scope.controlDTO.controlOwners;
controlOwnersDataSource();
}
};
Try this
$scope.handleControlOwnerCancel = function(){
this.ctrlOwnerModal.close();
var dtoVal = $scope.controlDTO.controlOwners;
var selVal = $scope.selectedOwners;
var selValCopy = angular.copy(selVal);
for (var i=dtoVal.length-1; i>=0; i--) {
for (var j=selVal.length-1; j>=0; j--) {
if (dtoVal[i].workerKey === selVal[j].workerKey) {
selValCopy.splice(j, 1);
} else {
$scope.selectedOwners = $scope.controlDTO.controlOwners;
controlOwnersDataSource();
}
}
}
selVal = selValCopy;
};

Adding checkbox selected values in multi-dimensional array

I am working on this demo. How can I add each selected row as an array into the data [] so that it looks like this:
[{"Cell phone":"BlackBerry Bold 9650","Rating":"2/5","Location":"UK"},
{"Cell phone":" Samsung Galaxy","Rating":"3/5","Location":"US"}]
Here is the code I have:
var data = [];
function myfunc(ele) {
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
check if this works,
here is the fiddle demo
var data = [];
function myfunc(ele) {
var values = [];
var keys = [];
$.each($("input[name='case[]']:checked").closest("table").find('th'),
function () {
keys.push($(this).text());
});
keys.shift(); // to remove the first key
var len = keys.length, obj={}, ctr=0;
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
obj[keys[ctr]]=$(this).text();
ctr++;
if(ctr==len){
values.push(obj);
obj={};
ctr=0;
}
});
alert("val---" + JSON.stringify(values));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
http://jsfiddle.net/ugdas2em/
Try this:
var data = {};
function myfunc(ele) {
//var values = new Array();
var k = 0;
var j = 0;
data[k] = {};
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
if(j==3)
{
k = k+1;
data[k] = {};
j = 0;
}
//values.push($(this).text());
data[k][j] = $(this).text();
j=j+1;
});
console.debug(data);
//alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
Note: If you want then you can use [] with data variable in place of {} in my code. You need to replace at three place. Thanks.

Extracting all CSS classes and ID's in a given HTML block

I have a textarea where I paste a block of HTML code. When I hit submit, I want to extract all CSS classes and ID's from that block and throw them into an array.
So far I have the submit working as well as the regular expression, but i don't know how to filter through the whole block and extract all instances where text matches my regular expression.
index.html
<body>
<textarea id="codeInput"></textarea>
<button id="submitCode">submit</button>
<script src="functions.js"></script>
</body>
function.js
$(function() {
$('#submitCode').click(function() {
var codeInput = $('textarea#codeInput').val();
console.log(codeInput);
});
});
$('#submitCode').click(function() {
var codeInput = $('textarea#codeInput').val();
var codeHTML = $('<div>', { html: codeInput }); // Parse the input as HTML
var allIds = [];
var allClasses = [];
codeHTML.find('[id]').each(function() {
allIds.push(this.id);
});
codeHTML.find('[class]').each(function() {
allClasses = allClasses.concat(this.className.split(' '));
});
console.log("IDs: " + allIds.join(', '));
console.log("Classes: " + allClasses.join(', '));
});
Make your function.js something like this:
$(function() {
$('#submitCode').click(function() {
var codeInput = $('textarea#codeInput').val();
var $input = $(codeInput);
var attrs: {
'class': [],
'id': []
};
$input.find('*').each(function() {
attrs.class.push($(this).attr('class'));
attrs.id.push($(this).attr('id'));
});
attrs.class.push($input.attr('class'));
attrs.id.push($input.attr('id'));
});
});
That goes through each element in the input code, and removes their class and id attributes, by first going through all the children of the container element in the input, and then afterwards doing the same for the container element in the input.
Personally I like Barmar's solution the best, but this works (jsfiddle):
$('#submitCode').click(function() {
var codeInput = $('#codeInput').val();
var ids = codeInput.match(/id="(.*?)"/);
var classes = codeInput.match(/class="(.*?)"/);
var output = classes[1].split(" ");
output.push( ids[1] );
console.log(output);
});
$(function() {
$('#submitCode').click(function() {
var ids = [], classes = [];
$("[id],[class]").each(function(i, el) {
var id, c;
if (id = $(this).attr('id')) {
ids.push(id);
}
if (c = $(el).attr('class')) {
classes.push(c);
}
});
console.log(ids, classes);
});
});
<textarea id="codeInput">
<div id="hello"><div class="w"></div></div>
<div id="world"></div>
<div class="my-class"></div>
</textarea>
<button id="submitCode">submit</button>
$(function() {
$('#submitCode').click(function() {
var CSS_CLASSES = [];
var CSS_IDS = [];
var el = document.createElement( 'div' );
var text = $("#codeInput").val();
el.innerHTML = text;
var nodes = el.getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if(node.id.length > 0) {
CSS_IDS.push(node.id);
}
if(node.className.length > 0) {
CSS_CLASSES.push(node.className);
}
}
console.log(CSS_CLASSES);
console.log(CSS_IDS);
});
});
http://jsfiddle.net/zeZ93/6/
I had this very same challenge and modified the code by #Ryan to extract all (unique) classes and IDs, including when multiple classes are applied to the same element. It's very useful and works for any URL.
See http://jsfiddle.net/pixelfast/4uftwbm0/57/
Thank you.
<!-- HTML -->
<textarea id="codeInput" cols=50 rows=10></textarea>
<button id="submitCode">submit</button>
<!-- jQuery -->
var remoteURL = "https://getbootstrap.com";
function url_content(url) {
return $.get(url);
}
url_content(remoteURL).success(function(data) {
$('#codeInput').val(data);
});
$(function() {
$('#submitCode').click(function() {
var CSS_CLASSES = [];
var CSS_IDS = [];
var el = document.createElement('div');
var text = $("#codeInput").val();
el.innerHTML = text;
var nodes = el.getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.id.length > 0) {
CSS_IDS.push(node.id);
}
if (node.className.length > 0) {
var x = node.className.split(" ")
$.each(x, function(index, val) {
if (val != '') {
CSS_CLASSES.push(val);
}
});
}
}
console.log("CLASSES FOUND: ", unique(CSS_CLASSES));
console.log("IDs FOUND: ", unique(CSS_IDS));
});
});
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}

generate list of variables from a FOR loop

var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}

Merging arrays in JavaScript not working

When I try var a = ar_url2.concat(ar_desc2); to join my arrays into one it returns null. I'm sure it's trivial but I spent a few hours stuck on this now and an explanation as why this is happening would be great. In my code bellow I tried while(ar_url2.length)a.push(ar_url2.shift()); and it returns same null...
function agregar() {
var i = 0,
textarea;
var ar_desc = [];
while (textarea = document.getElementsByTagName('textarea')[i++]) {
if (textarea.id.match(/^desc_([0-9]+)$/)) {
ar_desc.push(textarea.id);
}
}
var desc_count_demo = document.getElementById('desc_count').value;
var desc_count = desc_count_demo - 1;
i = 0;
var ar_desc2 = [];
var campo = null;
while (i <= desc_count) {
campo = document.getElementById(ar_desc[i]).value;
ar_desc2[ar_desc[i]] = campo;
i++;
}
i = 0;
var input;
var ar_url = [];
while (input = document.getElementsByTagName('input')[i++]) {
if (input.id.match(/^url_([0-9]+)$/)) {
ar_url.push(input.id);
}
}
var url_count_demo2 = document.getElementById('url_count').value;
var url_count2 = url_count_demo2 - 1;
i = 0;
var ar_url2 = [];
while (i <= url_count2) {
campo = document.getElementById(ar_url[i]).value;
ar_url2[ar_url[i]] = campo;
i++;
}
// var a = Array.prototype.concat.call(ar_url2, ar_desc2);
while (ar_url2.length) a.push(ar_url2.shift());
function url(data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
}
window.open('alta1.php?'+url(a));
}
EDIT: If I pass to function url(ar_url2) or url(ar_desc2) the returned values in the URL are
http://localhost/proj1/alta1.php?url_0=inpit&url_1=input
and
http://localhost/proj1/alta1.php?desc_0=input&desc_1=input
But still cannot merge both into one...
One thing I see is your ar_url Array is filled by:
while(input=document.getElementsByTagName('input')[i++]){
if(input.id.match(/^url_([0-9]+)$/)){
ar_url.push(input.id);
}
}
Since you the putting the whole id in the array, it will be filled with things like: 'url_0', 'url_1', 'url_2', etc...
Later you do:
ar_url2[ar_url[i]] = campo;
When you index into ar_url, you get out the 'url_XXX' strings. That means you are setting the 'url_XXX' properties on ar_url2 instead of filling in the elements of the array.
Try changing your second loop to:
while(input=document.getElementsByTagName('input')[i++]){
var result;
if(result = input.id.match(/^url_([0-9]+)$/)){
ar_url.push(+result[1]);
}
}
To use the value captured in the ([0-9]+) portion of the RegExp instead of the entire 'url_XXX' string.

Categories