user2990084
user2990084

Reputation: 2840

Concatenate javascript variable with html to create href

I am trying to create a href with html(), however the output is not correct. What is wrong with this jquery code?

$('#tag_modal').find('.modal-body').html("<a href='/companies/explore-companies?tags='"+data.results['tag_id']+">test</a>");

Output:

<div class="modal-body"><a 5="" href="/companies/explore-companies?tags=">test</a></div>

Upvotes: 0

Views: 2204

Answers (3)

Ghazgkull
Ghazgkull

Reputation: 980

Your quotes are wrong. Try:

$('#tag_modal').find('.modal-body')
    .html('<a href="/companies/explore-companies?tags='+data.results['tag_id']+'">test</a>');

Upvotes: 3

Musa
Musa

Reputation: 97672

You're closing the attribute before the tag id, close it after

$('#tag_modal').find('.modal-body').html("<a href='/companies/explore-companies?tags="+data.results['tag_id']+"'>test</a>");

Upvotes: 4

benjarwar
benjarwar

Reputation: 1804

Try creating your anchor element first:

var $anchor = $("<a href='/companies/explore-companies?tags='"+data.results['tag_id']+"'>test</a>");

And then appending it to your div:

$('#tag_modal').find('.modal-body').append($anchor);

That way you're breaking the process into discrete steps (first create the element, second append it to the DOM).

Edit: as others have mentioned, you also need to close the href value, with a single quote, before you close the tag with the greater-than symbol.

Upvotes: 0

Related Questions