so my javascript code is creating a list of table items, however I want it to able to change the color of the row according to what selections were made, each time a new item is added. Here's my code
if ( valid ) {
$( "#tasks2 tbody" ).append( "<div id='taskList'><ul class='taskScreen2'><tr>" +
"<td><h1>" + type.val() + "</h1></td>"+"<td class='title'><h3>"+ title.val() + " </td>" +"<td>"+ wordcount.val() + "</h3></td>" +"<td><p>"+ description.val() + "</p></td>" + "<td>"+ deadline.val() + "</td>"+
"</tr></ul></div>"
+ "<script> if ($('#type').val()=='Dissertation')"
+ "{document.getElementById('taskList').style.backgroundColor = 'red';} </script>"
);
This only changes the color of the top item while any new ones remains the same. I want it to change the bg colour of new item whenever it is added. I tried including the function both inside and outside the .append but it did not work. Any help would be greatly appreciated.
You are appending divs all with same ID's(which is wrong).Use class instead and it should work.
Try this:
if (valid) {
var ids=$("#tasks2, #taskList, #type");
for (var x=0; x<ids.length; x++) {
ids.get(x).className=ids.get(x).id;
}
ids.attr("id", "");
$(".tasks2 tbody").append("\
<div class='taskList'><ul class='taskScreen2'><tr>"
+"<td><h1>"
+type.val()
+"</h1></td>"
+"<td class='title'><h3>"
+title.val()
+"</td>"
+"<td>"
+wordcount.val()
+"</h3></td>"
+"<td><p>"
+description.val()
+"</p></td>"
+"<td>"
+deadline.val()
+"</td>"
+"</tr></ul></div>"
// Reply to Egidijus Poškus's comment: Here's how to do it!
+"<script>$(\".type[value='Dissertation']\").css('background-color', 'red');$(\".type[value='Report']\").css('background-color', 'blue');\
");
}
Related
How can I add dynamical drop down selects(set default selecte!) in dynamically table by using javascript and JSON.
I want to add many selects (dropdown) to every row in my table, and set the default text in the select. The table is created by using javascript append and has dynamic content imported from JSON files using Jquery.
I can import all content successfully, however the dropdowns can not set selected . I would appriciate if you guys can assist me to have the dropdown select. Thank you very much!
<script type="text/javascript">
...
$(target).append("<tr style='height:150px'>" +
"<td><input type='checkbox'></td>" +
"<td>pics</td>" +
"<td>" + menuItemName + "</td>" +
"<td id='"+menuItemId+"'>" +
"</td>" +
"<td class='menuItemPrice'>" + menuData.Categories[c].Items[i].Price + "</td>" +
"<td>mount</td>" +
"</tr>"
);
...
for (var o = 0; o < menuData.Categories[c].Items[i].Options.length; o++) {
var inputs = {isFirst: firstOption,
optionId: menuData.Categories[c].Items[i].Options[o].MenuItemOptionId,
optionName: menuData.Categories[c].Items[i].Options[o].MenuItemOptionName,
price: menuData.Categories[c].Items[i].Options[o].Price
};
$('#'+menuItemId).append("<div><select"+
"<option value='1'>small</option>" +
"<option value='2'>mid</option>" +
"<option value='3'>big</option>" +
"<option value='4'>very big</option>"+
"</select></div>"
);
here I want to set the default Select but can not success,please help me,Thank You!
$('#'+menuItemId).children(':selected').text(inputs.optionName);//here just can show the last size.
HTML
...
<tbody id="sortable">
First, your select tag does not have a closing angle bracket (>) so the HTML is malformed. It should be something like this:
$('#'+menuItemId).append("<div><select>"+
Second, you should use find instead of children because what you are looking for is multiple levels below the element identified by your selector, like so:
$('#'+menuItemId).find(':selected').text(optionName);
Here is a working example: https://jsfiddle.net/tLddsL2p/1/
I've been tearing my hair out over this seemingly simple problem, but I can't wrap my head around it.
I'm trying to generate a table in HTML using AJAX and some JQuery. The XML holds the data that I want rendered, each Child Node being rendered on a new line. The AJAX does all of the heavy lifting and generates the table.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<shows>
<show>
<title>Title</title>
<light>
<rule>Rule 1</rule>
<rule>Rule 2</rule>
</light>
<medium>
<rule>Rule 3</rule>
<rule>Rule 4</rule>
</medium>
<hard>
<rule>Rule 5</rule>
<rule>Rule 6</rule>
</hard>
<extreme>
<rule>Rule 7</rule>
</extreme>
</show>
</shows>
Obviously, I'll have more than this tiny bit of data down but that's besides the point.
Pertinent HTML
<table id="rules"></table>
And the Javascript:
$(xml).find('shows > show').each(function () {
var title = $(this).find('title').text();
title = "<tr>" + "<th>" + "</th>" + "<th>" + "<h1>" + title + "</h1>" + "</th>" + "</tr>";
category = "<tr>" + "<th>" + "</th>" + "<th>" + "Category Title: " + "</th>" + "</tr>";
rule = $(this).find('light > rule').text(); //problem is here?
punish = punish + "<tr>" + "<td>" + ruleCount + "</td>" + "<td>" + rule + "</td>" + "</tr>";
There's much more to the Javascript than this, but the line with the comment above I believe is the culprit of my headache. It's also essentially copied and pasted 3 more times in the script and modified to generate rules for medium, hard and extreme.
Here's the problem:
The Title, Category labels (table headers), rows, cells all generate just fine, but the data needs to be rendered so that each node (rule) is created on a new line (or new table row, essentially). Instead, the rule = $(this).find('light > rule').text(); line is cramming Rule 1 and 2 together, 3 and 4 together, etc (when reused further in the script obviously). The resulting HTML is a bit like this:
<table id="rules">
<tr><th></th><th><h1>Title</h1></th></tr>
<tr><td>1</td><td>Rule1Rule2</td></tr>
</table>
What I really want is for each rule to be on it's own table row. Like this:
<table id="rules">
<tr><th></th><th><h1>Title</h1></th></tr>
<tr><td>1</td><td>Rule1</td></tr>
<tr><td>2</td><td>Rule2</td></tr>
</table>
Any idea what I'm doing wrong??
Thanks in advance.
rule = $(this).find('light > rule').text();
This selects the two rule elements in light. text() returns a concatenation of the text of all elements in the wrapped set. You'll need to iterate over each rule using each()
$(this).find('light > rule').each(function() {
punish += "<tr><td>" + ruleCount + "</td><td>" + $(this).text() + "</td></tr>";
});
You need to use a loop to iterate through each rule
$(this).find('light > rule').each(function () {
punish = punish + "<tr>" + "<td>" + (ruleCount++) +"</td>" + "<td>" + $(this).text() + "</td>" + "</tr>";
})
I'm trying to follow the prof's example of creating an editable table on double clicking an entry in a HTML table. So my data method looks like this:
function formatData(message) {
var str = "<table border=1>";
for (var i = 0; i < message.length; i++) {
str += "<tr>" + "<td class='editable'>" + message[i].id + "</td>" +
"<td>" + message[i].name + "</td>" +
"<td class='editable'>" + message[i].url + "</td>" +
"<td class='editable'>" + message[i].desc + "</td>" +
"<td>" + "<a href='#' onclick='deleteRequest(this); return false' id='" + message[i].id + "'>delete</a>" + "</td>" +
" + "</td>" + "</tr>";
}
str += "</table>";
return str;
}
I bind a function edit() to the tags whose attributes are of class 'editable.' Then my edit function does:
function edit(elm) {
/* check to see if we are already editing */
if (elm.firstChild.tagName && elm.firstChild.tagName.toUpperCase() == "INPUT")
return;
/* save original content */
var orig = elm.innerHTML;
/* create edit field */
var input = document.createElement("input");
input.type = "text";
input.value = elm.innerHTML;
input.size = 20;
/* convert content to editable */
elm.innerHTML = '';
elm.appendChild(input);
/* position cursor and focus */
if (input.selectionStart)
input.selectionStart = input.selectionEnd = 0;
else
{
var range = input.createTextRange();
range.move("character", 0);
range.select();
}
input.focus();
/* set save trigger callback */
input.onblur = function(){save(elm, input,orig);};
}
I'm confused on how I would save the information and pass it to the web server to update. I need the id, url, and desc to update the web server. Since they double click on a table entry, that just gives me the element at that value, but I don't have the id. Do I change two lines in my formatData to:
"<td class='editable' id='" + message[i].id + "'>" + message[i].url + "</td>" +
"<td class='editable' id='" + message[i].id +"'>" + message[i].desc + "</td>" +
So that way I can ask the webserver for the url and desc with that id value? That seems like a bad way to do it since now two have the same id, but I'm not sure since I'm relatively new to AJAX, HTML, Javascript. Thanks.
Eh, I'll push a bit of help your way.
Basically, from what I gather you're binding a function to each td tag with editable. Well, you can determine the id inside that function.
B/c you can select the parentNode of the current node being edited, and then select the firstChild of that parentNode, so parentNode.firstChild which should be the first td, since remember on each row each of your td's will have a single parent tr. Then you select the firstChild of that td node, which is the text node it contains, and then grab its value, the id. So parentNode.firstChild.firstChild.nodeValue
This might not follow exactly with your code, as you only show parts of it... but this is the gist of the idea. Basically selecting nodes through the DOM and pulling the right one based on the current context.
I'd suggest playing around with it till you get it.
Here's a little bit of sample code for you to think about if you get stuck still. It's meant to be brief.
Basically, each middle column is tagged with the test function on the onfocus event (clicking inside the input). So it's on the input itself, and it pulls the parentNode td, then the next parentNode tr, then the firstChild of tr which is the first td then the firstChild of the first td which is the input on that row, then finally that input's value attribute.
<script>
function test(elem) {
alert( elem.parentNode.parentNode.firstChild.firstChild.value );
}
</script>
<table>
<tr><td><input value="1"/></td><td><input value="stuff" onfocus="test(this)"/></td><td>other stuff</td></tr>
<tr><td><input value="2"/></td><td><input value="stuff3" onfocus="test(this)"/></td><td>other stuff</td></tr>
<tr><td><input value="3"/></td><td><input value="stuff2" onfocus="test(this)"/></td><td>other stuff</td></tr>
</table>
I'm having a bit of trouble figuring out how to go about self-referencing a table row in Javascript.
Here's the boiled down code:
$( "#listitems tbody" ).append( "<tr onclick=\"editListItem(this)\">" +
"<td>" + id.val() + "</td>" +
"<td>" + title.val() + "</td>" +
"<td>" + description.val() + "</td>" +
"<td>" + TF + "</td>" +
"<td style=\"visibility: hidden;\">" + id.val() + "</td>" +
"</tr>" );
As you can see, I'm setting the contents of this table row and cells dynamically. However, I need to pass a reference to this table row into its onClick function, which calls this Javascript method:
function editListItem(obj) {
var id = obj.cells[4].innerHTML;
var cells = document.getElementById('listitems').rows[id].cells;
DATA[0] = cells[0].innerHTML;
DATA[1] = cells[1].innerHTML;
DATA[2] = cells[2].innerHTML;
DATA[3] = cells[3].innerHTML;
}
In this method, I need to access the value contained inside the 4th "hidden" cell of the table row that was clicked. I normally would just pass the ID variable into the onClick method, but this table's contents can be sorted and rearranged, so the ID variable will not necessarily correspond to the contents of the row.
I've been Googling for the past four hours but can't find any specific examples for this situation; everything I've tried just triggers a Javascript error proclaiming that obj.cells, obj[4], obj.childNodes, etc, does not exist, depending on which one I'm trying.
Does anyone know how you can access the innerHTML of table cell elements inside a table row element by passing "this" into the table row's onClick?
Please let me know if any part of this was confusing, I'm trying to get this done before I leave today or I know I'll forget it all and have to start all over.
how about:
$( "#listitems tbody" ).append(
$('<tr>....</tr>')
.bind('click', function(){
var tds = $(this).find('td'),
id = tds.eq(4).text();
})
);
And if that's not what you meant, let me know. I'm not 100% sure I understand what you're asking for :)
From the looks of your code, your using jQuery so you can easily grab the 5th td by using
$(this).children('td').eq(4)
and then do whatever you want with that jQuery element
checkout jQuery eq selector for more info
Create your <tr> element on its own first, and use proper JS to register the handler rather than embedding the handler in the element's attributes:
var tr = $('<tr>').click(editListItem);
$("#listitems tbody").append(tr);
$(tr).append( ... );
In editListItem, this will automatically apply to the whole row element:
function editListItem(row) {
var cells = $(this).children('td');
var id = $cells.eq(4).text();
var data = [];
data[0] = cells.eq(0).html();
}
I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});