how can i list array that is inside another array? - javascript

I'm processing a form onchange event, in this form i got a few inputs, selects and textareas, I was wondering if something like this would work for grabbing the input values in this form
var lat = {
listen: function () {
var input = document.getElementsByTagName('input');
var select = document.getElementsByTagName('select');
var textarea = document.getElementsByTagName('textarea');
var elements = [input,select,textarea];
console.log(elements.length);
for (var a = 0 ; a < elements.length ; a++) {
for ( var b = 0 ; elements[a].length ; b++) {
console.log(elements[a][b].value);
}
}
}
};

Get silly wit it
http://jsfiddle.net/jkabxpkw/1/
var values = document.getElementById('form') ? (function (array) {
var elements = document.getElementById('form').children;
for (var element in elements) {
if (elements.hasOwnProperty(element)) {
if (elements[element].value) {
array.push(elements[element].value);
}
}
}
return array;
}([])) : null;

Yes, you can map and reduce like so:
var elements = [
document.getElementsByTagName('input'),
document.getElementsByTagName('select'),
document.getElementsByTagName('textarea')
].map(function(i) {
// converts the HTMLCollection elements to an array
return Array.prototype.slice.call(i);
}).reduce(function(result, value) {
return result.concat(value);
}, []).forEach(function(element) {
console.log(element.value);
});

Related

Kendo Grid.dataItem loop not working

So my aim it to loop through all selected item in my kendo grid, but after the first iteration the dataItem method returns undefined.
function myFunction() {
var selectedItem = $("#DropDown").val();
var grid = $("#Grid").getKendoGrid();
var selectedItems = grid.select();
for (var i = 0; i < selectedItems.length; i++) {
var dataItem = grid.dataItem(selectedItems[i]);
if (dataItem != undefined)
dataItem.set("Item", SelectedItem);
}
}
Does anyone know why this might be happening?
That happens because set() performs a grid refresh behind-the-scenes so the DOM is recreated. The array you had with the selected items is lost. You can't rely on the tr's references. As a suggestion I think you can use they indexes instead:
function myFunction() {
var selectedItem = $("#DropDown").val();
var grid = $("#Grid").getKendoGrid();
var selectedItems = grid.select().toArray().map((item) => { return $(item).index(); });
for (var i = 0; i < selectedItems.length; i++) {
var currentItem = grid.tbody.find(`tr:eq(${selectedItems[i]})`);
var dataItem = grid.dataItem(currentItem );
if (dataItem != undefined)
dataItem.set("Item", SelectedItem);
}
}
var selectedItems = grid.select().toArray().map((item) => { return $(item).index(); });
This line gets an array of indexes from the selected grid rows to iterate further ahead;
var currentItem = grid.tbody.find(`tr:eq(${selectedItems[i]})`);
This line retrieves the selected row from by the index.
Demo

How can I check all "a" elements inner text against a set of labels text for matches using JavaScript?

I have a bunch of "a" elements on my page that hold the day of the month for a calendar. I have hidden labels, each containing a day of the month. I want to use JavaScript to check of there is a match. If there is a match, I want to add HTML nested within the a element.
Here is what I have tried, but it does not work as expected:
<span id="eventDayLabel1" class="daysClass">18</span>
18
$(function () {
$('a').on('click', function (event) { event.preventDefault(); });
});
var elemAs = document.getElementsByTagName('a');
for (var i = 0; i < elemAs.length; i++) {
var elemA = elemAs[i];
var dayLabels = document.getElementsByTagName('daysClass');
function contains(dayLabels, elemA) {
for (var i = 0; i < dayLabels.length; i++) {
if (dayLabels[i].innerText == elemA.innerText) {
// add HTML here
}
}
return false;
}
}
Why doesn't this piece of code work? I've checked that the labels and a elements are being created there are matches (using inspect element in Chrome).
You aren't calling the contains() function and you're using getElementsByTagName() to get a class.
Just remove the function and the return false, and use getElementsByClassName() instead.
var elemAs = document.getElementsByTagName("a");
for (var i = 0; i < elemAs.length; i++) {
var elemA = elemAs[i];
var dayLabels = document.getElementsByClassName("daysClass");
//function contains(dayLabels, elemA) {
for (var i = 0; i < dayLabels.length; i++) {
if (dayLabels[i].innerText == elemA.innerText) {
console.log('match');
}
}
//return false;
//}
}
<span id="eventDayLabel1" class="daysClass">18</span>
18
<span id="eventDayLabel1" class="daysClass">18</span>
17
<span id="eventDayLabel1" class="daysClass">19</span>
19

pushing into arrays in javascript

My script (is meant to) grab text from the a page (which works fine) and then splits it by by newline (\n) and puts each splitted string into an array called "dnaSequence"; from there it loops through each element in the array and if the string contains the character ">" it assigns that string to the "var header_name", else it pushes all other lines into a new array called "dnaSubseq". The original text looks something like this:
>header_1
gctagctagc
cgcgagcgagc
>header_2
gcgcatgcgac
When I execute the code it fails to alert on anything. Here is the code:
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.pushValues(dnaSequence[i]);
}
alert(dnaSubseq);
}
}
Change
dnaSubseq.pushValues(dnaSequence[i]);
To
dnaSubseq.push(dnaSequence[i]);
If it doesn't alert anything, that means you forgot to invoke the function :)
loaderMy();
http://jsfiddle.net/zszyg5qx/
Try this function
function loaderMy() {
var dnaSubseq = [];
var dnaSequence = [];
var header_name = "";
var splittedLines = document.getElementById("page-wrapper").innerText;
dnaSequence = splittedLines.split('\n');
for (var i = 0; i < dnaSequence.length; i++) {
if (dnaSequence[i].match(/>/)) {
header_name = dnaSequence[i];
alert(header_name);
}
else {
dnaSubseq.push(dnaSequence[i]);
}
alert(dnaSubseq);
}
}

return or send variable to onchange event

I am trying to achieve the same functionality of a function from two separate events. So the function I created is:
function adding_stuff() {
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates
}
$(".primary .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(".primary .panel-content ul").append(li.concat(names[i]))
}
}
There are two buttons primary and secondary. I want the same functionality for both the functions but the output in different <div>. Currently the selected <div> is ".primary", however I want this to depend on the button which has been clicked.
The function is triggered using:
$("#primary").onchange = adding_stuff;
$("#secondary").onchange = adding_stuff;
NOTE: primary and secondary are inputs of type file.
You can add additional data when you register the callback, which will be made available within the event handler:
$('#primary').on('change', { target: '.primary' }, adding_stuff);
$('#secondary').on('change', { target: '.secondary' }, adding_stuff);
and then within the handler:
function adding_stuff(ev) {
var cls = ev.data.target; // extract the passed data
...
// file handling code omitted
$(".panel-content", cls).append(...)
}
using jquery's change() event
function adding_stuff(obj,objClass) {
var names = [];
var dates = [];
for(var i = 0; i < obj.files.length; i++) {
//adding stuff to names and dates
}
$("."+ objClass+" .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$("."+ objClass+" .panel-content ul").append(li.concat(names[i]))
}
}
$("#primary").change(function(){
adding_stuff(this,'primary');
});
$("#secondary").change(function(){
adding_stuff(this,'secondary');
});
Try
function adding_stuff(opselector) {
return function() {
var names = [];
var dates = [];
for (var i = 0; i < this.files.length; i++) {
// adding stuff to names and dates
}
var ul = $("<ul class='list-unstyled'></ul>").appendTo(opselector)
for (var i in names) {
ul.append("<li>" + li.concat(names[i]) + "</li>")
}
}
}
$("#primary").change(adding_stuff('.primary .panel-content'));
$("#secondary").change(adding_stuff('.secondary .panel-content'));
You can use $(this).attr("class") inside the function. It will return the class of button who triggered the event.
function adding_stuff() {
var div = $(this).attr("class");
var names = [];
var dates = [];
for(var i = 0; i < this.files.length; i++) {
//adding stuff to names and dates to $div
}
$(div + " .panel-content").append("<ul class='list-unstyled'></ul>");
for(var i in names) {
var li = "<li>";
$(div + " .panel-content ul").append(li.concat(names[i]));
}
}

How to access multiple textbox by getElementsByName

I have written following code in html:
<input type="text" id="id_1" name="text_1">
<input type="text" id="id_2" name="text_2">
<input type="text" id="id_3" name="text_3">
Here I have to get all textBoxes in an array in javascript function whose id starts with "id". So, that I can get above two textBoxes in an array.
How to get all textBoxes whose id start with "id"?
var nodeList = document.querySelector("input[name^='text_'")
A nodeList should be sufficiently like an array for your purposes.
Note that support for querySelector might not be sufficient for your purposes (in which you will need to getElementsByTagName and then filter the results in a loop).
Alternatively you could use a library which provides its own selector engine. In YUI 3 you could:
var listOfYUIObjects = Y.all("input[name^='text_'");
Mootools, Prototype, jQuery and a host of other libraries provide similar functionality.
var ele = document.getElementsByTagName("input");
var matchingEle = [];
var eleName = '';
for (var i = 0; i < ele.length; ++i) {
el = ele[i];
eleName = el.getAttribute("name");
if (eleName && eleName.indexOf("text_") == 0) {
matchingEle.push(el);
}
}
You could use a generic function that filters a list of elements based on a pattern. This is useful if you want to do a similar thing in future but with different criteria on the properties.
http://jsfiddle.net/3ZKkh/
function filter(elements, pattern) {
var i, j, match, e, f = [];
for (i = 0; i < elements.length; i += 1) {
e = elements[i];
match = true;
for (j in pattern) {
if (pattern.hasOwnProperty(j)) {
if (!(j in e && pattern[j](e[j]))) {
match = false;
break;
}
}
}
if (match) {
f.push(e);
}
}
return f;
}
var pattern = {
'type': function (t) {
return t.toLowerCase() === 'text';
},
'name': function (t) {
return t.toLowerCase().search('text') === 0;
}
};
console.log(filter(document.getElementsByTagName("input"), pattern));
var list = document.getElementsByTagName('input'); //Array containing all the input controls
var textBoxArray = []; //target Array
for (var i = 0; i < list.length; i++)
{
var node = list[i];
if (node.getAttribute('type') == 'text' && node.getAttribute("id").substring(0, 1) == "id")
{
/*
insert matching textboxes into target array
*/
textBoxArray.push(node);
}
}

Categories

Resources