-1

I am having Jquery function with an div id, I have to attached a dynamic value with that div id. The div id name is foodtypes

$(function() {
var i = 0;
$('body').on('click','#foodtypes+i+ input',function() {
    console.log('foodtype function called')

});

But this method is never called.SO, i hardcoded the value of i as below then its working fine.

 $(function() {
var i = 0;
$('body').on('click','#foodtypes0 input',function() {
    console.log('foodtype function called')

});

Someone help me how to pass that or concatenate the variable dynamically.

1
  • You must be in a class, I saw this question yesterday. It's the same way you would concat a string to a variable. The selector is just a string. Commented Nov 9, 2014 at 6:44

3 Answers 3

1

It's just string arithmetic in Javascript:

'#foodtypes' + i + ' input'

will produce this (if i === 0):

'#foodtypes0 input'

You can just add strings in Javascript and when you add a number to a string, the number is converted to a string before adding it onto the previous string.

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

Comments

1

it should be:

$('body').on('click', '#foodtypes'+i+' input', function() {
    //do something
});

Comments

0

try to use below code :

   $(function() {
    var i = 0;
    $('body').on('click','#foodtypes' + i + ' input',function() {
        console.log('foodtype' + i + ' function called');
    });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.