Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>  
like image 963
thank_you Avatar asked Aug 26 '12 23:08

thank_you


People also ask

Which operator is used to concatenate two or more strings?

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.


1 Answers

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.

like image 74
sabithpocker Avatar answered Sep 20 '22 12:09

sabithpocker