How to apply a CSS class to an ID that just succeed - javascript

I'm working on an editable table with HTML5 attribute called contenteditable. Everything works well until I have another idea of telling user which cell is just updated. By highlight it with a class from bootstrap called alert-danger.
After a cell is successfully sent. A data is sent back to a parent page telling the result div what the status is. It only shows the status on top of the table but I'd like to add another class in the cell. So I added $("td[id="+cols3_key+"").addClass('alert-danger'); when a data calls back. Expecting the latest cell is apply with alert-danger class. But it doesn't work. Here's my script.
javascript
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var cols3_key = $(this).attr("id") ;
var value = $(this).text() ;
$.post('inc/ajax.php' , cols3_key + "=" + value, function(data){
if(data != ''){
$("td[id="+cols3_key+"]").addClass('alert-danger');
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
}
});
});
The question is : How can I change this line to refer to a cell that has been just processed?
$("td[id="+cols3_key+"").addClass('alert-danger');
Regards,

Try this, you are missing to close the ]
$('td[id="+cols3_key+"]').addClass('alert-danger');
OR
$('td[id$="cols3_key"]').addClass('alert-danger');

You can just do $(this).addClass('alert-danger'); in place of $("td[id="+cols3_key+"").addClass('alert-danger');
In case you do not get proper $(this) inside post callback, you can try $("td#"+cols3_key+"").addClass('alert-danger');
In jquery to access ID you have to use
#. For e.g, to access <td id='test'></td>
you will have to write $('td#test').addClass('newClass');

You were missing a ], so you could use $("td[id="+cols3_key+"]") which can be made simply: $("#"+cols3_key)
Note the first fix here only requires extra single quotes if the id contains special characters:
e.g. $("td[id='"+cols3_key+"']")
The second one shown will work in either case.
Instead I would suggest a better way of doing this:
1) Put your ajax call in a function so you can pass specific elements to it that will be remembered per Ajax call.
2) Just reference the element and stop worrying about the id
Something like this:
var update = function($element){
var value = $element.text();
$.post('inc/ajax.php' , $element.attr('id') + "=" + value, function(data){
if(data != ''){
$element.addClass('alert-danger');
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
}
});
}
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
update($(this));
});

Finally,
I've got my way out of here with many helps from you guys and THE notice from #TrueBlueAussie. Here's the full script.
HTML
<h2 class="lead text-danger">HTML5 Inline Edit</h2>
<div id="status"></div>
<table class="table table-bordered table-striped">
<tr>
<td id="table_col1:1" contenteditable="true">
content1
</td>
<td id="table_col1:2" contenteditable="true">
content2
</td>
<td id="table_col1:3" contenteditable="true">
content3
</td>
</tr>
</table>
CSS
#status{
background:#ff0000;
border:solid 1px #ccc;
border-radius:5px;
color:#fff;
display:none;
padding:5px;
width:100%;
}
Javascript
$(window).load(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var cols3_key = $(this).attr("id") ;
var value = $(this).text() ;
$.post('' , cols3_key + "=" + value, function(data){
if(data != ''){
$('td[id="'+cols3_key+'"]').addClass('alert-danger');//this is the trick. I need a couple of single quotes here to express that I need a var not an id name
message_status.slideDown();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.slideUp()},3000);
setTimeout(function(){$('td[id="'+cols3_key+'"]').removeClass('alert-danger')},3000);
}
});
});
});
A working demo here - http://jsfiddle.net/nobuts/Lroqpk7x/9/

Related

Cannot append to node

I have a the following html code in a table:
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
When I click the button, I would like to empty the td and add the text which is stored in a cookie. The td empties fine but I am unable to append the text. The text is in the variable as it is visible in the alert. I have used the code below to try and achive this, the commented out code is what I have tried and doesn't work.
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
//alert(hostname);
var trid = $(this).closest('tr').attr('id');
//alert(trid);
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
$(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').append(olddesc);
// $(this).closest('tr').find('#description').text(olddesc);
// $(this).closest('td').text(olddesc);
// $('#'+trid+' td').each(function(){
// if($(this).attr('id') == 'description'){
// $(this).append(olddesc);
// }
// })
//$(document).find('#'+trid+' td#description').append(olddesc);
})
Can anyone please help me fix this or recommend a better way of doing it?
You can use .html() to add your dynamic data to HTML tag id
var olddesc = Cookies.get(hostname+','+trid+',description');
alert(olddesc);
// Create custom / dynamic HTML
var temp = `<p>` + olddesc + `</p>`;
$(this).closest('td').empty(); <----- THIS WORKS
// Edit: Use ID of html tag
$('#description').html(temp);
This shall work for you.
$(this).closest('td').append(olddesc); runs after you've removed this from the td, therefore the td is no longer an ancestor of this. You do not need to empty the td; simply set its text to olddesc and it will be automagically emptied as part of the process of setting its text.
// (REMOVE THIS) $(this).closest('td').empty(); <----- THIS WORKS
$(this).closest('td').text(olddesc);
Just use .html
$(document).on('click', '#removeinput', function() {
var hostname = $('#hostname').text();
var olddesc = "Cokkies return"; //Cookies.get(hostname+','+trid+',description');
$(this).closest('td').html(olddesc); //<----- THIS WORKS
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="description">
<input id="newdescripion" value="VOIP/DATA" type="text">
<button type="button" id="removeinput">Remove</button>
</td>
</tr>
</table>

How to automatically call a JavaScript that modify a value before show this value?

I am very new in JavaScript and I have the following problem to solve.
I have a table that contains this td cell:
<td class= "dateToConvert" width = "8.33%">
<%=salDettaglio.getDataCreazione() != null ? salDettaglio.getDataCreazione() : "" %>
</td>
This retrieve a String from an object and show it into the cell
The problem is the retrieved string represent a date having the following horrible form: 20131204 and I have to convert it into the following form: 2013-12-04.
So I am thinking to create a JavaScript that do this work when the value is retrieved.
My problem is: how can I do to automatically call the JavaScript before to show the value into the td cell? (So I show the modified output in the desidered form)
EDIT 1:
So I have create thid JavaScript function into my page:
function convertData() {
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.innerText = td.innerText.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
}
But it don't work because it never enter in this function (I see it using FireBug JavaScript debugger). Why? What am I missing? Maybe have I to call it explicitly in some way in my td cell?
Of course it is better to fix backend method to make it return proper format. But since you have no control over it try to use something like this:
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
Check the demo below.
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
<table>
<tr>
<td class= "dateToConvert" width = "8.33%">
20131204
</td>
<td class= "dateToConvert" width = "8.33%">
20140408
</td>
</tr>
</table>

Dynamically generating form elements using jquery

There are multiple paragraphs in the page. Each paragraph must be followed by a div with two buttons Add and Edit. Clicking the Add button should create a textarea dynamically above it.
Related references that didn't work:
How to use jQuery to add form elements dynamically
How to add (clone) form fields using jQuery and increment ids and names
DEMO
HTML code:
<div id="notes"></div>
In my JavaScipt:
<script>
// get notes in json format from php array
var notes = <?php echo json_encode($notes); ?>;
// call the scan function to iterate through the notes
scan(notes);
function scan(obj)
{
jQuery.each(obj, function(key, val) {
if (val instanceof Object) {
for ( var v in val ) {
if (val[v]['type'] == 'Topic') {
$("#notes").append('<h2 class="topic">'+val[v]['content']+'</h2>');
}
if (val[v]['type'] == 'Subtopic') {
$("#notes").append('<h4 class="subtopic">'+val[v]['content']+'</h4>');
}
if (val[v]['type'] == 'Concept') {
$("#notes").append('<h5 class="concept">'+val[v]['content']+'</h5>');
}
if (val[v]['type'] == 'Paragraph') {
$("#notes").append('<p>'+val[v]['content']+'</p>');
// append input for all paragraphs
$('#notes').append('<div class="paragraphs">');
$('#notes').append('<div id="block">');
$('#notes').append('<p class="edit"></p>');
$('#notes').append('<p>');
$('#notes').append('<div id="para">');
$('#notes').append('<p><textarea cols="40" rows="2" id="textarea"></textarea></p>');
$('#notes').append('<button id="add" class="add success tiny">Add</button>');
$('#notes').append(' ');
$('#notes').append('<button id="startEdit" class="canEdit tiny">Edit</button>');
$('#notes').append('</div>');
$('#notes').append('</p>');
$('#notes').append('</div>');
$('#notes').append('</div>');
}
scan(val[v]);
}
}
});
};
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
text = $('#textarea'+i).text();
var data = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
$('.paragraphs').on('click', '#add'+i, function() {
if ( $('#add'+i).text() == "Add" ) {
ajaxRequest(data, 'editNotes', 'POST'); // POST request on editNotes
$('#textarea'+i).show();
$('#add'+i).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $('#add'+i).text() == "Save" ) {
ajaxRequest(data, 'saveNotes', 'POST'); // POST request on saveNotes
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$('#add'+i).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
console.log('after: i='+i);
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
How do I add the form elements dynamically with incremental id and class names?
Any help is appreciated
unfortunately append does not work like it may seem, when you submit something like:
$('#element').append('<div>start here'):
$('#element').append('end here</div>'):
The very first call sent will close the div, it will actually create 2 separate elements. One way to help with this rather than having a large append as it can get kinda messy, is to create a variable and place all the elements into that variable and append it.
Example:
http://jsfiddle.net/h8V93/
var appends='<div class="paragraphs">'
+'<div id="block">'
+'<p class="edit"></p>'
+'<p>'
+'<div id="para">'
+'<p><textarea cols="40" rows="2" id="textarea"></textarea></p>'
+'<button id="add" class="add success tiny">Add</button>'
+' '
+'<button id="startEdit" class="canEdit tiny">Edit</button>'
+'</div>'
+'</p>'
+'</div>'
+'</div>';
$('#notes').append(appends);
I hope this helps.
Update
Edit for further reading, the best way to actually do this is to create an html page as a separate file and include it like so:::
$.get("<urlhere>", function (data) {
//Append, After, Before, Prepend data or whatever you want to do with it.
});
This is very convenient in GM or TM scripts where you keep the html file on your own server.
Hope this update helps future readers.
in recent versions of TM (tampermonkey), because of added cross domain origin policies, use GM_xmlhttpRequest -> http://wiki.greasespot.net/GM_xmlhttpRequest

Get values of div, check if the value is in td, if so, change class

I need to return a value(s) within a div, then check another div to see if the values exist. If they do, change the class of the link. The loop is working great. I need to now check the other field.
var cart = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
cart += ' ' + $(div).text();
});
if(cart != "")
{
//do something
}
I need to see if the value returned by cart is in a table value:
<td class="views-field views-field-title">
<a href="/accessory/oi-01">
<span class="assess-title">OI-01</span>
</a>
<p>
<a class="add-to-quote" href="/cart/add/3">Add to Quote</a>
</p>
</td>
If the values match, I need to change the class from "add-to-quote" to "added-to-quote". The example with for the td, is showing one of many that are on the page with various other numbers. I am trying to find only the one that matches the value returned by cart. Any thoughts???
Thanks!
Try with this code:
if(cart != "")
{
//Find all the "assess-title"s
$('.views-field.views-field-title > a > .assess-title').each(function (i, span) {
var $span = $(span);
if(cart.indexOf($span.html())!=-1){//The cart contains it?
$span.parent().next().find("a.add-to-quote").addClass("theClassToAdd").html("Added to Quote");
}
});
}
EDIT:
Here is a jsFiddle

How to fetch the dynamically created element by its ID in jQuery

Initially adding the element statically like below:
<td valign="top" id="description_div">
*<table class="des_box" id="comment_div">
<tr><td class="head" id=file_comments> The function comments </td></tr>
<tr><td class="comment" id="test_point_comment_info"></td></tr>
</table>*
</td>
Dynamically adding the element as below :
$("#description_div").append(
'<table class="des_box1" id=comment_div><tr><td class="head" id=file_comments> The function comments </td></tr><tr><td class="comment" id=test_point_comment_info_' + id + '></td></tr> </table>')
Now, when I try to fetch the element by its id (that is by "comment_div") ... I am not able to retrieve the dynamically created element. But able to fetch the static element by using $("#comment_div")
I am trying to do following on the element :
$("#comment_div").show();
tried .live() ....but was not able to fetch the dynamic element.
$("#comment_div").live().show();
check box code :
<li><input type="checkbox" name="comment" />Comment</li>
actual functions where am trying to fetch the element:
$("#checkbox_div input:checkbox").click(function() {
var division = "#" + $(this).attr('name') + "_div";
$(division).show();
}
function SetCheckboxes(checkbox_data) {
//SetCookie('pre_checkbox', "1111111111111111")
var checkbox_data = GetCookie('pre_checkbox');
if (checkbox_data == null) {
SetCookie('pre_checkbox', "1111111111111111")
checkbox_data = GetCookie('pre_checkbox');
}
checkbox_array = new Array("owner", "test_time", "bp", "single_use", "num_of_test", "pause", "clearall", "clearclass", "clearmax", "closeall", "qeinbat", "m_lint","geck","header","comment","feature");
for ( i = 0; i < checkbox_data.length; i++) {
var checkbox_name = checkbox_array[i];
var value = checkbox_data[i];
var division = "#" + checkbox_name + "_div";
if (checkbox_name=="geck" || checkbox_name=="header" || checkbox_name== "comment" || checkbox_name=="feature"){
console.log("entering_loop_as_expected")
if (value == "1") {
//alert("1");
$("#checkbox_div input[name='" + checkbox_name + "']").attr("checked", "checked");
$(division).show();
} else {
$(division).hide();
}
continue;
}
Please help me out on this.
.live() is what you wanted but it has been depreciated, you now need to use .on()
$(document).on("click", "#checkbox_div input:checkbox", function(){
//Your code here.
});
Using document for your selector with .on will allow you to bind events to dynamically created elements. This is the only way I've found to do it when the DOM elements don't exist prior to execution.
I do this in a dynamically created table that is sort-able and works great.
EDIT:
Here is an example. Click the button to add a div then click the div to get it's contents.
http://jsfiddle.net/FEzcC/1/
You missed the quotes, also ensure you try to access them before they are added to DOM, e.g they will not be available on DOM ready if they are added on some button click. I think you forgot to give value of id, I have made a live demo.
Live Demo
$("#checkbox_div input:checkbox").click(function() {
var division = "#" + $(this).attr('name') + "_div";
$(division).show();
});
id=1;
$("#description_div").append('<table class="des_box1" id="comment_div"><tr><td class="head" id="file_comments"> The function comments </td></tr><tr><td class="comment" id="test_point_comment_info_' + id + '"></td></tr> </table>');
Edit based on comments and fiddle being provided.
You have few problems with html in the demo
Your html starts with td instead of table
You do not enclose the ids with quotes
You are assigning same id to more then one element, instead assign a
common class and use that.
Live Demo, Problem here are not dynamic element but the wrong HTML / Script
Html
<table>
<tr>
<td valign="top" id="description_div">
<table class="des_box" id="comment_div1">
<tr>
<td class="head" id="file_comments">The function commentszz</td>
</tr>
<tr>
<td class="comment" id="test_point_comment_info"></td>
</tr>
</table>
</td>
</tr>
</table>
<div id="checkbox_div">
<input type="checkbox" name="des" />Comment
</div>
Javascript
$("#description_div").append(
'<table class="des_box" id="comment_div2"><tr><td class="head" id=file_comments> The function comments </td></tr><tr><td class="comment" id=test_point_comment_info_' + 'id' + '></td></tr> </table>');
$(document).on("click", "#checkbox_div input:checkbox", function () {
var division = "." + $(this).attr('name') + "_box";
$(division).show();
});
If you have to use same id for more than one element with is wrong you can use attribute selector. First correct the html by enclosing td within tr and table tag.
Live Demo
$(document).on("click", "#checkbox_div input:checkbox", function(){
var division = "[id=" + $(this).attr('name') + "_div]";
$(division).show();
});
What is id value in + id +, id is undefined in current context. I have put it in single quote and its working fine.
Update: You are using same id comment_div for static and dynamic content, id should be unique in DOM. Use class instead of id for multiple elements
Updated jsFiddle

Categories

Resources