I have a html which looks roughly like this
<div id="wallPostTemplate">
<li id='comment-content--oOo-id-oOo-' class='comment-content' comment_id='-oOo-id-oOo-'>
<a class='comment-avatar' href='-oOo-link-oOo-'>
<img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>-oOo-korisnikPodaci.Slika-oOo-'></a>
-oOo-text-oOo-
</li>
</div>
Now I get the contents of the html into a sting with $('#wallPostTemplate').text() and then I want to replace dynamically the occurrences of the string -oOo-id-oOo-
with whatever data I have stored inisde a variable like -oOo-id-oOo-, -oOo-text-oOo- and so on...
Now I tried numerous ways to tackle this thing but I always end up without a solution.
Here is my latest try out. HELP pls Q_Q
var regex = new RegExp('{\-oOo\-'+index+'\-oOo\-}', "g");
post = post.replace(regex, value);
Also I tried str.replace but it does not work... It seems new lines are the problem but I have no idea how to over come this.....
edit:
To make it more simple to understand i made a example on jsfidle: http://jsfiddle.net/DdBFB/
And as you can see, you can see nothing.... it dous not work when you get the content over the html function.
If I understand your question your goal is make something like a post template that will be loaded in runtime/cliente side. So if this is really your goal you can try use the jQuery Template Plugin
Sample for your case: (don´t tested yet)
var tmlpPost = "<div id='${postId}'>" +
" <li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>" +
" <a class='comment-avatar' href='${link}'>" +
" img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>" +
" </a> " +
" ${postText}" +
" </li>" +
"</div>";
$.tmpl( tmlpPost, { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something", "postText" : "Post text goes here..."}).appendTo( "#yourPostWall" );
Or using <script> not a var: See this Fiddle
<script id="tmlpPost" type="text/x-jquery-tmpl">
<div id='${postId}'>
<li id='comment-content-${postId}' class='comment-content' comment_id='${postId}'>
<a class='comment-avatar' href='${link}'>
<img class='small_avatar' src='<?="../" . MESTO_ZA_UPLOAD_FAJLOVA_KORISNIKA ?>${korisnikPodaciSlika}'>
</a>
${postText}
</li>
</div>
</script>
Now on page load:
$("#tmlpPost").tmpl( { "postId" : "123" , "link" : "http://posturl.com", "korisnikPodaciSlika" : "something", "postText" : "Post text goes here..."}).appendTo( "#output" );
Although your question is not really clear I've whipped up an example that replaces a value based on a regular expression.
var source = "-oOo-korisnikPodaci.Slika-oOo-";
var id = "korisnikPodaci.Slika";
var regex = new RegExp('\-oOo\-' + id + '\-oOo\-', "gmi");
// Match
source.replace(regex, "hello world"); // => "Hello World"
// Mismatch
source = "-oO!!!o-korisnikPodaci.Slika-oO!!!o-";
source.replace(regex, "hello world"); // => "-oO!!!o-korisnikPodaci.Slika-oO!!!o-"
ok, i figured the answer was that i set the regex flags wrong, so i went to jsfiddle and fiddled with it and you can see the answer there :)
http://jsfiddle.net/DdBFB/11/
I was missing the multi line flag Q_Q....im no good with regex even in php not to speak in js...
Related
I put together a quote machine as an exercise of freecodecamp.com. You click the button, you get a quote. Then, if you want, you can tweet the quote by clicking the "Tweet It" button. I had a lot of trouble figuring out how to get the quote to populate the tweet field. I finally just looked at someone else's code on the issue, and now it is populating.
The problem: it is populating <p> and </p> tags with every quote. Example:
"<p>When typography is on point, words become images.</p>
" Shawn Lukas
It's also annoying that the second set of quotation marks always appears on the line below next to the author's name.
I'm not sure how the tags are getting in there, but I'd like help clearing them out. Here's my code:
HTML
<div id="container">
<div class="content">
<div id="quote" class="triangle-isosceles">
<p>
<span class="msg"></span>
</p>
</div>
<p id="author"><span class="nme"></span></p>
</div>
<button type="button">Get Quote</button>
<a class="twitter-share-button" id="tweet-quote" target="_blank">
<button type="button" class="btn btn-primary">Tweet it!</button>
</a>
</div>
JS
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + "<p>— " + author + "</p>")
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + quote + '" ' + author));
});
});
</script>
I'm omitting the CSS. I can't get a jsfiddle to work (never can), but here's the CodePen link: https://codepen.io/dtarvin/pen/pePowj
Update: just found a quote with an apostrophe and got back those numbers instead of the symbol. Not sure how to handle that when the quotes are random.
Thanks!
you have "<p>— " + author + "</p>" in the append code, regarding the html entity code you need to parse the quote to switch them to the normal version. Also you might need to remove tags within the a[0].content variable. if you have no control over what is returned, you may need to do a lot more filtering to catch stuff like this.
Or if you have access to the serverside script, then use this to get the quote and return the cleansed quote.
For instance, if you visit the url https://quotesondesign.com/wp-json/posts you will see the <p> tags within the quote themselves.
So you basically need to clean the content of the content variable.
for instance to remvoe the p tag within the content string try:
var quote = a[0].content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '');
If you need these tags in to display then you could add a seperate function that on pressing the tweet it button, will do this for you.
So you have them on the browser but on tweeting its all striped and good on twitter
Try this it work
<script>
$.ajaxSetup({
cache: false
});
$('button').on('click', function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
var quote = a[0].content;
var author = a[0].title;
$(".msg").empty().append(quote + author);
var html = quote + author;
var div = document.createElement("div");
div.innerHTML = html;
var text = div.textContent || div.innerText || "";
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent( text ));
});
});
</script>
I have some code that is roughly along the lines of this:
exportValue = [];
function reduceArray() {
//does something
exportValue = parseFloat(exportValue)
}
From that, I get that exportValue is 73951. I then have to add that number to the page... so I tried both of these:
$("#exportValueDiv").append(exportValue);
$("#exportValueDiv").append("<li>" + exportValue + "</li>");
But that doesn't work.. I'm confused on how to add something like a variable to the DOM....
If I do something like:
$( "#exportValueDiv" ).append( "<li>value</li>")
it works, but I don't want to add a string, I want to add the value of the variable. I looked this up, but I'm still confused, so any help would be greatly appreciated!!!
Look into jQuery manipulation
$("#exportValueDiv").text(exportValue); //Replaces text of #exportValueDiv
$("#exportValueDiv").html('<span>'+exportValue+'</span>'); //Replaces inner html of #exportValueDiv
$("#exportValueDiv").append('<span>'+exportValue+'</span>'); //Adds to the inner html of #exportValueDiv
The .append() contract expects a DOM element or HTML String. You will need to do:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
Try this:
$("#exportValueDiv").append("<div>" + exportValue + "</div>");
The following appends your variable to a div that already has information:
<div id="exportValueDiv">
<p>
Some information.
</p>
</div>
<script>
var exportValue = "Hello world.";
$("#exportValueDiv").append('<p>'+ exportValue +'</p>');
</script>
https://jsfiddle.net/supadave57/f9tqw0d4/
I'm using jQuery and I want to show FullName of a Student in popup, but I'm getting only first name, e.g. if I want to show Abc Xyz it is only showing Abc - it is taking only the first word but not the word after the space.
My code is as given below:
<a data-dialog-href="#" id="delete-#item.StudentId" href="#" data-studentName=#item.StudentName>Click Here</a>
jQuery('body').on('click', '[data-dialog-href]', function (e) {
var studentName = jQuery(this).attr('data-studentName');
alert('Student Name : ' + studentName);
}
How can I get whole string including space? Thanks in advance.
The issue is because you need to wrap the value of the attribute in your HTML in quotes, otherwise the first space reached will delimit the value. Try this:
<a data-dialog-href="#" id="delete-#item.StudentId" href="#" data-studentName="#item.StudentName">Click Here</a>
Also note that you should use the data() method to retrieve the value:
$('body').on('click', '[data-dialog-href]', e => {
var studentName = $(e.target).data('studentName');
console.log('Student Name : ' + studentName);
});
I'm building some kind of add/remove taglist that is connected with mySQL. I've managed to get the tags from the database to display with a ajax call, but i can't do any kind of operation to them. Not even a common style. When i check with Firebug all the html seems to be in place so i can't figure out what's wrong. Here is my code:
jQuery:
$(document).ready(function() {
$("#ontvangenjson").css("border","3px solid red");
$.getJSON("jason2.php", function(data) {
$.each(data, function(){
var merkTag = " <a class=\"deletemerk\" href="+"http://localhost/website/remove_merk.php?id="+this.pkFavorietemerken+">" + this.merken + "</a>";
$("#ontvangenjson").append(merkTag);
});
});
});
PHP: jason2.php
$merken_lijst = "SELECT favorietemerken.pkFavorietemerken, favorietemerken.merken FROM favorietemerken JOIN bedrijven ON bedrijven.pkBedrijvenID=favorietemerken.fkBedrijvenID WHERE favorietemerken.fkBedrijvenID=$neem_id";
$rows = array();
$sth = mysql_query($merken_lijst);
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
RECEIVED JSON:
[{"pkFavorietemerken":"71","merken":"Nike"},{"pkFavorietemerken":"70","merken":"Le Coq Sportif"},{"pkFavorietemerken":"69","merken":"Converse"},{"pkFavorietemerken":"68","merken":"Champion"},{"pkFavorietemerken":"67","merken":"Adidas"}]
HTML:
<body>
<h1><label for="brands-form-brand">Get JSON data</label> <input type="button" id="knop" value="get JSON" /></h1>
<hr />
<p class="section-title"><strong>JSON Data received</strong></p>
<div id="ontvangenjson"> </div>
</body>
ANSWER
After alot, alot,alot of research I've finaly solved this problem. The code wasn't really wrong but a piece of it was misplaced. The get.JSON is asynchronous meaning if you want to make any changes using the jQuery .css function you will need to do that inside the callback for the getJSON.
$.getJSON("jason2.php", function(data) {
var merkTag = "";
$.each(data, function(){
merkTag += " <a class=\"deletemerk\" href="+"http://localhost/website/remove_merk.php?id="+this.pkFavorietemerken+">" + this.merken + "</a>";
});
$("#ontvangenjson").append(merkTag);
// NEW CODE
$(".deletemerk").css("border","3px solid red");
});
Shorthand properties (such as border) are not supported by jQuery.css().
http://api.jquery.com/css/
If you want to use all the three properties of border, try defining them independently , it might solve your problem.
I'm not sure this will solve your problem, but I would start by trying to clean up the way you're making that link. You may have missed one or two quotes. Instead of the confusion of escaping or failing to escape double quotes, just surround your string with single quotes:
var merkTag = '<a class="deletemerk" href="http://localhost/website/remove_merk.php?id='
+ this.pkFavorietemerken
+ '">'
+ this.merken
+ '</a>';
This leaves you free to use double quotes when you're building an HTML string. I've used multiple lines here just for clarity's sake. Clarity over brevity.
My code works fine in other browsers, but in IE8 I get "error on page" - and when I click that it says:
"Exception thrown and not caught Line: 16 Char: 15120 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"
I tried linking to jquery.js (rather than jquery.min.js) and to 1.5.1/jquery.min.js,
but problem still remains.
Can someone correct/improve my code for me, or guide me as to where to look. Thanks
<script type="text/javascript">
function fbFetch()
{
var token = "<<tag_removed>>&expires_in=0";
//Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
var url = "https://graph.facebook.com/<<ID_REMOVED>>?&callback=?&access_token=" + token;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url, function(json)
{
json.data = json.data.reverse(); // need to reverse it as FB outputs it as earliest last!
var html = "<div class='facebook'>";
//loop through and within data array's retrieve the message variable.
$.each(json.data, function(i, fb)
{
html += "<div class='n' >" + fb.name;
html += "<div class='t'>" + (dateFormat(fb.start_time, "ddd, mmm dS, yyyy")) + " at " + (dateFormat(fb.start_time, "h:MMtt")) + "</div >";
html += "<div class='l'>" + fb.location + "</div >";
html += '<div class="i"><a target="_blank" title="opens in NEW window" href="https://www.facebook.com/pages/<<id_removed>>#!/event.php?eid=' + fb.id + '" >more info...</a></div>';
html += "</div >";
}
);
html += "</div>";
//A little animation once fetched
$('.facebookfeed').animate({opacity: 0}, 500, function(){
$('.facebookfeed').html(html);
});
$('.facebookfeed').animate({opacity: 1}, 500);
});
};
Does the code do the job in IE8 or does it break? The reason I ask is because if it works as expected you could just wrap it in a try{ } catch{ \\do nothing } block and put it down to another thing IE is rubbish at.
You may be better off creating an object for the creation of the facebook div. Something like...
var html = $('<div />');
html.attr('class', 'facebook');
Then in your each loop you can do this...
$('<div />').attr('class', 'n').append(fb.name).appendTo(html);
$('<div />').attr('class', 't').append etc...
Then append html to the facebookfeed object
Doing this may remove the scope for error when using single quotes and double quotes when joining strings together, which in turn may solve your issue in IE8
$('.facebookfeed').fadeOut(500, function(){
$(this).append(html).fadeIn(500);
});
Hope this helps!
UPDATE
The append method is used to add stuff to a jquery object. For more info see here
So to surround the div's as you mentioned in the comments you would do something like this...
var nDiv = $('<div />').attr('class', 'n').append(fb.name);
$('<div />').attr('class', 't').append(fb.somethingElse).appendTo(nDiv);
// etc
And then you would need to append that to the html div like so...
html.append(nDiv);
So that would give you
<div class="facebook">
<div class="n">
value of fb.name
<div class="t">
value of fb.somethingElse
</div>
</div>
</div>
So what you have done is created a new jquery object and appended to that, then appended that to the html object which you have then appended to the facebookfeed div. Confusing huh?!