'How to reach the element itself inside jQuery’s `val`?
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 val
s with pagedata["name"]
and pagedata["email"]
, respectively.
But the this
value isn’t pointing to the original element. What should I use instead?
Solution 1:[1]
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 ];
});
Solution 2:[2]
simply use $.each
$('.fillvalfromvar').each(function(){
$(this).val(pagedata[$(this).attr('id')]);
});
or use $('input[id]')
if those inputs dont have the class mentioned
Solution 3:[3]
Try this
$('.fillvalfromvar').each(function(){
$(this).val(pagedata[$(this).attr('id')]);
})
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gabriele Petrioli |
Solution 2 | Alex |
Solution 3 | Fikri Marhan |
Solution 4 | skparwal |