sAs59
sAs59

Reputation: 572

Jquery changing attributes using loop

If I have the following variables:

var ordercode, ordername, order1price, orderfree;

How can I add the values of these variables to attr[value] using 'each'?

<form>
   <input type="hidden" name="ordercode" value="">
   <input type="hidden" name="ordername" value="">
   <input type="hidden" name="order1price" value="">
   <input type="hidden" name="orderfree" value="">
</form>

Like:

$('form input').each(function {
    value = ordercode where name = ordercode
})

Thanks!

Upvotes: 1

Views: 1175

Answers (5)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

If you want to change the value of a particluar input, use like this

$("input[name='ordercode']").val("new value");

Upvotes: 0

Anas
Anas

Reputation: 991

use this keyword

value=$(this).val();

Upvotes: 0

Gurkan İlleez
Gurkan İlleez

Reputation: 1573

$('form input').each(function() {
    if (this.name == 'ordercode'){
        this.value = 'ordercode';
    }
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388326

You can't access variables like that...

what you can do is to create an object with those input names as keys like

var obj = {
  ordercode: 'ordercode',
  ordername: 'ordername',
  order1price: 'order1price',
  orderfree: undefined
}
$('form input').val(function() {
  return obj[this.name];
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <input type="text" name="ordercode" value="">
  <input type="text" name="ordername" value="">
  <input type="text" name="order1price" value="">
  <input type="text" name="orderfree" value="">
</form>

Upvotes: 2

Sameer Shemna
Sameer Shemna

Reputation: 906

easy does it:

$('form input').each(function {
    $(this).val($(this).attr('name'));
});

enjoy!

Upvotes: 0

Related Questions