jason328 jason328 - 7 months ago 21
Javascript Question

Concatenate in jQuery Selector

Simple problem. I have a js variable I want to be concatenated too within a jQuery selector. However it is not working. No errors are popping up either. What is wrong? How do I correctly concatenate a variable to some text in a jQuery selector.

<div id="part2"></div>

<script type="text/javascript" >

$('#button').click(function ()
{
var text = $('#text').val();
var number = 2;
$.post('ajaxskeleton.php', {
red: text
},
function(){
$('#part' + number).html(text);
});
});


</script>

Answer

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.