-1

Is it possible to insert a variable in $(#var).val() ? In <td>, variable td should be used with # inside $(#td).val()

$(document).on('click', '#edit', function(){ 
  var td = $(this).data("name");
  var formdata = {foodtypename: $(#add-food-type).val()}
   
  $.ajax({
    type: 'put',
    url: '/editItem/'+$(this).data("id"),
    data: formdata,
    dataType: 'json',
    success: function(data){
      console.log(data);
      var product = '<tr class="item'+data.id+'">
        <td id="'+data.id+'">'+$(#td).val()+'</td></tr>'
    }
  });
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

0

Yes if you want to use td as id you could use concatenation sign + :

$("#"+td).val()

Line should looks like :

var product='<tr class="item'+data.id+'"><td id="'+data.id+'">'+$("#"+td).val()+'</td></tr>';

NOTE : You're missing quotes in $(#add-food-type).val(), full code will be like :

$(document).on('click', '#edit', function(){    
  var td = $(this).data("name");
  var formdata = {foodtypename: $("#add-food-type").val()}

  $.ajax({
    type: 'put',
    url: '/editItem/'+$(this).data("id"),
    data: formdata,
    dataType: 'json',
    success: function(data){
      console.log(data);
      var product = '<tr class="item'+data.id+'"><td id="'+data.id+'">'+$("#"+td).val()+'</td></tr>'
    }
  });
});

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • you can't just insert a newline in the middle of a string if not using template literals or escaping the newline. – Kevin B Mar 21 '17 at 16:22
  • I've just missed that you could see that the same line in the explanation isn't separed.. (thanks updated my post) – Zakaria Acharki Mar 21 '17 at 16:24
  • I still don't see an answer (or question for that matter) explaining how to combine strings as useful to the users of SO. at least not in this format. – Kevin B Mar 21 '17 at 16:25
  • Thanks Zakaria, I haven't finished writing the whole code. Will let know if it worked. and yes I will not insert newline. Thanks – creatorsTake Mar 21 '17 at 16:27
  • He want to form a jQuery selector with variable, that was the question @KevinB and my answer was just combine it as string using the `+` sign .. Not sure if this deserve a Downvote.. – Zakaria Acharki Mar 21 '17 at 16:33