Append additional key values to a different <div> - javascript

I've got radios attached to divs, and when the div is clicked the info on the widget updates to display the data associated to the div. I'm getting the data from the Yahoo API with JSON script. The appropriate data is appearing on my div called "Current", but when I click on "24-Hour" I get nothing.
Check out my script on this fiddle: http://jsfiddle.net/thetuneupguy/r2Bca/11/
$.each(data.query.results.quote, function (key, obj) {
var $lc = $('<tr/', {
'class': 'my-new-list'
}).appendTo('#blk-2 table');
$lc.append($('<td/>').text(obj.Name || "--"));
$lc.append($('<td/>').text(obj.PreviousClose || "--"));
});

It appears that I forgot to close out a tag, which I have caught and fixed...
var $lc = $('<tr/', {
should be...
var $lc = $('<tr/>', {

Related

how to use $(this) with foreach in javascript using jquery

I am working on a personal project in Javascript to allow people to create a table of "dream plays" in Scrabble. Here is the link: http://psyadam.neoclaw.net/tables8.html
I am currently trying to allow the user to edit a dream play.
Here is my code:
function editRow(e)
{
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
$(this).children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success"
$(this).addClass('selected')
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
// insertRow assumes that the correct row in the table has the "selected" class added to it
function insertRow()
{
var Row = $('<tr>').append(
$('<td>').append('<input id="input1">'),
$('<td>').append('<select id="input2"><option value=""></option><option value="Yes">Yes</option><option value="No">No</option></select>'),
$('<td>').append('<select id="input3"><option value=""></option><option value="Natural">Natural</option><option value="1 Blank Used">1 Blank Used</option><option value="2 Blanks Used">2 Blanks Used</option></select>'),
$('<td>').append('<select id="input4"><option value=""></option><option value="vs Computer">vs Computer</option><option value="Online Game">Online Game</option><option value="Friendly Game">Friendly Game</option><option value="Club Game">Club Game</option><option value="Tournament Game">Tournament Game</option></select>'),
$('<td>').append('<input id="input5">')
)
$("#myTable tr.selected").after(Row)
}
Right now I'm just trying to get my code to insert a row into the table. I am trying to do this by using the code $(this).addClass('selected') to tag the row the user selected and then use it in my insert function to insert a row. However, nothing seems to happen. I am using pageEnd.innerHTML += "success" as a debugging tool to see if it is even getting there. Unexpectedly, it prints success twice when it should only print once, as in the test I ran every word was unique.
In any case I can't figure out why it's not working. Any help is appreciated. Thanks, ~Adam
You have two options to achieve this:
The first one as the others are suggesting i.e. by keeping a variable of outer this and then using this:
$('tr').each(function() {
var outerThis = this;
// inside another loop (not sure about children method, just an example)
$(outerThis).children("td:contains(test)").each(function() {
// do something with outerThis to operate on further
});
});
Another option to use Javascript's bind() method:
$('tr').each(function(i, trElement) {
// this == trElement
// inside another loop
$(outerThis).children("td:contains(test)").each(function(index, tdElement) {
$(this) // will be now tr element
$(tdElement) // will be td element
}.bind(this));
});
Try this:
function editRow(e) {
var eventEl = e.srcElement || e.target,
parent = eventEl.parentNode
parent = parent.parentNode
var test = $(parent.cells[0]).text()
$('tr').each(function(){
var outerThis = this;
outerThis.children("td:contains(test)").each(
function()
{
pageEnd.innerHTML += "success";
$(this).children().css('text-align', 'center');
}
)
})
pageEnd.innerHTML += test
//pageEnd.innerHTML += $(parent.cells[3]).text()
insertRow()
}
I set the outer this to a variable which you can use. Also textAlign is not a jQuery function. You need to use .css() and then specify text-align in that.

How to pass an attribute to the function hover?

I have a table which is populated taking data from an array of contacts. I need to pass to the function hover one of each contact data (your image). How could he?
Here is the code of the dynamic creation of each row.
What would have to put behind tr, to capture it on hover?
for(var i in tbContactos)
{
var contacto = JSON.parse(tbContactos[i]);
$("#tblList tbody").append("<tr alt="+contacto.Imagen+">");
.....
.....
$("#tblList").hover(function(event){
var src = $(this).attr("alt");
............
............
To attach hover event you can use .on(), see below code -
$("#tblList tbody").on("mouseenter","tr",function(){
// do stuff for mouse enter event
var trAttr = $(this).attr('alt');
}).on("mouseleave","tr",function(){
// do stuff for mouse leave event
var trAttr = $(this).attr('alt');
});
try this:
$("#tblList tbody").append("<tr onMouseOver='test(this)' alt="+contacto.Imagen+">");
function test(row){
//here you will get the entire row.
row.getElementsByTagName("td")//will return an array of columns within the row
}

javascript editable table does not work properly

I am using the following code to make a html table editable (this code is obtained from an online tutorial link: http://mrbool.com/how-to-create-an-editable-html-table-with-jquery/27425).
$("td").dblclick(function () {
//Obtain and record the value in the cell being edited. This value will be used later
var OriginalContent = $(this).text();
//Addition of class cellEditing the cell in which the user has double-clicked
$(this).addClass("cellEditing");
//Inserting an input in the cell containing the value that was originally on this.
$(this).html("<input type='text' value='" + OriginalContent + "' />");
//directing the focus (cursor) to the input that was just created, so that the user does not need to click on it again.
$(this).children().first().focus();
//the opening and closing function that handles the keypress event of the input.
//A reserved word this refers to the cell that was clicked.
//We use the functions first and children to get the first child element of the cell, ie the input.
$(this).children().first().keypress(function (e) {
//check if the pressed key is the Enter key
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
It seems to work fine. Then I am using the following function to read the contents of the table and create a json representation:
function showRefTable(){
var headers = [];
var objects = [];
var headerRow = $('#dataTable thead tr');
var rows = $('#dataTable tbody tr');
headerRow.find('th').each(function(){
headers.push($(this).text());
});
for (var i=0; i<rows.length; i++){
var row = rows.eq(i);
var object = new Object();
for (var j=0; j<row.find('td').length; j++){
object[headers[j]] = row.find('td').eq(j).text();
}
objects.push(object);
}
var json = JSON.stringify(objects);
alert(json);
}
This function is used as a callback to an onclick event.
The problem is that the function used to read the table contents shows the original contents even if I make an edit (show page source shows the original content).
Thanks
It's really bad to read table contents from .text(). You will not be able to use any formatting for numbers and many other problems. You'd better of keeping table contents in standalone datasourse object and redrawing table from it every time when user changes values.
I would advise using kendo grid - it's powerfull, reliable js table.
EDIT: your function does not work, becuse you said you call it as callback to onclick event. So you read contents of the table before they actually changed.
You should read contents when they are saved. In your case, try calling you function when user saves the input (presses Enter)
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
//Now, when content is changed, call your function
showRefTable();
}

Getting the content of the first cell from a dynamically created element inside another cell

I am unable to retrieve the content of the first cell. I'm trying it like this:
console.log($(this).closest("tr").find('td:first').innerHTML);
//or...
console.log($('td:first', $(this).parents('tr')).text());
Code:
$('.editable').click(function () {
var text = $(this).text();
if (typeof $(this).find("textarea")[0]=="undefined")//checking if we have a textarea already
{
$(this).text('');
$('<textarea />').appendTo($(this)).val(text).select().blur(function () {
var newText = $(this).val();
$(this).parent().text(newText).find('textarea').remove();
console.log($(this).closest("tr").find('td:first').innerHTML);
});
}
});
JSfiddle: http://jsfiddle.net/KjknL/
I think the problem has to do with the textarea being added dynamically. But I cannot move from it. If I use .prev() or .next(), it returns empty. Any ideas?
try this: http://jsfiddle.net/KjknL/2/
the textarea doesn't exist anymore because you removed it just before trying to reach the first td from it.
console.log($(this).closest("tr").find('td:first').html());
$(this).parent().text(newText).find('textarea').remove();

Jquery mobile - Click button to add to UL

i am trying to build an application that when the user enters text into a textbox on a jquery based mobile app and clicks save it adds it to the list on the screen
so by default i won't have a list, but as the user adds an item the list should be created or if the list already exists, the new item added as a new list item.
in terms of saving it i will work on that after, for the time being i just want to dynamically append to a ul in jqm on the screen
Can someone assist with code that may help with this. it is giving me an item added saying "item undefined" however numslist is my list and txtbox is the textbox so im not sure where i am going wrong
thanks
<script>
var $txtbox = $("#txtbox").val();
var count = 0;
$("#main").live("pagecreate", function(event) {
$("#numlist").listview({create: function(event, ui) {
$("#addBtn").bind("click", function(event, ui) {
var str = "<li><a href='#'>Item " + ($txtbox) + "</a></li>";
$("#numlist").append(str);
$("#numlist").listview("refresh");
});
$("#removeBtn").bind("click", function(event, ui) {
// if (--count < 0) {
// count = 0;
// return;
// }
$("#numlist").find("li").remove();
$("#numlist").listview("refresh");
});
}});
});
</script>
Well, you can use localstorage, that way you won't need to code extra functions that save/store data.
try this:
var $lst = $('#productList');
$("#btnID").on("click",function() {
var $txtBox = $("#txtBox");
var $li = $('<li/>').html($txtBox.val());
$lst.append($li).listview('refresh');
$txtBox.val("");
});
working fiddle here: http://jsfiddle.net/REthD/21/
If I understood your question correctly, something similar to the following should work for you:
$('input[type=button]').on('click', function() {
var ul = $('#ul_id').length > 0 ? $('#ul_id') : $('<ul />', { id: 'ul_id'}).appendTo('#parent');
$('<li />').text($('#textbox').val()).appendTo(ul);
});
The first line in the event will check if the element exists, if it does, it returns that, otherwise, creates a new and appends to the specified parent element. Then, it appends a to the with the text from the textbox.
jsFiddle example

Categories

Resources