Why is my jQuery .css function not working? - javascript

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.

Related

How can I reuse result from JQuery for javascript textual matching?

I have html elements coming into function as string, then I am injecting elements into it as string however to my surprise it didn't work.
something like:
var replacement = $(row).find('td:last').append("<script type=\"text/javascript\"> function remove" + override.SessionKey + "(){ $('tr[session-key=\"" + override.SessionKey + "\"]').remove(); }</script><input type=\"button\" value = \"Remove\" onClick=\"remove" + override.SessionKey + "()\" />")
row.replace($(row).find('td:last')[0],replacement[0])
After some further investigation I have narrowed it down to matching failing in replace function, basically after you search with JQuery result cannot be used for textual matching
Here is an example of what I mean:
var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"
$('div').text(r.indexOf($(r).find('td:last')[0]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div></div>
One would expect to always have a match as I am using contents of original html string.
How can I reuse result from JQuery for textual matching?
I think you're looking for .outerHTML:
var r = "<tr class=\"hide\" session-key=\"SessionProductDataMotorEnrichmentSagaFactorScore\" session-key-data-type=\"Decimal\"><td id=\"tdDisplayName91\">SagaFactorScore</td><td id=\"tdValue91\"></td></tr>"
$('div').text(r.indexOf($(r).find('td:last')[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div></div>
That is a terrible way of doing what you're trying to do.
var btn = $("<button></button>");
btn.attr("type","button").text("Remove").on("click",function() {
var tr = $(this).closest("tr");
tr.remove();
});
This creates the button with associated event bound directly to it. You can then append it to all rows, for instance, like so:
$("tr>td:last-child").append(function() {return btn.clone(true);});

javascript load image to div onclick

I want to display image user click from image link in a for loop to a div.
my for loop is as follows.
<a href='' name=my_image[i]
onclick='disp_image('link_image_url')'id=my_image[i] class='popup-open'><img src=my_image[i] width='80' height='65'></a>;
and my javascript function
<script language=\"javascript\">
function disp_image(url){
document.getElementById('image').innerHTML ="<img src=url width='100' height='105'>";
;}
</script>
</script>
However it is not being load in my div content
<div id="image"></div>
can someone has an idea how can i display selected image in a div content dynamically
Use this:
var _leng = my_image.length
, td = "<td><a href='#url#' onclick='displaying(/image#url#)' id='/image#url#'><img src='#url#' width='80' height='65' /></a></td></tr><tr>"
, i;
for (i=0; i < _leng; i++) {
str += td.replace(/#url#/g, my_image[i])
}
Check this example:
http://jsfiddle.net/hMfRG/
You have mismatched quotes so the string isn't being generated properly, or at all... you probably have errors in the console.
str += "<td><a href='" + my_image[i] + " onclick='displaying()' id='/image" + my_image[i] + "'><img src='" + my_image[i] + "' width='80' height='65' /></a></td></tr><tr>";
You can't use these special quotes ‘’ or ”, only use these single or double quotes ' or ".
Example:
document.getElementById('image')
You have displaying() in the loop but below, its called displayImage(). Also, the function expects an argument which you're not supplying in the call.
Look at the syntax highlighting of your post. You can clearly see that your quotes are all over the place. For instance, you have src='"+url+'", which is wrong. You also have "smart quotes" in places. Fix the quotes and it should stop throwing syntax errors.
But most importantly, your onclick function calls displaying(), whereas the function is called displayImage and takes an argument.
I've done it this way:
<div id="result" style="width:450px;height:296px;">
<img name="main" src="/images/image.jpg" alt="">
</div>
function change_pic(img_name,img_src)
{
document[img_name].src=img_src;
}

Dynamic str replace with javascript on html containing stream

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...

jquery: "Exception thrown and not caught" in IE8, but works in other browsers

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?!

problem with using getElementById().getValue in FBJS/Facebook !

I am using this code to generate hidden HTML code in Facebook :
echo "<div id=\"y257y\" style=\"display:none;\">".$fdesc."</div>";
And, I am trying to get this element back in JS using the following code
newVal=document.getElementById('y257y').getValue();
But, I am getting an error: Undefined
Can anyone kindly help me out ?
Thanks.
-
ahsan
Instead of:
newVal = document.getElementById('y257y').getValue();
try using:
newVal = document.getElementById('y257y').innerHTML;
Are you using any JavaScript library, like jQuery or Prototype? If you're using jQuery:
newVal = $('#y257y').html();
Other suggestions:
Use hidden form element:
echo "<input type=hidden id=y257y value=\"$fdesc\">";
and in JavaScript:
newVal = document.getElementById('y257y').value;
Or just output a <script> tag:
echo "<script>newVal = \"$fdesc\";</script>";
and there's no need to find the value in the DOM – it's already in JavaScript.
Try using a textarea? Since at least that may have a getValue method if you are really lucky:
$fdesc = str_replace('<', '<', $fdesc);
$fdesc = str_replace('>', '>', $fdesc);
echo "<textarea id=\"y257y\" style=\"display:none;\">".$fdesc."</textarea>";
newVal=document.getElementById('y257y').getValue();
newVal = newVal.replace(">", ">")
newVal = newVal.replace("<", "<")
But something tells me that is not going to work for you, facebook may not like it.
Seems easier just to do this:
$fdesc = <<<EOD
<div>Here is your html</div>
<p>And some more </p>
EOD;
$fdesc = str_replace("'", "\'", $fdesc); //Escape single quotes
$fdesc = str_replace("\n", "";', $fdesc); //Get rid of line breaks
echo "var fdesc = '$fdesk';";

Categories

Resources