How to read Div inner contents at ajax? - html

I'm trying to update the sql db by a List of variables sent from the Html page.
Some of the Data are correctly sent, while others are not. I put the list in a div which is divided to two parts : "h1" and another "Div". The data at the header are all sent correctly, but the body itself which is at the second div isn't sent at all.
This is the Div which the data is put at:
$('#Classes').append('<div> <h1 class = "flip" wpID="' + subjects[i].Wkp_ID + '" lessonID="' + subjects[i].Ttb_lessonID + '" Date="' + Datecoming + '">' + subjects[i].sbj_Name + " Class:" + subjects[i].Ttb_Class + '</h1><div id ="NewBody" class="panel" contenteditable>' + subjects[i].Wkp_Body + '</div> </div>');
And that's how I read them at the ajax part:
var WeekPlan = [];
$('#Classes div').each(function (index) {
var header = $(this).children('h1');
var WeekBody = $(this).children('div').val();
var wpID = header.attr('wpID');
var lessonID = header.attr('lessonID');
var Wkp_Date = header.attr('Date');
WeekPlan[index] = { "Wkp_ID": wpID, "Wkp_Date": Wkp_Date, "Wkp_Body": WeekBody, "Wkp_lesson": lessonID };
});
The Wkp_ID, Wkp_Date, Wkp_Lesson are right, but the Wkp_Body just returns an empty string.
So do you know why is this happening and how can I truly read the body ? Most probably the problem is with this line:
var WeekBody = $(this).children('div').val();
But how can I access it correctly ?
Thanks a lot.

Here is what worked for me in case anyone needs it:
Creating the div:
$('#Classes').append('<div class="BigDiv"> <h1 class = "flip" wpID="'+ subjects[i].Wkp_ID + '" lessonID="' + subjects[i].Ttb_lessonID + '" Date="' + Datecoming + '">' + subjects[i].sbj_Name + " class:" + subjects[i].Cls_Name + '</h1><div class="panel" contenteditable>' + subjects[i].Wkp_Body + '</div> </div>');

Related

How to replace RichTextEditor text without loosing the formatting in Flex

In my ActionScript code, I'm using a richTextEditor to do the following.
protected function createEmailTemplateContent(subRecord:String = null):void{
var index:int = emailTemplateContent.selection.beginIndex;
if(subRecord != null){
emailTemplateContent.text = emailTemplateContent.text.substring(0,index) + '{[' + fieldTypeDD.selectedItem + '].[' + insertFieldDD.selectedItem.toString().substring(0,insertFieldDD.selectedItem.toString().indexOf('(+)')-1) + '].[' + subRecord + ']}' + emailTemplateContent.text.substring(index,emailTemplateContent.text.length);
}else{
emailTemplateContent.text = emailTemplateContent.text.substring(0,index) + '{[' + fieldTypeDD.selectedItem + '].[' + insertFieldDD.selectedItem + ']}' + emailTemplateContent.text.substring(index,emailTemplateContent.text.length);
}
}
The above method implements when the user selects an item from a drop down list. Then that particular item will be populated inside the text area of the rich text editor.
My issue is that if the user has already done some formatting (using the formatting options in RichTextEditor) on the text, that also get replaced when the user selects an item and populates the text area.
In this, 'emailTemplateContent' means the RichTextEditor. I have included my RichTextEditor code in the following.
<component:RichTextEditorWithAllControls id="emailTemplateContent" dropShadowVisible="false" creationComplete="emailTemplatesContentInit()" headerHeight="0" width="100%" height="100%" htmlText="#{emailTemplateObject.emailContent}" showControlBar="false" verticalScrollPolicy="auto"/>
I assume this happens because when I populate the 'text' value in the richTextEditor, the 'htmlText' value is also get replaced.
Does anyone know a way to overcome this issue.
Thanks in advance.
First store the concatenated text in a String and then replace it in the html text. Something like below
protected function createEmailTemplateContent(subRecord:String = null):void{
var index:int = emailTemplateContent.selection.beginIndex;
var newText:String;
if(subRecord != null){
newText = emailTemplateContent.text.substring(0,index)
+ '{[' + fieldTypeDD.selectedItem + '].[' + insertFieldDD.selectedItem.toString().substring(0,insertFieldDD.selectedItem.toString().indexOf('(+)')-1) + '].[' + subRecord + ']}' + emailTemplateContent.text.substring(index,emailTemplateContent.text.length);
}else{
newText = emailTemplateContent.text.substring(0,index) + '{[' + fieldTypeDD.selectedItem + '].[' + insertFieldDD.selectedItem + ']}' + emailTemplateContent.text.substring(index,emailTemplateContent.text.length);
}
emailTemplateContent.htmlText = emailTemplateContent.htmlText.replace(emailTemplateContent.text, newText);
}

Place one HTML input directly below another with HTML

So I have a bunch of HTML elements I'm creating dynamically. I would really like the element "imageBox" to appear directly below the "mediaBox" instead of to the left of it like it is now. Here is my code right now:
var div = document.createElement("div");
//HTML code for each element to be added with each new checkpoint
var nameBox = "<b>Checkpoint " + markerId + ":</b> <input type='text' id=" + markerId + " placeholder='Checkpoint name'>"
var descBox = "<textarea rows='4' cols='35' placeholder='Checkpoint description' id=" + markerId + "desc style='vertical-align: top;'></textarea>"
var mediaBox = "<input type='text' id='media" + markerId + "' placeholder='paste URL to YouTube video' size='23'>"
var imageBox = "<input type='text' id='image" + markerId + "' placeholder='paste URL to image' size='23'>"
var removeButton = "<button type='button' value='Remove' id='remove" + markerId + "' onClick='remove_marker(" + markerId + ")'> Remove </button>"
var undoButton = "<button type='button' value='Undo' ' style='display: none;' id='undo" + markerId + "' onClick='remove_marker(" + markerId + ")'> Undo </button>"
var removeText = "<div id='removed" + markerId + "' style='display: none;'> Removed <button type='button' value='Undo' ' style='display: none;' id='undo" + markerId + "' onClick='undo_Remove(" + markerId + ")'> Undo </button> </div>"
div.innerHTML = nameBox + descBox + mediaBox + imageBox + removeButton + removeText;
I know it is really messy and ideally I should be using CSS but I'm not right now. It shows up on my page like this:
It would be great if the image URL box could be right under the YouTube one!
Thanks so much!
For minimal re-writing, you can try wrapping the two boxes in an unordered list. If you really truly want to avoid CSS, set an inline style to remove the bullets.
div.innerHTML = (nameBox
+ descBox
+ '<ul style="list-style: none;"><li>'
+ mediaBox + "</li><li>" + imageBox
+ "</li></ul>"
+ removeButton
+ removeText);
I just inserted the relevant bits into your last line. You really really should use document.createElement and div.appendChild to create these things.

remove span by class from $(this).html()

Basically my search returns search results in spans, then when one is clicked, a new span is added to another div with a select input and hidden input so all the selected features can be posted as an array.
My question is, $(this).html() now includes a span of class alias_span. Which I don't want to appear in the new span. How do I remove it before inserting the contents of the clicked span into the new span
$(".minisearch_res").live('click', function() {
// when a search result is clicked we disable the submit button,
// append a span to the left column with an id,
// a select input to select standard/optional and
// a hidden field with the required information to save and something to
// show the user
var id = $(this).attr('id');
var html = "<span class= \"added_result_cont\" id=\"" + id + "_cont\">";
html += "<select name='" + id + "_sel'>";
html += "<option value=\"none\" selected=\"selected\"></option>";
html += "<option value=\"std\">Standard</option>";
html += "<option value=\"opt\" >Optional</option>";
html += "</select>";
html += "<span id= \"" + id + "\" class=\"added_result\">";
html += "<input type=\"hidden\" name=\"selectedfeat[]\" value=\"" + id + "\">";
html += $(this).html() + "</span></span>";
$('#div_apply_to').append(html);
$(this).remove();
$('#search_input').trigger('keyup');
$("input[type=submit]").attr("disabled", "disabled");
});
Update: here's the html of the span
<span class="minisearch_res" id="opt_1">Anti-Lock Brakes<br><span style="padding-left:20px" class="alias_span"><i>abs</i></span><br></span>
<div></div>
Add it to the dom, then remove it.
var htm = (
'<span class="foo">foo</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>'
);
var $el = $("div").append(htm);
console.log($el.html());
$el.find('.foo').remove();
console.log($el.html());
http://jsfiddle.net/chovy/w2HdE/
Got a tidy cross browser solution, which I'm very proud of :)
var temp = $(this);
temp.children('.alias_span').remove();
$('#div_apply_to').append("...html..." + temp.html() + "...html...");
inspiration came from here:
Remove element from Ajax Response

Parsing JSON - script fails when an expected element is missing

I have the following line in my script, building a string based on news feed data retrieved from JSON:
var buildstring = "<table><tr><img src=" + obj.value.items[x]["media:content"].url + "> <b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";
In general it works fine - except for one thing. The feed that is being parsed occasionally doesn't have an image file associated with a particular title and description, and in that case, the entire script fails.
Is there any way to get the script to skip over any missing item in the feed and to build the string from the items that are there? E.g. if there is no image file for a story, the string consists of just the title and description? In the typical case I am taking 5 - 10 stories - if all of them have the 3 elements (image, title and description.content), it's all fine. If one story is missing the image file, I get nothing at all.
Thanks for any advice or assistance.
EDIT:
More complete code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"> </script><script type="text/javascript">
function pipeCallback(obj) {
document.write("<div id=testdiv><b>LATEST NEWS</b><hr>");
var x;
for (x = 0; x < obj.count ; x++)
{
var imageurl = obj.value.items[x]["media:content"].url ? obj.value.items[x]["media:content"].url : "http://static.jquery.com/org/images/project/jquery-project-sm.png";
var buildstring = "<table><tr><img src=" + imageurl + "> <b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";
document.write(buildstring);
buildstring = null;
}
document.write("</div>");
}
</script>
You could use a ternary expression to build the string:
var textOnly = "<b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";
var buildstring = (typeof obj.value.items[x]["media:content"] == 'undefined') ?
"<table><tr><td><img src=" + obj.value.items[x]["media:content"].url + "></td>" + textOnly
: "<table<tr><td></td>" + textOnly;
Obviously this gets really ugly, fast, which is why they invented client-side templating (JQuery templating, Underscore.js, Mustache.js, Handlebars.js, etc, take your pick).
These allow you to separate the data from the markup, so you can write something like this:
var template = "<table><tr><td><img src='{{ image }}' /></td><td>{{ title }}</td><td>{{ description }}</td></tr></table>";
And you can get the HTML by from the data + template:
var html = Mustache.render(template, obj.value.items[x]);
The best option is simply to include placeholder, right? So if there is no image then the placeholder appears...
This would be achieved like this:
var imageurl = obj.value.items[x]["media:content"].url ? obj.value.items[x]["media:content"].url : "http://link.to.default/image.png";
var buildstring = "<table><tr><img src=" + imageurl + "> <b>" + obj.value.items[x].title + "</b><br /><td>" + obj.value.items[x].description.content + "</td></tr></table><br />";

Auto select the check box in rows

I am displaying table rows in the form. Each row has 5 columns, one of the columns is an (editable) textbox field.
ajaxLoading(true);
$.post('<%=request.getContextPath()%>'+"/processServlet", postData,
function(data) {
var ctxPath='<%=request.getContextPath()%>';
currentPosition = data.currentPosition;
var items = $("#itemsTable");
items.empty();
if (data.items.length == 0) {
items.append($('<tr><td colspan=5 style="color:red;">No items<td></tr>'));
}
;
for (var i = 0; i < data.items.length; i++) {
editText = "";
items.append($("<tr " + zebra + "><td><a href=\"javascript: deviceView('" + data.items[i].id + "')\">" + data.items[i].num +
"</a></td><td>" + data.items[i].itemType +
"</td><td><input type = 'checkbox' id = 'CheckBoxRow_' />" + data.items[i] +
"</td><td><input type = 'textbox' id = 'TextBoxRow_' value = '" + data.items[i].itemName +"' "/>" +
"</td><td>" + data.items[i].status +
"</td><td>" + data.items[i].date + "</td>" +
"<td>" + data.items[i].firmware + "<td>" +
"Delete" +
"</tr>"));
;
ajaxLoading(false);
}, "json");
How do I auto select the check box when the data is entered or modified in the textbox and save the data in the database?
bind to textbox onchange event and have it set the checkbox to checked=true once returned with a value (and not already checked).
$('#itemsTable input[type="checkbox"]').change(function(e){
var $cb = $(this);
if ($cb.is(':checked')){
$cb.closest('tr').find('input[type="checkbox"][id^=CheckBoxRow_]').prop('checked','true');
}
});
basically. though you really should not use HTML in an append, and should be building the objects with jQuery.