0

Here is the function

function addCategory(category) {
$('#category_choice').append($('#!the variable "category" has to go in here!'));
$('#feed_submit_categories').hide();
}

The "category" variable sends the id of the element that has to be appended. How can I insert the "category" var into the function? In PHP it is much easier having $var_name tags... But here, I have no idea as to how to include it.

1
  • 1
    You're looking for string concatenation. Commented May 2, 2013 at 18:06

3 Answers 3

3
function addCategory(category) {
    $('#category_choice').append($('#'+category));
    $('#feed_submit_categories').hide();
}

Simple example of concatenation ( variables, string ):

var h = "Hello";
var w = "World!";

alert( h+w );            // HelloWorld!
alert( h+' '+w);         // Hello World!
alert( h+' my dear '+w); // Hello my dear World!

jQuery selector can use string to represent literally an element ID selector:

$('#element')

that means you keep as string what you need and you concatenate a variable to it:

var elName = "element"; // string variable
$('#'+ elName) // same as: $('#element')

If you need to append every time a new fresh element do like:

$('#category_choice').append('<div id="'+category+'" />');

just make sure not to duplicate your elements ID for ID has to be unique per page element.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! random text to cover the minimum characters in comment box
thanx a million! I was doing it this way (but wasn't able to pass the "category" item), but than I decided to just copy the div I want to append, but it started consuming them =)
2

Use

function addCategory(category) {
  $('#category_choice').append( $('#'+category) );
  $('#feed_submit_categories').hide();
}

1 Comment

Thank you! random text to cover the minimum characters in comment box
2
$('#category_choice').append($('#'+category));

jQuery selectors are just strings that are evaluated, you can generate a string following basic Javascript rules.

For example :

var iAmString = "#"+category;
$(iAmString)  //<-- using string var as a selector

1 Comment

is there a way to make a copy of the div I am appending? Because I am echoing categories with PHP, and every time I run this function, it takes away the div...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.