0

My code is the following:

const pagedata = {
    name: "Value for name",
    email: "Value for email",
  };

$(".fillvalfromvar").val(pagedata[$(this).attr("id")]);

I need to fill all the elements having the fillvalfromvar class with the value of the variable pointed to by the element id. For example the HTML is the following:

<input id="name" class="fillvalfromvar" type="text">
<input id="email" class="fillvalfromvar" type="text">

And I’d like to fill those vals with pagedata["name"] and pagedata["email"], respectively.

But the this value isn’t pointing to the original element. What should I use instead?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Roman Matveev
  • 563
  • 1
  • 6
  • 22
  • How about to set `fillvalfromvar` into class property for each of your elements? – DaGLiMiOuX May 23 '13 at 09:46
  • Why can't you just hardcode it in? What is `this` meant to refer to? – Dharman May 23 '13 at 09:46
  • Some closely related variations: Mapping the current value (e.g. via a function, or appending something to it): [Modify the value of each textfield based on original value using jQuery](/q/24725927/4642212), and [Append text to input field](/q/841722/4642212); Using the index of the element in the collection: [Insert array values in inputs with specific class, index by index](/q/58516211/4642212). – Sebastian Simon Feb 08 '22 at 05:09

4 Answers4

4

Use the syntax that accepts a function as the parameter

$('.fillvalfromvar').val( function(){
   return pagedata[ this.id ];
});

(assuming that those input elements have the fillvalfromvar class)


or you could use the .each() method

$('.fillvalfromvar').each( function(){
   this.value = pagedata[ this.id ];
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

simply use $.each

$('.fillvalfromvar').each(function(){
   $(this).val(pagedata[$(this).attr('id')]);
});

or use $('input[id]') if those inputs dont have the class mentioned

Alex
  • 9,911
  • 5
  • 33
  • 52
0

Try this

$('.fillvalfromvar').each(function(){
     $(this).val(pagedata[$(this).attr('id')]);
})
Fikri Marhan
  • 359
  • 1
  • 9
-1

you need to define the class of your input text:

<input id='name' type='text'  class="fillvalfromvar">
<input id='email' type='text' class="fillvalfromvar">

Please try this.

skparwal
  • 1,086
  • 6
  • 15