0

I have 2 variables.

var a = 1;
var b = 2;

Now I have 2 input boxes with name 'form-1-a' and 'form-1-b'.

I need to put variables in these input boxes. Please look at below code as it is not working.

$("input[name^='form-']").val(eval($(this).attr('name').split('-')[2]));

Though entire code is bit complex but simplified and it does not seem to work without any error message.

Javascript is fun and pain at same time. Below code worked.

$("input[name^='form-']").each(function(){
  $(this).val(eval($(this).attr('name').split('-')[2]))
});
Pulkit Sharma
  • 264
  • 1
  • 2
  • 18
  • 2
    Related: ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530) – VLAZ Oct 24 '21 at 08:50
  • 2
    In practice, you never need — or _want_, really — dynamic variable names. Use a simple object instead: `const obj = { a: 1, b: 2 };` … `console.log(obj[$(this).attr('name').split('-')[2]]);`, or, for indexed structures, an array. Please also familiarize yourself with [how the "this" keyword works](/q/3127429/4642212); in particular, note that `.val` accepts a _function_ argument which binds its `this` value to the current element. – Sebastian Simon Oct 24 '21 at 08:51
  • 1
    At any rate, the problem here is the usage of `this` as it does *not* refer to the element that was found by jQuery. But using dynamic variable name resolution is also an issue. – VLAZ Oct 24 '21 at 08:53
  • I will try with each method. Let me try and update if it helps. – Pulkit Sharma Oct 24 '21 at 09:00
  • Related: [Do all set returning functions support implicit loop?](/q/52058369/4642212). – Sebastian Simon Oct 24 '21 at 09:08

0 Answers0