1

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!

1
  • you only want to change the value of ordercode? Commented Oct 24, 2014 at 5:35

5 Answers 5

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

easy does it:

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

enjoy!

Comments

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

Comments

0

use this keyword

value=$(this).val();

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.