I was wondering how i can add a new tr and td wrapped around data received from a ajax call? The following doesn't work.
$.get('/edit/'+course_id, function(data){
///add class to current tr
$('#course_'+course_id).addClass( "info" );
$('<tr><td>'+data+'</td></tr>').insertAfter('#course_'+course_id);
});
Any help would be much appreciated.
Thanks
You can add that to a table element. I think in IE, it needs to be attached with tbody.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
var data='some HTML';
$('<tr><td>'+data+'</td></tr>').insertAfter('#course');
});
</script>
</head>
<body>
<table>
<tbody>
<tr id="course"><td></td></tr>
</tbody>
</table>
</body>
</html>
(really) difficult to answer without the HTML markup, but this might be a binding problem :
maybe you can try
var successCourse = function(courseId) {
return function(data) {
///add class to current tr
$('#course_' + courseId).addClass("info");
$('<tr><td>' + data + '</td></tr>').insertAfter('#course_' + courseId);
};
};
$.get('/edit/'+course_id).done(successCourse(course_id));
The neatest way is probably...
$.get('/edit/' + course_id, function() {
// do whatever else you need to do
var formatted = $('<tr/>').append($('<td/>', { html: data }));
formatted.insertAfter('#course_' + course_id);
});
This saves you from the mess of writing html tags in as strings and having to remember to close them etc, by letting jQuery do pretty much everything for you.
Here's an example on jsFiddle which shows it working. Hope this helped!
Related
I am using jQuery replaceWith() method to replace some content from the html. Its working fine. But I want to change the data attribute value once replaceWith() has been done.
So basically I am getting this from my ajax response
UpdatedItem = '<li data-cart-key="XXX" data-item-name="Test" data-item-price="$111.00" data-item-key="XXX"><span class="cart-action-wrap"><a class="edit-cart-item" data-cart-item="XXX" data-cart-key="XXX" data-cart-action="edit">Edit</a><a class="remove-cart-item" data-cart-item="XXX" data-cart-key="XXX" data-cart-action="remove">Remove</a></span></li>';
Now I am using replaceWith() here like this
$( 'ul.custom-contents' ).find( 'li.updated' ).replaceWith( UpdatedItem );
Here I wanted to use methods like update data attribute value, remove class, add class after replaceWith() has been done.
So can someone tell me is there any way available to do this? Any help and suggestions would be really appreciable. Thanks
you can solve like this.
UpdatedItem =
'<li data-cart-key="" data-item-name="Test" data-item-price="$111.00" data-item-key="XXX">updated</li>';
divElement = document.createElement("div");
divElement.innerHTML = UpdatedItem;
element = divElement.firstElementChild;
$("ul.custom-contents").find("li.updated").replaceWith(element);
element.setAttribute("data-item-name", "myValue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<ul class="custom-contents">
<li class="updated">old</li>
<li class="">old</li>
<li class="">old</li>
</ul>
<script src="app.js"></script>
</body>
</html>
You can create a jQuery object inside replaceWith, do the operations and return it. Use .find() for nested elements:
$( 'ul.custom-contents' ).find( 'li.updated' ).replaceWith( fucntion(){
let obj = $(UpdatedItem)
obj.addClass("..")
obj.data("cart-key", "..")
obj.data("item-name", "..")
obj.removeClass("..")
//Find <a> with class "edit-cart-item"
obj.find("a.edit-cart-item").addClass(...)
obj.find("a.edit-cart-item").data("item-name", "..")
return obj;
});
Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.
I got this code from the GitHub:
<script src="path/to/jSignature.min.js"></script>
<script>
$(document).ready(function() {
$("#signature").jSignature()
})
</script>
<div id="signature"></div>
But it doesn't pull anything up on the actual webpage. I would think there is more code required but I don't know where to start.
Here is a minimal working example
<!DOCTYPE html>
<html lang="en">
<head>
<lang>
<title>Minimal working jSignature Example</title>
<meta charset="UTF-8">
<!-- Files from the origin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://willowsystems.github.io/jSignature/js/libs/jSignature.min.js"></script>
<head>
<script>
$(document).ready(function() {
// Initialize jSignature
$("#signature").jSignature();
})
// ripped from the description at their the Github page
function getBase64Sig(){
// get the element where the signature have been put
var $sigdiv = $("#signature");
// get a base64 URL for a SVG picture
var data = $sigdiv.jSignature("getData", "svgbase64");
// build the image...
var i = new Image();
i.src = "data:" + data[0] + "," + data[1];
// and put it somewhere where the sun shines brightly upon it.
$(i).appendTo($("#output"));
}
</script>
<body>
Put your signature here:
<div id="signature"></div>
<button onclick="getBase64Sig()">Get Base64</button>
<div id="output"></div>
</body>
</html>
I hope you can go on from here.
It is really as simple as they describe it to be, only their description of the actual example is a bit lacking for beginners.
I am validating data present in CKeditor on a button click event using jquery. After the button click it separates the list of correct answers and wrong answers. This works fine. But after modifying the wrong answers and hit the button, it again takes the initially entered values. How to make it take the modified data on the 2nd button click.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<script src="../ckeditor/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
CKEDITOR.replace('Field');
var correctZips = new Array;
var wrongZips = new Array;
var CorZip;
var WorZip;
$('#save').click(function () {
var editor_data = CKEDITOR.instances['Field'].getData();
var element = $(editor_data).text().split(",");
$.each((element), function (index, value) {
if(this.length=5 && jQuery.isNumeric(this)) {
correctZips= correctZips+"<span>"+this+"</span>"+",";
}else {
wrongZips= wrongZips+"<span id='flip' style=\"background-color: yellow; \">"+this+"</span>"+",";
}
}
)
CKEDITOR.instances.Field.setData((correctZips + wrongZips), function (index, value){
})
//$("#save").attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<textarea id="Field"></textarea>
<button id ="save">Verify the ZipCodes</button>
</body>
</html>
Regards,
Steven
You are deinfing the 2 ZIPS variables as arrays outside of the click handler. You need to reset them for each time a click occurs so they need to be defined inside the handler and they shouldn't be defined as arrays since you are using them to concatenate strings
$('#save').click(function () {
var correctZips = '', wrongZips='';/* start with empty strings*/
/* remainder of your handler code*/
});
I am getting the index of a row by doing this:
row.parent().children("tr").index(row)
Is there a more efficient way to find the index? I have hundreds of rows so it is killing my performance that I have to select all rows just to find the index.
How about row.prevAll().length?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" charset="utf-8" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
console.log($("tr").index($("#my")));
})
</script>
</head>
<body>
<table border="0" cellspacing="5" cellpadding="5" id="tbl">
<tr><th>Header</th></tr>
<tr><td>Data</td></tr>
<tr id="my"><th>Header</th></tr>
<tr><th>Header</th></tr>
<tr><td>Data</td></tr>
</table>
</body>
</html>
Hope that helps. Cheers.
Id attribute is the most fastest way to parse any html. You could provide all your rows with an Id.
Although the index method will determine the index among of the siblings elements, which could be faster
row.parent("tr").index();
see this example http://jsfiddle.net/shNrS/
If you are getting the reference to the row somehow (click handler etc) than there is no additional overhead in looking up that element, just .index() it and profit (although watch out for multiple tbody elements which are valid but would add complexity to your script)
If you are indexing all tr elements at runtime, might as well cache it in jquery data for future use!
The fastest way here is probably using plain javascript:
function getRowIndex(elem) {
var index = 0;
while (elem = elem.previousSibling) {
if (elem.tagName == "TR") {
++index;
}
}
return(index);
}
Working demo: http://jsfiddle.net/jfriend00/y4anN/
If you had to do this repeatedly on a large table that wasn't changing dynamically, then you could just pre-number the rows once with a custom attribute and from then on, all you'd have to do it retrieve the custom attribute from any row.
You would pre-number all the rows with a custom attribute like this:
function numberRows(table) {
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].dataIndex = i;
}
}
And, then you can just obtain the index number from any given row like this:
row.dataIndex
Working demo: http://jsfiddle.net/jfriend00/CR2Wk/