-4

I am using JQuery to output a link to my webpage. Part of the link is dynamic, and I am having trouble using variables and text together. The variable just gets treated as text. What am I doing wrong?

My Jquery:

var new_collection_id= 1;
var new_collection_title= 'This is a title';

.html('<a href="collection.php?id=1&collection=new_collection_id">     
new_collection_title </a>')
2
  • 1
    How the script should know that those are variables? String Concatenation. Commented Jan 31, 2014 at 20:27
  • Just out of curiosity, have you done any research? Commented Jan 31, 2014 at 20:33

2 Answers 2

3

You need to use concatenation.

.html('<a href="collection.php?id=1&collection=' + new_collection_id + '">' + new_collection_title + ' </a>')
Sign up to request clarification or add additional context in comments.

Comments

3

You need to use string concatenation.

.html('<a href="collection.php?id=1&collection=' + new_collection_id 
     + '">' +  new_collection_title + '</a>')

Ideally I would suggest you to use

.html( $('<a></a>')
      .text(new_collection_title)
      .attr('href', 'collection.php?id=1&collection=' + new_collection_id)
    )

DEMO

2 Comments

@plalx While that's needed in general, you can do without it when you know the ID is always a number.
@Barmar I know, however there's no way to tell here... well now it seems there is since the OP modified the question ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.