how do i get the position of the objects in my array? - javascript

I wan't to get the order of the objects in my array so I can store them to my database? But I don't know what to write in my for loop.
here's the code
<script>
$(document).ready(function () {
var rootLimit = 8;
$('ul.sortable').nestedSortable({
handle: 'a',
items: 'li',
listType: 'ul',
maxLevels: '3',
toleranceElement: '> a',
update: function (event, ui) {
list = $(this).nestedSortable(
'toHierarchy',
{ startDepthCount: 0 }
);
var page_id = ui.item.find('> a').attr('data-page-id');
console.log(list);
for (var i = 0; i < list.length; i++) {
//Do something
}
$.post('/page/updatemenu/' + page_id, {
list : list
}, function (data) {
});
}
});
});
</script>

Instead of for you can use jQuery method .each():
list.each(function(index, item){
// do something with item or index of item
});

Use -
var index = $(ui.sender).index();

Related

Update live JavaScript Array while pushing elements to HTML ID

I am facing a slight dilemma as a JavaScript newbie. Let me explain the script:
I have implemented a JavaScript function rss() which pulls from an internet RSS news feed and saves the news headlines into an array newsArray[].
The function headlinesInsert() should push every item in the array to the HTML ID #headlineInsert, similarly to how it is shown here.
However, the linked example's textlist variable (which should be replaced with my local newsArray[]) does not seem to be 'compatible' for some reason as when replacing nothing shows on the HTML side.
The idea is that the rss() function updates the global newsArray[] with new headlines every 10 minutes while the headlinesInsert() pushes this data to the HTML ID constantly (as per the linked example).
With my limited knowledge of JavaScript, I am hoping someone could help me set the following code right and put the idea into action.
// Push RSS Headlines into HTML ID
var newsArray = [];
var listTicker = function headlinesInsert(options) {
var defaults = {
list: [],
startIndex:0,
interval: 8 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function headlinesInsert(index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function headlinesInsert() {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function headlinesInsert() {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
// The following line should hold the values of newsArray[]
var textlist = new Array("News Headline 1", "News Headline 2", "News Headline 3", "News Headline 4");
$(function headlinesInsert() {
listTicker({
list: textlist ,
startIndex:0,
trickerPanel: $('#headlineInsert'),
interval: 8 * 1000,
});
});
$(function slow(){
// Parse News Headlines into array
function rss() {
$.getJSON("https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.stuff.co.nz%2Frss", function(data) {
newsArray = [];
for (var i = 0; i < data.items.length; i++){
newsArray[i] = (data.items[i].title);
}
console.log(newsArray);
})}
// Refresh functions ever 10 minutes
rss()
setInterval(function slow() {
rss();
}, 600000); // 10 Minute refresh time
});
Check following code. You need to initialise listTicker once rss feed is loaded.
<script src='https://code.jquery.com/jquery-3.2.1.min.js'></script>
<script>
var listTicker = function(options) {
var defaults = {
list: [],
startIndex: 0,
interval: 3 * 1000,
}
var options = $.extend(defaults, options);
var listTickerInner = function(index) {
if (options.list.length == 0) return;
if (!index || index < 0 || index > options.list.length) index = 0;
var value = options.list[index];
options.trickerPanel.fadeOut(function() {
$(this).html(value).fadeIn();
});
var nextIndex = (index + 1) % options.list.length;
setTimeout(function() {
listTickerInner(nextIndex);
}, options.interval);
};
listTickerInner(options.startIndex);
}
var textlist = new Array("news1", "news2", "news3");
$(function() {
function rss() {
$.getJSON("https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.stuff.co.nz%2Frss", function(data) {
newsArray = [];
for (var i = 0; i < data.items.length; i++) {
newsArray[i] = (data.items[i].title);
}
console.log(newsArray);
listTicker({
list: newsArray,
startIndex: 0,
trickerPanel: $('#newsPanel'),
interval: 3 * 1000,
});
})
}
rss();
});
</script>
<div id='newsPanel' />

Initializing javascript objects with variables that are functions within a for loop -- how to avoid overwriting?

I have this code:
for(i = 0; i < 1; i++){
$("body").append(questions[i]);
for(j = 0; j < prompts.length; j++){
var temp_id = "slider-" + j;
var temp_num_text_id = "slider-text-" + j;
var temptextdiv = $("<h5>50</h5>");
$("body").append(temptextdiv);
temptextdiv.attr('id', temp_num_text_id);
var tempdiv = $("<div></div>");
$("body").append(tempdiv);
tempdiv.attr('id', temp_id);
$("#" + temp_id).slider({
min: 0,
max: 100,
value: 50,
slide: function(event, ui){
$("#" + temp_num_text_id).html(ui.value);
}
});
}
}
The goal is to have one question with various prompts about the question, each being a ranking done on a jquery-ui slider. My trouble is trying to 'link' the text that displays the value of the slider with the slider itself. When I was testing this out with one slider it was as simple as the function within the declaration of the slider object shown above, but when this is done within a loop, all of the sliders only change the text value of the last slider. As I understand it from similar questions others have had, every iteration of the loop overwrites the previous declaration. How do I avoid this?
As I mentioned in the comment, all id attributes should be unique. This can be done by assigning a consecutive number to the ids.
For example: https://jsfiddle.net/Twisty/vLut8ysw/
JavaScript
var questions = [
"<div id='q1'>Question 1</div>",
"<div id='q2'>Question 2</div>",
"<div id='q3'>Question 3</div>",
"<div id='q4'>Question 4</div>",
"<div id='q5'>Question 5</div>",
];
var prompts = [
25,
50,
75,
];
var promptIds = 0;
$(function() {
$.each(questions, function(q, i) {
$(i).appendTo("body");
$.each(prompts, function(p, j) {
var temptextdiv = $("<h5>", {
id: "p-slider-text-" + promptIds
}).html(j).appendTo("body");
var tempdiv = $("<div></div>", {
id: "p-slider-" + promptIds
}).appendTo("body");
tempdiv.slider({
min: 0,
max: 100,
value: j,
slide: function(event, ui) {
temptextdiv.html(ui.value);
}
});
promptIds++;
});
});
});
This will create unique ids for each slider.

Trouble clearing object from array using buttons (jquery)

I'm attempting to move an image and data-id attribute from one section of divs, to a placeholder section of divs. I also want to be able to splice out those objects from the array when clicking the 'remove' button from either section.
It's mostly working by targeting the 'data-id' attribute and then performing the actions I want it to - but I'm running into one bug.
https://jsfiddle.net/kgmucdac/
$(document).ready(function() {
var selections = [];
var prodLength = 4;
var arrayVal = "";
$(".killThis").click(function() {
killCount();
});
$("#products").on('click', '.add', function () {
$(this).removeClass('add');
$(this).addClass('removeTop');
$(this).text("remove");
$('.remove').show();
arrayVal = ($(this).data('id'));
if (selections.length <= prodLength) {
selections.push({src: $(this).parent().find('img').attr('src'),vid: $(this).data('id')});
}
addProd();
console.table(selections);
});
$("#products").on('click', '.removeTop', function () {
arrayVal = ($(this).data('id'));
$(this).removeClass('removeTop');
$(this).addClass('add');
$(this).text("add");
nukeProd();
cleanArray();
drawProds();
});
$('#placeholders').on('click', '.remove', function () {
arrayVal = ($(this).data('id'));
console.log(arrayVal);
nukeProdReverse();
cleanArray();
tempClear();
drawProds();
})
function drawProds() {
var prods = $('#placeholders').find('.placeholder');
for (var i = 0; i < prods.length; i++) {
var prod = prods[i];
var selection = selections[i];
if ((selection != undefined)) {
$(prod).find('img').attr('src', selection.src);
$(prod).find('.remove').attr('data-id', selection.vid)
} else {
$(prod).find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$(prod).find('.remove').css('display', 'none');
}
}
}
function addProd() {
drawProds();
}
function nukeProd() {
$('.placeholder[data-id="' + arrayVal + '"]').find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$('.remove[data-id="' + arrayVal + '"]').attr('data-id', '');
}
function cleanArray() {
for(var i = 0; i < selections.length; i++) {
if(selections[i].vid == arrayVal) {
selections.splice(i, 1);
break;
}
}
console.table(selections);
}
function nukeProdReverse() {
$('.placeholder[data-id="' + arrayVal + '"]').find('img').attr({
'src': 'https://i.imgur.com/D6MQP01.png'
});
$('.remove[data-id="' + arrayVal + '"]').removeAttr('data-id');
$('.removeTop[data-id="' + arrayVal + '"]').text("add");
$('.removeTop[data-id="' + arrayVal + '"]').addClass('add');
$('.removeTop[data-id="' + arrayVal + '"]').removeClass('removeTop');
}
function tempClear() {
$('.remove').removeAttr('data-id');
}
function killCount() {
console.log(arrayVal);
}
});
That's my JSFiddle that I've been working on. When I add the products in any order from the top row, I can delete them using the top row's remove buttons, no issues.
However, using the bottom row's 'remove' buttons, I can only remove them all if I start from right to left (4th, 3rd, 2nd, 1st)... If I remove them in any other order, e.g., the 3rd, the one that slides into its place will not work correctly.
I think it has something to do with the index incrementation but I'm kind of at the end of my road on this in terms of what I know how to do/cobble together.

Mouse actions possible on all id tags on a webpage

What I want to do is, find all possible actions (click , hover, etc) on each element id on a web page.
Below is my effort towards it:
function executeInteractions($) {
for (var interaction_count = 0; interaction_count < interactions.length; interaction_count++) {
var obj = interactions[interaction_count];
for (var event_count = 0; event_count < obj.events.length; event_count++) {
(function(elem, event_name, e_count, i_count, t_i_count) {
setTimeout(function() {
elem.trigger(event_name);
var sendData = {id : elem.attr('id') , event_n: event_name }
&.post("link#",sendData)
setTimeout(function() {
}
}, 10);
if (i_count + 1 >= t_i_count) {
window.interactionsComplete = true;
}
}, 500 * i_count);
}(obj.item, obj.events[event_count], event_count, interaction_count, interactions.length));
}
}
}
function findInteractions($) {
$(document).click(function(e) {
e.preventDefault();
});
$(document).submit(function(e) {
e.preventDefault();
});
var node, toBeProcessed = new Array;
toBeProcessed.push($('body')[0]);
while (toBeProcessed.length) {
node = $(toBeProcessed.pop());
var eventObject = node.data('events');
if (eventObject) {
var events = [];
for (var e in eventObject) {
events.push(e);
}
interactions.push({
'item': node,
'events': events
});
}
var childrens = node.children();
if (childrens && childrens.length > 0) {
for (var i = 0; i < childrens.length; ++i) {
toBeProcessed.push(childrens[i]);
}
}
}
}
window.interactions = [];
When the post request is received at the server end, I get lot of null values for id.
Can someone help me out here, or may be suggest any other efficient method to capture all possible actions on id elements on a web page.
You can apply unique class to each attribute on page and then write .click()/.mouseover() JQuery event on it.
HTML:
<p class="uniqueClass">1st para</p>
<p class="uniqueClass">2nd para</p>
JQuery code:
<script>
$( ".uniqueClass" ).click(function() {
alert("Clicked");
});
</script>
For mouse over, you can use .mouseover() function like:
<script>
$( ".uniqueClass" ).mouseover(function() {
alert("Mouse Over");
});
</script>

Hide a column in flexigrid

Is there a way to hide and show a column in jQuery flexigrid like this?
$('#FlexigridID').hideCol('ColumnName');
$('#FlexigridID').showCol('ColumnName');
New code tested:
$(function () {
var visible = true;
$('#yo').click(function () {
alert('hello');
visible = !visible;
showColumn('#yourFlexigridNameHere', 'Lastname', visible);
});
});
// you can put this in a separate javascript library
function showColumn(tbl, columnName, visible) {
var grd = $(tbl).closest('.flexigrid');
var colHeader = $('th[abbr=' + columnName + ']', grd);
var colIndex = $(colHeader).attr('axis').replace(/col/, "");
// queryVisible = $(colHeader).is(':visible');
// alert(queryVisible);
$(colHeader).toggle(visible);
$('tbody tr', grd).each(
function () {
$('td:eq(' + colIndex + ')', this).toggle(visible);
}
);
}
HTML:
<input id='yo' type="button" />
You can also set the hide to false on flexigrid's colModel setup:
colModel: [
{display: 'Row ID', name : 'Lastname', width : 100,
sortable : true, align: 'left', hide: false}
You can also add a method against flexigrid, you can put this in a separate javascript library:
(function ($) {
$.fn.showColumn = function (columnName, visible) {
if (visible == undefined) visible = true;
var grd = this.closest('.flexigrid');
var colHeader = $('th[abbr=' + columnName + ']', grd);
var colIndex = $(colHeader).attr('axis').replace(/col/, "");
$(colHeader).toggle(visible);
$('tbody tr', grd).each(
function () {
$('td:eq(' + colIndex + ')', this).toggle(visible);
}
);
};
$.fn.hideColumn = function (columnName) {
this.showColumn(columnName, false);
}
})(jQuery);
You can now invoke hiding and showing using these:
$('#FlexigridID').hideColumn('ColumnName');
$('#FlexigridID').showColumn('ColumnName');
visible = !visible; // for toggling need
$('#FlexigridID').showColumn('ColumnName', visible);
Try this:
$('#FlexigridID').find("tr td").eq(columnIndex).hide();
$('#FlexigridID').find("tr td").eq(columnIndex).show();
Try something like this
$('td:nth-child(2)').hide();
for table with header(th)
$('td:nth-child(2),th:nth-child(2)').hide();
Read more about Hide a Table Column with a Single line of jQuery code
$("#yourFlexigridNameHere").flexToggleCol(columnIndex, false);
//columnIndex - starts from 0

Categories

Resources