-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.

Karthik
  • 470
  • 8
  • 25
  • 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. – scrappedcola Nov 09 '14 at 06:44

3 Answers3

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

it should be:

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

try to use below code :

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