SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Aug 2004
    Location
    Italy
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Synthax troubles

    Hi all,
    i have this code:


    Code:
    var popupSrc = document.getElementById("f_url").value;
    
    var popupTitle = document.getElementById("poptitle").value;
    
    
    html = "<a href=javascript:myPopImage(";
    
    html += "'" + popupSrc + "',";
    
    html += "'" + popupTitle + "'";
    
    html += ")>";
    where "f_url" and "poptitle" are text fields.
    It should always output:

    Code:
    <a href=javascript:myPopImage('http://www.sampleurl.com/image.jpg','Popuptitle')">
    but it stops working if the value of "poptitle" field is made of
    more than one word,like:

    Code:
    <a href=javascript:myPopImage('http://www.sampleurl.com/image.jpg','My Popup Title')">
    It seems that the space(s) between 2 or more words inside "poptitle" field
    affects and breaks the synthax of the code producing stange outputs like:

    Code:
    <a href=javascript:myPopImage('http://www.sampleurl.com/image.jpg','My)">
    so it truncates the value to the first word.
    I need some help,of course.
    Where i am wrong?
    Thanks in advance,ralf.

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use the following simple function to avoid troubles when building long formatted strings in javascript:

    Code:
    function sprintf(format) {
    	var args = sprintf.arguments, i = 1;
    	return format.replace(/%s/g, function() {
    		return args[i++];
    	});
    }
    With this function your code looks much simpler:

    Code:
    html = sprintf(
    	"<a href=javascript:myPopImage('%s', '%s')>", 
    	popupSrc, 
    	popupTitle);
    hth...

  3. #3
    SitePoint Member
    Join Date
    Aug 2004
    Location
    Italy
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you,
    i'll try and let you know.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •