This is homework, just declaring it now.
I have to load a 'quiz' via XML (completed successfully), and generate td cells (done) to display said questions (not done, test data instead).
Here is my source code for the javascript
var selected;
var $cell;
var $cell2;
$(document).ready(function() {
$("#getTitle").click(function() {
selected = $("#quizname>option:selected").text();
$("#quiztitle").html(selected+" Quiz");
$("#quiz2").html(selected+" Quiz");
murl = "quizdata.xml";
$.ajax({type:"GET",
url:murl,
success:loaddata,
cache:false,
dataType:"xml",
data:selected,
error:ajaxerror
});
});
});
var $xml;
function loaddata(respobj,status,xhr) {
//to do:
//dynamic td creation for each xml question
$("#questions").empty();
$xml = $(respobj).find("quiz:contains("+selected+")");
for (var i=0;i<$xml.attr("qnum");i++) {
$('<tr>').attr("id","questions"+(i+1)).appendTo("#questions");
$("<td>").attr("id","question"+(i+1)).appendTo("#questions"+(i+1));
$("#question"+(i+1)).html((i+1)+". "+$xml.find("question[num='"+(i+1)+"']").text());
$("#question"+(i+1)).addClass("th.thirty");
$("<td>").attr("id","blank_question"+(i+1)).appendTo("#questions"+(i+1));
$("#blank_question"+(i+1)).addClass("question");
$("#blank_question"+(i+1)).html("Put Answer Here");
$("<td>").attr("id","answer"+(i+1)).appendTo("#questions"+(i+1));
$("#answer"+(i+1)).addClass("question");
$("#answer"+(i+1)).html((i+1)+". "+$xml.find("answer[num='"+(i+1)+"']").text());
$("#answer"+(i+1)).click(selectCell);
}
}
function selectCell() {
$cell = $(this);
$cell.css("background-color","red");
for (i=0;i<$xml.attr("qnum");i++) {
$("#blank_question"+(i+1)).click(function() {
$cell2 = $(this);
$cell.css("background-color","lightgray");
temp_text = $cell.text();
temp_id = $cell.attr("id");
$cell.attr("id",$cell2.attr("id"));
$cell.text($cell2.attr('id'));
$cell2.attr("id",temp_id);
$cell2.text(temp_id);
$("#answer"+(i+1)).unbind("click");
$("#answer"+(i+1)).bind("click", function() {
selectCell();
});
});
}
}
function swapCell() {
$cell.css("background-color","lightgray");
alert($(this).attr("id"));
}
function ajaxerror(xhr,status,error) {
$("td#desc").attr("class","");
$("td#desc").html("xhr="+xhr);
$("td#desc").append("<br /><br />status="+status)
$("td#desc").append("<br /><br />error="+error);
}
My issue is (try it here: HomeWork Link) that the first time you click the first cell, swap it with the second, it works. However, it only works every OTHER click and swap, which makes me think that there are some binding issues or focus issues because I need it to swap seamlessly. Is there an obvious error in the code or am I missing a specific focus/bind event?
Thanks!
Edit: the values being displayed AFTER swapping are the cells ID attribute
After googling "jquery recursive .click binding" I found that instead of .click() I changed it to .live() and that works perfectly.
Related
var myTimelineVis = {
loadData: function(visItems, visContainer, visOptions, visTimelines) {
$.getJSON('myURL/' + $(this).val(), function(data) {
visItems.clear();
$.each(data, function(i, imp_sched_events) {
$.each(imp_sched_events.items.timeline_dataset, function(i, item) {
visItems.add(item);
if ($(visContainer).is(':empty')) {
visTimeline = new vis.Timeline(visContainer, visItems, visOptions);
} else {
visItems.update(item);
}
visTimeline.fit();
$('.vis-item-content').foundation();
});
});
});
},
setData: function(selectClass) {
var visItems = new vis.DataSet(),
visContainer = document.getElementById('visualization'),
visOptions = {},
visTimeline = '';
$(selectClass).on('change', function(visItems, visContainer, visOptions, visTimelines) {
this.loadData(visItems, visContainer, visOptions, visTimelines);
});
}
}
$(document).ready(function() {
myTimelineVis.setData('select.implementation_schedule');
});
I am trying to trying to create a vis timeline on page load and then load data onto it when my select changes (I have two selects). On page load, I can see the change event binding to both selects within Chrome console, but nothing happens, not even an error, on the actual select change. It just acts like they don't exist.
Is this is a scope issue?
For jQuery, the listener would not be added in an Ajax call, but in the $(document).ready(). It works differently than vanilla JavaScript.
If the select is dynamically changed you would need to use the following syntax with a hard-coded selector. The selector can be broad like "#myForm select". There's no need to use a variable.
$(document).on('change', '.selectClass', function(visItems, visContainer, visOptions, visTimelines) {
this.loadData(visItems, visContainer, visOptions, visTimelines);
});
});
In an HTML file, I use JS to generate table rows to show data returned by database:
function appendResult(data) {
var result = JSON.parse(data);
var row = result.length;
if (row == 0) {
$("#productList").html("No matching result.");
} else {
$("#productList").html("");
var i = 0;
while (i < row) {
// For each return record, create a new row, then write data into cell accordingly. New records are always written to last cell.
$("#productList").append("<tr class='hightLight'><td class='sku'></td><td class='productName'></td><td class='description'></td><td class='qtyPerCtn'></td><td class='weight'></td><td class='upc'></td><td class='gtin'></td><td class='vendorCode'></td><td class='note'></td></tr>");
$("td.sku").last().html(result[i]["sku"]);
$("td.productName").last().html(result[i]["productName"]);
$("td.description").last().html(result[i]["description"]);
$("td.qtyPerCtn").last().html(result[i]["qtyPerCtn"]);
$("td.weight").last().html(result[i]["masterWeightLb"]);
$("td.upc").last().html(result[i]["UPC"]);
$("td.gtin").last().html(result[i]["gtin"]);
$("td.vendorCode").last().html(result[i]["vendorCode"]);
$("td.note").last().html(result[i]["note"]);
i++;
}
}
}
Then I have a function to highlight the row when the mouse rolls over it:
// high light row when mouse roll over
$(document).ready(function () {
$(".hightLight").hover(function () {
$(this).addClass("highLightOnRollOver");
}, function () {
$(this).removeClass("highLightOnRollOver");
});
});
But apparently this doesn't work. The highlight function doesn't work. But if I put a row in plain html, it works:
<table>
<tr class="hightLight"><td>test</td></tr>
</table>
Does it mean JS functions can't identify the elements generated by JS? How can I solve this problem?
This will work even if you add elements after the dom is ready:
// high light row when mouse roll over
$(document).ready(function () {
$("table")
.on('mouseenter', ".hightLight", function () {
$(this).addClass("highLightOnRollOver");
})
.on('mouseleave', ".hightLight", function () {
$(this).removeClass("highLightOnRollOver");
});
});
You'll have to use delegation, like this:
$(document).on("hover", ".hightLight", function () {
If the javascript is sourced before the DOM is created, it wont see it. Delegation gets around it by saying "look for a hover within document, if that hover is within .hightLight, then do this...
You could replace also document with a closer parent of .hightLight... it looks like #productList would probably work well.
Im trying to code a site where the objective is to click on two identical images and it hides the both the images you've managed to match to eachother.
$(document).ready(function(){
var animal1;
var animal2;
$(".memory1").on("click", function(){
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function(){
animal2 = $(this).data('animal');
if (animal1==animal2){
$(this).data('animal').hide();
}
else {
alert("Wrong, Try again!");
}
});
});
so the line where its going wrong is obviously
$(this).data('animal').hide();
But I cant figure out a way to hide both images, or a better way of going about it.. :/
http://jsfiddle.net/4vgfca76/
This doesn't work the way you think it does
$(this).data('animal').hide();
When data is used with one argument, it get's the data attribute, which you should already know as you're doing it a few lines above.
What you get is the string hund etc. and that string doesn't have a hide() method.
You should be using the attributes selector to select the elements with that attribute instead
$(document).ready(function () {
var animal1, animal2;
$(".memory1").on("click", function () {
animal1 = $(this).data('animal');
});
$(".memory2").on("click", function () {
animal2 = $(this).data('animal');
if (animal1 == animal2) {
$('img[data-animal="'+animal1+'"]').hide();
} else {
alert("Fel! Försök igen");
}
});
});
I've been wrestling with a simple JQuery event handler for hours.
My event handler fires exactly once, when the page loads, and never again no matter the event or the interaction with the select box.
When deferred, the alert (when I have one) shows the first select option. When not, the alert is blank.
All I want is for the select box to load from AJAX and for a user choice to trigger another AJAX call.
HTML:
<select id="connection" name="Connection"></select>
<div id="testme" style="background: #CCC; width:100%; height:50px;position:relative;color:red">testing</div>
Javascript:
$(document).ready(function () {
// Event handler. Tried as a separate function and as a parameter to $.on(...)
function connectionSelected() {
var str = $('#connection option:selected').text();
alert(str);
$("#testme").text(str);
}
var $connectionSelect = $('#connection');
//$connectionSelect.selectmenu(); // Tried enabling/disabling
// Tried this and all JS code inside and outside of $(document).ready(...)
$.when(
$.ajax({
dataType: "JSON",
url: '#Url.Content("~/API/ConnectionHint")', // The AJAX call (using ASP Razor) works fine
success: function(data) {
// This function is always called and works
var items = [];
$.each(data, function(key, val) {
items.push("<option value='" + key + "'>" + val + "</option>");
});
$connectionSelect.append(items.join(""));
// Tried setting up the event handler here
},
error: function() {
$connectionSelect.html('<option id="-1">none available</option>');
}
})
).then(function() {
//$("#connection option").blur(connectionSelected()).change();
$("#connection").on("change", connectionSelected());
});
});
Tried dozens of variations of the event handler, several events, inside and outside of a deferred.done and deferred.then, etc.. E.g.:
$connectionSelect.selectmenu({
change: function (event, data) {
$('#connection').change(function () {
var str = "";
$('#connection').each(function () {
str += $(this).text() + "<br>";
});
$("#testme").text(str);
});
}
});
I usually write back-end code and am familiar only with portions of JQuery, and this is driving me crazy. I've looked more than 30 related question on SO and elsewhere, e.g.
Jquery event fires once
Jquery .change() function not working with dynamically populated SELECT list
http://jqueryui.com/selectmenu/#product-selection
Any ideas are appreciated.
Instead of
$("#connection").on("change", connectionSelected());
try
$("#connection").on("change", connectionSelected);
Note that in the second one I'm passing your function handler by reference, instead of invoking it.
I am using jquery to add mulitple new "addTask" form elements to a "ul" on the page every time a link is clicked.
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
saveTask();
});
These new nested ul elements all have an button with the same class "saveTask". I then have a function that allows you to save a task by clicking on an button with the class "saveTask".
// Save New Task Item
function saveTask() {
$('.saveTask').click(function() {
$this = $(this);
var thisParent = $this.parent().parent()
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
}
This essentially allows the user to enter some text into a form input, hit save, and then the task gets saved into the database using ajax, and displayed on the page using jQuery.
This works fine when there is only one element on the page with the class "saveTask", but if I have more than 1 form element with the class "saveTask" it stops functioning correctly, as the variable "var task" shows as "undefined" rather than the actual value of the form input.
Don't rely on the .parent() method. Use .closest('form') instead. So the following line:
var thisParent = $this.parent().parent()
should look something like this instead:
var thisParent = $this.closest('form');
EDIT:
Based on the updated information you provided, it looks like when you're trying to register the click event handler it's failing out for some reason. Try this javascript instead as it will make use of the live event so that all the newly added items on the page will automatically have the click event autowired to them.:
$(function(){
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
});
$('.saveTask').live('click', function() {
$this = $(this);
var thisParent = $this.closest('ul');
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
});
First turn the save task into a function:
(function($){
$.fn.saveTask= function(options){
return this.each(function(){
$this = $(this);
$this.click(function(){
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
});
});
return false;
})(jQuery)
When the app starts change the saveTask selector to this:
function saveTask(){
$('.saveTask').saveTask();
}
Then on your add function:
function addTask(){
$newTask = $("<div>Some Task stuff</div>");
$newTask.saveTask();
}
This code is written very quickly and untested but essentially create a jQuery extension that handles for data submission then when ever a task is created apply the save task extension to it.
I think you're looking for the live event.
Also, your code is a little awkward, since the click event is only added when the saveTask() function is called. In fact, the saveTask() function, doesn't actually save anything, it just adds the click event to the elements with the .saveTask class.
What is your HTML structure?
It looks like your code can't find the input.taskName element.
Try setting thisParent to something like $this.closest('form'). (Depending on your HTML)
You could try wrapping your click function in an each()
ie
function saveTask(){
$('.saveTask').each (function () {
$this = $(this);
$this.click(function() {
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
})
}
I find this helps sometimes when you have issues with multiple elements having the same class