Dynamically Moving Through Hidden Tables With jQuery - javascript

I'm having issues moving through a sequence of Hidden Divs that will eventually turn into Tables on another page that I am working on and the issue that I am running into is that the jQuery Javascript code does not seem to be responding to calls.
My JS Fiddle Example:
http://jsfiddle.net/qwertycody/QUprb/3/
My Actual Applied Work:
http://www.voyagersclan.com/scripts/pokemon/poke_pc.php
<script type="text/javascript" src="jquery.js"></script>
<script>
var currentID = 1;
$(function() {
$('#left').on('click', function(){
var currentDiv = '#' + currentID;
$('currentDiv').hide(500);
currentID = currentID - 1;
currentDiv = '#' + currentID;
$('currentDiv').show(500);
})
});
$(function() {
$('#right').on('click', function(){
var currentDiv = '#' + currentID;
$('currentDiv').hide(500);
currentID = currentID + 1;
currentDiv = '#' + currentID;
$('currentDiv').show(500);
})
});
</script>
Above is a code sample of my Javascript that doesn't seem to work correctly.
The overall goal of this is to be able to move through dynamically generated Tables with Individually Assigned Divs that can freely be Shown and Hidden at the press of a button.

Your answer is very close! The problem is that your selector is using a string, instead of the variable you intialized!
var currentDiv = '#' + currentID;
$(currentDiv).hide(500); // works!
$('currentDiv').hide(500); // gets an element of type "currentDiv"
Look at this updated JSFiddle.
I also added some bounds checks into your event handlers. This way you can only scroll through the available tables (1-4).

Related

jQuery $.load Not Executing

I am currently using jQuery on my Django site to reload a div once a user clicks a button.
$(document).ready(function(){
var post_list = Array.from(document.getElementsByClassName("post_container"))
for(var post in post_list){
post_list[post].id = 'post' + post;
}
var $arrows = $(".arrow");
$arrows.each(function(index){
var data = $(this).data();
var element = $(this);
element.on('click', function(event){
if(user_auth){
var currentParentElement = element.parent().parent().parent().get(0);
var id = $(currentParentElement).attr('id');
$(id).load(document.URL + ' ' + id);
}
})
})
});
From the console I can see that currentParentElement and id are pointing to the correct div to reload, but $(id).load() does not seem to be doing anything.
In the image linked below, the clicking the arrow buttons should make the green or red number change. The number does not change when the arrow is clicked, but it does change when I reload the entire page.
https://i.stack.imgur.com/T26wn.png
Your ID selector is missing the # symbol. For example, suppose the id of this target element is "myID":
var id = $(currentParentElement).attr('id');
Then the jQuery selector you're using is:
$('myID')
Which is looking for a <myID> element. There isn't one, so no matches are found, so there's nothing to call .load() on.
You could add the symbol to your selector:
$('#' + id).load(document.URL + ' #' + id);
(Note: The same correction was also made in the selector passed to load() for the same reason.)

How to clone and place two different items in jquery in the respective positions

I have a div and a button to close that div. I am cloning them both separately and assigning a unique incrementing id to both. Everything is working in that the cloning happens and the button closes the Div.
I have a problem though regarding the placement of the button. I want the button to always be in the same position with reference to its cloned div. Any ideas how to do this?
HTML
X
<div id="id"></div>
Add
Javascript
function duplicateDiv(){
$('#btn').clone().attr('id', 'btn'+ cloneCount2++).insertBefore($('[id^=id]:first'));
$('#id').clone().attr('id', 'id'+ cloneCount++).insertAfter($('[id^=id]:first'));
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj){
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#"+divId).hide();
$("#"+currentId).hide();
}
If interpret Question correctly , try using .appendTo() , .insertAfter($("#btn" + cloneCount))
var cloneCount = 0, cloneCount2 = 0;
function duplicateDiv() {
//the close button
$("#btn")
.clone().attr("id", function(_, id) {
return id + (++cloneCount2)
})
.appendTo("body")
$("#id")
.clone().attr("id", function(_, id) {
return id + (++cloneCount)
})
.insertAfter($("#btn" + cloneCount))
//clearing the input items in the new cloned div
$("#id").find("input").val("");
}
function hideDiv(obj) {
var currentId = $(obj).attr('id');
var divId = currentId.replace("btn", "id");
$("#" + divId).hide();
$("#" + currentId).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
X
<div id="id">div</div>
Add
One of the way is Jquery Offset
var destination = $('.original-content').offset(); // get position of original
$('.original-content').hide(); // hide original
$('.cloned-content').css({top: destination.top, left: destination.left}); // set position of cloned

For Loop to Programmatically hide elements

I am currently trying to programmatically hide div elements on a page using an Array and loop in jQuery, but it doesn't seem to work.
I have done alerts and console.log to confirm the array is firing and the loop is working through the items, but it's the .hide() method that seems to be giving issue. Any help would be appreciated.
Thanks
$(document).ready(function(){
var divsToHide = ["fin_0", "fin_1", "fin_2", "fin_3", "fin_4", "fin_5",
"fin_6", "fin_7", "fin_8", "fin_9", "fin_10", "fin_10-1", "fin_10-2", "fin_10-3",
"fin_10-4", "fin_10-5", "fin_10-6", "fin_10-7", "fin_10-8", "fin_10-9", "fin_20",
"fin_21", "fin_22", "fin_23"];
$.each(divsToHide, function(index, value)
{
var currentDiv = "div#" + value;
var stringCurrent = currentDiv.toString();
var currentHide = $(' stringCurrent ');
console.log(currentDiv);
currentHide.hide();
});
});
You should probably use:
var currentHide = $(stringCurrent);
Your code
var currentHide = $(' stringCurrent ');
has no reference to stringCurrent variable, it just try to find <stringCurrent> element.
Even better, you should use
$.each(divsToHide, function(index, value)
{
$("#" + value).hide()
});
since an element id should be unique to the document
You need to remove the ' around stringCurrent. Otherwise your string is not interpreted but jquery searches for ' stringCurrent '

Limit the input in Fieldset

I am trying to create a section of my webstore where the customer can 'build' their own bundle and choose any combination of 5 items.
I have a set of buttons which, when clicked, add their value to a Fieldset along with a button to remove it in case they misclicked or changed their mind.
All the components work fine, but I don't know how to limit the Fieldset to only five items. Is there a way to either count the lines, then stop accepting input
after five or look for 'Remove' five times?
I'm still fairly new to coding and not too sure what is possible.
This input will end up being submitted in a form.
Here is my Fiddle and below is my Javascript code which i have tried for it :
$(document).ready(function () {
$(".buttons").click(function () {
var intId = $().length + 1;
var item = $(this).html();
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
removeButton.click(function () {
$(this).parent().remove();
});
fieldWrapper.append(size);
fieldWrapper.append(removeButton);
$("#buildyourkit").append(fieldWrapper);
});
});
This will give you the current quantity of elements added to the . Just make sure that there is still room for another before appending a new one.
$("fieldset .fieldwrapper").length
I've forked your fiddle. Just look at the console while adding new items to the fieldset.
You can have a global variable which will count up and disable all buttons if over 5 every time you add a field, and down and enable all buttons every time you remove a field.
Also, it is a bit nicer to just set a live handler listening for any remove buttons, rather than make a new function and bind a new listener for each button, so I demonstrated; but it is not obligatory (your way works, too, given it's just 5 elements).
$(document).ready(function () {
var buttonMaxID = 0;
var buttonCount = 0;
$('$buildyourkit').on('click', '.remove', function () {
$(this).parent().remove();
if (buttonCount-- >= 5) {
$('.buttons').prop('disabled', false);
}
});
$(".buttons").click(function () {
if (++buttonCount >= 5) {
$('.buttons').prop('disabled', true);
}
var item = $(this).html();
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + (buttonMaxId++) + "\"/>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
fieldWrapper.append(size);
fieldWrapper.append(removeButton);
$("#buildyourkit").append(fieldWrapper);
});
});
What I propose is designing a manager class to maintain all functions/methods that must interact with the UI. This allows you to define your data set in one place, and keep the UI binds in one place. By doing so, you set yourself up with a cleaner code base, easy refactoring, and quickly make code modifications. Also, you get all this goodness without any global variables, another great bonus.
The code does look like its larger, but once you understand the simplicity of the manager you will see the possibilities I outlined above.
$(document).ready(function () {
//Create a new Kit Manager
var kitManager = new KitManager();
$(".buttons").click(function () {
kitManager.add(this);
});
$(".report").click(function () {
kitManager.getKit();
});
});
function KitManager()
{
//Static amount of items to return
var MAX_ITEMS = 5;
//Where the items should be visually displayed on the UI
var kitLegend = $("#buildyourkit");
//Internal array for storing the items added
var items = []
function add(element)
{
if(items.length < MAX_ITEMS)
{
var itemNumber = items.length + 1;
var item = $(element).html();
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + itemNumber + "\"/>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
//Add item to the array collection
items.push(item);
//Bind a remove function to the newly created button
removeButton.click(function () {
kitLegend[0].removeChild(fieldWrapper[0]);
items.splice(itemNumber, 1);
});
//Append UI components to container
fieldWrapper.append(item).append(removeButton);
//Append to main legend
kitLegend.append(fieldWrapper);
}
else
{
//Simple alert to user
alert('You\'ve Reached The Maximum Number of Items');
}
}
//Simple function for demonstration of a reporting feature
//or potential method for returning the stored items
function getKit()
{
for(var i=0,length=items.length;i <length;i++)
{
console.log(items[i]);
}
}
//Expose public method call
return {
add:add,
getKit: getKit
};
}
http://jsfiddle.net/x97S5/
I hope you find the solution acceptable, and if you have any further questions please ask.
For more information on the solution and technique proposed take a look at Key Principles of Maintainable JavaScript

Javascript running twice

I have to develop a small application for school and I first designed in photoshop a bit and "converted" it into html. That went all fine. I created a custom dropdown with javascript and it worked smoothly. I've just tried implementing CodeIgniter into the design but the javascript started running twice.
I've tried comparing the code of the plain html version with the codeigniter result but I can't seem to find any difference.
Can any of you maybe help me?
Here's the CodeIgniter result:
http://intellia.itforit.net/index.htm
As asked by Krof Drakula here are the most important pieces of code:
The actual jquery plugin: (styleForm.js)
;(function($){
$.fn.styleForm = function() {
var form = this;
/* Select */
$('select', this).each(function(){
var div = '<div class="styledSelect"><ul>';
var first = false;
$('option', this).each(function(){
var cssclass = "";
if(!first) {
first = true;
cssclass = 'class="first"'
}
div += '<li ' + cssclass + ' id="' + $(this).attr("value") + '">' + $(this).text() + '</li>';
});
div += '</ul></div>';
$(this).hide();
$(this).after(div);
});
$('.styledSelect ul').toggle(function(){
$('li:not(.first)', this).show("fast");
}, function(){
$('li:not(.first)', this).hide("fast");
});
$('.styledSelect ul li:not(.first):not(.selected)').click(function(){
var id = $(this).attr('id');
var content = $(this).text();
$('.styledSelect ul li.first').attr('id', id).text(content);
$('.styledSelect ul li').css({'font-weight': 'normal'});
$(this).css({'font-weight': 'bold'});
/* SELECT in Select form item */
var selected = $('select option[value="' + id + '"]:not(.first)', form).get(0);
selected.setAttribute("selected", "selected");
//$(form).submit();
});
};
})( jQuery );
And here's where it gets launched: (canvasDrawing.js)
$(document).ready(function(){
$('form').styleForm();
//Unimportant canvas stuff
});
Thanx in advance,
Duckness
The problem is that your canvasDrawing.js, in the "unimportant canvas stuff", causes a javascript error. If the canvas it describes actually exists, your styleForm stuff only runs once. So add this to your HTML:
<canvas id="floorplan"></canvas>
And magic will happen. Or, in your canvasDrawing file, add clause like this right after styleForm:
var canvas = document.getElementById('floorplan');
if (!canvas)
return;
I'm not actually all that clear why having an error in that function causes it to run twice, but it's definitely the problem. See it: your code + a canvas element = working.

Categories

Resources