Fetch contenteditable=true data - javascript

I want to fetch data from div tag which set contenteditable=true
I have used autosuggestion in that..Data is successfully fetched but when I write item which is written in autosuggestion field then it wont be fetched because it add HTML tag and it wont save into database
My code
if data is changed:
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function () {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function () {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function () {
getTextChangeContent();
});
UPDATE
function getTextChangeContent() {
var ma = document.getElementById('myAudio');
var remove = ma.src.slice(0, -4);
var path = remove.substring(remove.lastIndexOf("/") + 1);
var newPath = path.concat('.wav');
var text_id = document.getElementById('textbox');
var textdata = text_id.innerHTML;
$.ajax(
{
type: "POST",
url: '#Url.Action("getChangeContent")',
dataType: "json",
mtype: "post",
data: { arg: varid, content: textdata, path: newPath },
async: true,
success: function (data) {
alert(data + " DATA");
}
});
}
when I changed data and use autosuggestion then it will show data as
The door is blacl <span class="atwho-inserted">[[Ceilings]]</span>
How to ignore html tag and take only values of that?
Plz suggest me

Retrieve innerText rather than innerHTML in order to ignore the HTML content. If you want only the content inside the html tag with class .atwho-inserted, then retrieve only that content.
var textdata = text_id.innerText;

Related

how can I use text from a leaflet popup to complete the url for an ajax call?

I want to make an ajax call when clicking on text within a popup. The text in the leaflet popup is previous set by a different ajax call.
Here is the javascript for both ajax calls.
$("#button").click(function() {
var name = document.getElementById('searchterm').value
var stuff = $.ajax({
url: 'http://localhost:8080/demo/points/' + name,
type: 'GET',
dataType: 'json' ,
})
.done(function( json ) {
obj = JSON.parse(stuff.responseText);
var n;
for (n in obj) {
var marker = omnivore.wkt.parse(obj[n].wkt).addTo(map);
var id = JSON.stringify(obj[n].id)
var link = $(''+id+'').click(function() {
var moreStuff = $.ajax({
url: 'http://localhost:8080/demo/graph/'+id
type: 'GET',
dataType: 'json' ,
})
.done(function( json ) {
obj2 = JSON.parse(moreStuff.responseText);
// create an array with nodes
edges = new vis.DataSet(obj2["edges"])
// create an array with edges
nodes = new vis.DataSet(obj2["nodes"])
// create a network
var container = document.getElementById('mynetwork');
// provide the data in the vis format
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: {
shape: 'circle'
},
edges: {
length: 250
}
};
// initialize your network!
var network = new vis.Network(container, data, options);
});
});
var div = $('<div />').text('Address UPRN: ').append(link)[0];
marker.bindPopup(div);
}
});
});
When the second call is finished it adds a graph view using vis.js. This works fine when I manually enter the id.
The problem lies somewhere in this part of the code
for (n in obj) {
var marker = omnivore.wkt.parse(obj[n].wkt).addTo(map);
var id = JSON.stringify(obj[n].id)
var link = $(''+id+'').click(function() {
var moreStuff = $.ajax({
url: 'http://localhost:8080/demo/graph/'+id
type: 'GET',
dataType: 'json' ,
})
I think, as the IDs are set on all the markers when they are added to the map. Then when I click on the text it uses the last ID set to complete the url for the ajax call.
So I guess what I am asking is how can I use the popup text as part of the second ajax call? or maybe how do I preset the url to be used for each of the popups?
I've solved the problem using .on() and passed the id value as data in the function.
var link = $(''+id+'').on('click', { value: id }, function(x) {
moreStuff = $.ajax({
url: 'http://localhost:8080/demo/graph/' + x.data.value,
type: 'GET',
dataType: 'json' ,
})
This link was helpful, as was this link

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

Multiple AJAX calls and show div on finish

I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});

.slideDown (jQuery) not working

This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. Here is my script:
$(".expand").click(function(){
var button = $(this);
var id = $(this).attr("eid");
var url = "/get-complete/" + id + '/';
$.ajax({
type: "GET",
url: url,
success: function( data ) {
var obj = $.parseJSON(data);
var lang = '';
$.each(obj, function() {
lang += this['html'] + "<br/>";
});
button.siblings('.comment-expand').slideDown('slow', function(){
button.siblings('.comment-expand').html(lang);
});
button.attr('class', 'collapse');
button.html('Collapse');
},
});
return false;
});
Here is the html:
<a class="expand" href="/#" eid="{{ event.id }}">Expand</a>
<div class="comment-expand"></div>
This is the sample data returned by the GET request:
[{"html": "\n <div class=\"comment-count-bar\">\n</div>\n "}]
This is the code to collapse the post, but this isn't working either:
$("body").delegate(".collapse", "click", function(){
var button = $(this);
button.siblings('.comment-expand').slideUp('slow');
button.attr('class', 'expand');
button.html('Expand');
return false;
});
Try this:
$.ajax({
type: "GET",
url: url,
// setting the dataType to json, jQuery itself parses the response
dataType: 'json',
success: function(data) {
// Hiding the element and setting it's innerHTML
// before calling slideDown()
button.siblings('.comment-expand').hide().html(function() {
// Mapping the response and concatenating `html` properties
// If the response has only one array use:
// return data[0].html + '<br>'; instead
return $.map(data, function(v) {
return v.html + '<br>';
}).join('');
}).slideDown();
button.addClass('collapse')
.removeClass('expand')
.html('Collapse');
},
});
Edit: Since you are adding the class dynamically you should delegate the event:
$(document).on('click', '.collapse', function() {
// var button = $(this);
// ...
});

jQuery nested XML question

I am using jQuery to insert an HTML shell into a page, and populate the shell with XML. Here is the XML in question
<minorPropCategory title="Test Title 1">
<minorProp>FLV</minorProp>
<minorProp>BLV</minorProp>
<minorProp>RLV</minorProp>
</minorPropCategory>
<minorPropCategory title="Test Title 2">
<minorProp>LAS</minorProp>
<minorProp>ILV</minorProp>
<minorProp>BIL</minorProp>
</minorPropCategory>
So first, what I do is import an HTML snippet for each minorPropCategory, and add the title using this code
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
Then, what I want to do is add another HTML snippet, and then populate it. This is where I am having a problem. I can try it like this
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
But it never shows up on the page, because I don't think it is firing at the proper time. Alternatively, I tried moving the creation of the minor modules into the .load function of it's parent, but I run into another problem. The code looks like this.
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
$(this).find('minorProp').each(function(){
alert("minorPropFired");
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
alert("test");
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
The problem is, that the line with "$(this).find('minorProp').each(function(){" doesn't fire because "this" has changed. I guess, by now, my noob is showing. I feel like I am doing this in the wrong way. Any help would be appreciated. Thanks.
Posted below is the full .js file of what I am trying to do.
// JavaScript Document<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
//gets the code for the ad from the URL. Using URL jQuery add-on to make this super-easy
var adCode = $.url.param("adCode");
if (adCode != null){
//gets the ad code's XML file
$.ajax({
type: "GET", url: adCode+".xml", dataType: "xml",
success: function(xml) {
//Set the header image
$("#headerImg").attr(
{
src:$(xml).find('headerImage').text(),
alt:$(xml).find('headerImageAlt').text()
}
);
//set the header text
$("#headerText").html($(xml).find('adText').text());
//set the top image
$("#topImg").attr(
{
src:$(xml).find('topImage').text(),
alt:$(xml).find('topImageAlt').text()
}
);
//MAJOR MODULE CODE - This code reads all of the major modules, then adds a majorModule div, and populates it
//Gets all majorProps from ad XML
$(xml).find('majorProp').each(function(){
var propCode=$(this).text();
var majorModuleCode = "majorModule.html";
//names the div with a unique ID
div = $("<div id='"+propCode+"majorModule' class='majorModule'>");
//Sets loading message in case it takes longer than usual to load
div.html("Loading......");
//After majorModule.html code loads, starts populating module
div.load(majorModuleCode,"t",
function(){
//Get the XML for the prop, which contains prop specific stuff
$.ajax({
type: "GET",
url: propCode+".xml",
dataType: "xml",
success: function(xml2) {
$("#"+propCode+"majorModule").find(".propImg").attr(
{
src:$(xml2).find('smallImage').text(),
alt:$(xml2).find('smallImageAlt').text()
}
);
$("#"+propCode+"majorModule").find(".propLogoImg").attr(
{
src:$(xml2).find('smallLogo').text(),
alt:$(xml2).find('name').text()
}
);
$("#"+propCode+"majorModule").find(".viewCalendarLinkA").attr(
{
href:"https://www.harrahs.com/AvailabilityCalendar.do?propCode="+propCode+"&showHotDeal=Y"
}
);
$("#"+propCode+"majorModule").find(".learnMoreLinkA").attr(
{
href:$(xml2).find('homeLink').text()
}
);
$("#"+propCode+"majorModule").find(".propText").html(
$(xml2).find('bodyText').text()
);
}
});
//Get the lowest rate for the prop
$.ajax({
type: "GET",
url: "lowest_rate\\"+propCode+".xml",
dataType: "xml",
success: function(xml3) {
$("#"+propCode+"majorModule").find(".roomRate").html(
"$"+($(xml3).find('roomtype').filter(
function (index) {
return $(this).attr("lowest") == "Y";
}).text()).slice(0, -3)
)
}
});
}
);
$("#mainModuleContainer").append(div);
});
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
}
});
}
});
To fix this problem just before running minorDiv.load do something like this
var elem = $(this);
minorDiv.load(minorModuleContainerCode,"t", function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").
html(minorHeader);
// replace $(this) with elem here
elem.find('minorProp').each(function(){
...
}
...
}
This will keep the reference to correct object in your nested functions.

Categories