Reputation: 11107
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>
Upvotes: 31
Views: 180371
Reputation: 15566
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.
Upvotes: 47
Reputation: 339786
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
Upvotes: 4