How to get the variable passed through the function JavaScript/jQuery

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.

Answers


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.


Need Your Help

How to read Tomcat JDBC Data Sources Resource Factory properties?

java spring tomcat jdbc jndi

I have an tomcat 6 with an configured JNDI Tomcat JDBC Data Sources Resource Factory. Now my task is to verify that the connection pool has a minimal max size.

Enterprise distribution profile expired. What to do?

ios xcode6 provisioning-profile enterprise

I have developed and published an Enterprise iOS app, a year ago.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.