updating div with jQuery and Knockout.js with .html() not working - javascript

This should be a simple matter of updating some simple modal controls with .html() but for some reason, I'm having issues. This is the modal code...
<div id="answerTaskQuestionModal" class=" modal-dialog" data-bind="with: currentQuestion">
<div id="answerTaskQuestionValidation" class="validation"></div>
<span data-bind="text: html"></span>
<div id="taskQuestionAnswer"></div>
</div>
And here is the JavaScript inside my working view model...
self.answerTaskQuestion = function (question) {
$('#answerTaskQuestionValidation').html('');
var $taskQuestionAnswer = $('#taskQuestionAnswer');
$taskQuestionAnswer.html(' \* {my html with bindings} *\ ');
$answerTaskQuestionModal.dialog('open');
self.currentQuestion(question);
};
Basically, I'm trying to dynamically change the ways one can answer a question as a proof of concept. If I just paste the html inside the target div, they work. However, when I check the value of .html(), this is what happens...
first run: $taskQuestionAnswer.html() returns undefined
second run: $taskQuestionAnswer.html() returns the proper HTML but the div won't update.
Replacing the bindings with just simple HTML doesn't help either. What am I missing here?

I think after $taskQuestionAnswer.html(' \* {my html with bindings} *\ ');
you should call ko.applyBindings(myViewModel) again to apply view model to new html.

Related

How to add jquery addClass() method to element ng-repeat AngularJS

I made a text editor summernote for an article, and after that I read it with modalbootstrap and angularJS ng-repeat in html element to get data from json api my php, its works.
but the problem with the article content is that there is an image and I want to add the 'img-fluid' class so that the image is responsive.
I have tried adding classes with the jquery addClass method to element html, and it works with code like this.
point assume example:
my script.js
$('img').addClass('img-fluid');
result element img without ng-repeat works.
<div class='container'>
<div class='onlyDiv'>
<p>
<img src='bla.jpg' class='img-fluid' <--works>
</p>
</div>
</div>
but if the img element with the ng-repeat directive doesn't work
results addClass() doesn't work.
<div class='container'>
<div class='divWithNgRepeat' ng-repeat='artcl.content | unsafe'>
<p>
<img src='bla.jpg' <--no class added>
</p>
</div>
</div>
please help me master, thanks
First, try change the "ng-repeate" to "ng-repeat". If that's not the problem, then the jQuery line may be running before than ng-repeat loop. In this case you need to use something like:
angular.element(document).ready(function () {
$('img').addClass('img-fluid');
});
yess bro , I have successfully solved the problem. as # symphonic's says jquery is more executed before the ng-repeat directive finishes loading the data. I tried the code below and it worked
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal("show");
});
$("#myModal").on('shown.bs.modal', function(){
$('img').addClass('img-fluid');
});
});

json & JavaScript replacing html h1 heading?

When I reload my browser to show some json data the JavaScript code keeps replacing my HTML code? How can I correct the problem?
JavaScript code:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.write(data.title);
};
HTML Code:
<div class="container">
<div id="json_example">
<h1>json Example</h1>
</div>
</div>
Don't use document.write() as it replaces fully built HTML documents with the new content. document.write() should only ever be used to construct dynamic pages while the page is being built.
Instead, just populate some pre-existing element with data.title,
As in:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#output").text(data.title);
};
<div class="container">
<div id="json_example">
<h1>json Example</h1>
<span id="output"></span>
</div>
</div>
You are using document.write() which takes your document, and replaces it's content with the content you supply to the function. If you want to replace just the content of the <div id="json_example"></div> element, then you can use the following snippet in place of the document.write():
$("#json_example").text(data.title);
For non jQuery-version:
document.querySelector("#json_example").innerText = data.title;
If you want to replace the content of the <h1> the correct selector would be #json_example h1 instead.
In all the snippets what you do is find the element you want to change the content of using a CSS-selector. Both jQuery and pure Javascript supports this since IE8.
After finding the correct element, you set the elements content text to the content you want.
NOTE! Do NOT use innerHtml or .html() to set the content, as that opens you to script injections. Only use those methods when you generate the HTML yourself on the fly, in the browser. Even your database needs to be considered dirty.
try this
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.getElementById("json_example").textContent = data.title;
};
Since you're already using jQuery here's a possible solution which uses it.
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#json_example").html("<h1>" + data.title + "</h1>");
};
This replaces your div html with your content.

jQuery Accordion and Angular JS

I'm trying to make a jQuery accordion from an Angular JS ng-repeat directive. The code doesn't match the example in jQuery UI and it doesn't work. The element with ng-repeat appears to be messing it up. I want h3 as the title and the div below as the content. Repeat for each details.dataset. I've tried without the Ang JS command and it works, so the javascript libraries are loaded correctly.
$(document).ready(function () { $("#myAccordion").accordion(); })
<div id="myAccordion">
<div class="dockListing" ng-repeat="data in details.dataset">
<h3>{{data.name}}</h3>
<div>
<p><strong>Data 1:</strong>
{{data.content}}
</p>
</div>
</div>
</div>
here $(document).ready(...) section is loading first and it is arranging whatever it is getting inside the "#myAccordion" div in accordion format.And then the "ng-repeat" is taking place and fetching "details.dataset".So, first make sure "details.dataset" arrives first and then the " **** $("#myAccordion").accordion(); **** " fires.You can use setTimeOut(time) function or any callback function to achieve that.

jquery html() and append() not working

for some reason both methods results are TextNode. It means that browser doesnot parse content of appended string.
for example
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append(code);
on the page I do have content
"<div><p>Some</p> news are <span>here</span></div>"
this
$("#news_details").contents()
shows that string with html source is attached(for some reason unknown to me) as single textnode
but if will type in firebug
var text = $('#news_detaisl').text()
$('#news_details').contents().remove()
$('#news_details').append(text)
and after that, it is parsed and shows in a right way.
user the html()
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").html(code);
Since you haven't asked a question directly I can only assume what you want. Try this and tell me if it helps and if it was what you wanted:
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append($(code));
Oh and $().append and $().html do NOT behave in the same way. $().append adds the input as a new child while $().html either returns the innerHTML of an element or sets it. Depending on whether you set a parameter.
only this code works fine, but such a weird behavior
var content = news.newsDetails(here async ajax request which load html snippet with content); //content is a string with html snippet from server
$("#news_content").append(content);
var value = $(".news_title").text();
$(".news_title").contents().remove();
$(".news_title").append(value);
$(".news_details").css('display','block')
and html snippet
<div class="news_details">
<img class="pointer" src="/static/img/close6.png" alt="close" width='16' height='16'>
<div class="news_head gradient">
<span>{{ item.pub_date|date:"d M Y" }}</span>{{ item.title }}
</div>
<div class="clear"></div>
<div class="news_title">{{ item.full_text }}</div>

How to store a HTML snippet and insert it later in the document?

Is there a way to store a HTML snippet in a variable using Javascript or jQuery like this? (obviously it's a non-working an example)
var mysnippet = << EOF
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
EOF
And then insert it in the document using jQuery:
mysnippet.append($('#someelement'));
EDIT:
Please, read this before answering of commenting: What I have is a raw HTML snippet inside my JS file, and I need to store it in a Javascript variable using something like that EOF construction. I need to avoid putting it between quotation marks.
If it's not possible using Javascript and/or jQuery, then the question has no solution.
Just get the HTML code of the div you want by var content = $('#somediv').html(); and then append it to some div later on ! $('#otherdiv').append(content);
$().html(); delivers the HTML Content of that div. documentation: http://api.jquery.com/html/
$().append(<content>); appends the Content to a special div. documentatoin: http://api.jquery.com/append/
You could use javascript templates like ejs and haml-coffee.
You could write:
var mysnippet = "<div class='myclass'>"+
"<div class='anotherclass'>"+
"Some dummy text"+
"</div>"+
"</div>";
and then insert is using the append function (which takes the snippet as argument).
Yes. Fiddle example
JavaScript
var html = '<b>Bold</b>'
$('.anotherclass').append(html);
HTML
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
Unfortunately nothing like << EOF is available. Here's one solution:
$el = $('<div />')
.addClass('myClass')
.append(
$('<div />')
.addClass('anotherclass')
.text('Foo Bar')
);
Thinking on the same issue I have found this discussion. What I have in mind is to put a hidden textarea, containing the html, and then retrieving the html from there.
Thus there will be no conflicts with doubled DOM ids, since textarea content isn't rendered as html.
For those who come across this as I have...
You may wish to use the new
<template>
tag in HTML5.
It still doesn't store the HTML in the JavaScript unfortunately :(

Categories

Resources