0

How do i cycle through all form inputs with a certain name and set those to a specified value?

I tried this jsfiddle and i can't get it to work. http://jsfiddle.net/qvcA6/

$(document).ready(function() {
    $("#link-1").click(function() {

$('[name=price]','#myform').val('0.00');
      });  
});

EDIT: i didn't think it would matter, but the array key for the form field name isn't accounted for. So all of your examples are working but they break when i put keys in the field names. Anybody know how to go about accounting for the keys? updated jsfiddle -> http://jsfiddle.net/qvcA6/8/

2
  • Side question for my own edification: isn't this going to cause problems when submitting the form? Typically names in a form are unique, and are used to create the request parameters. Commented Oct 20, 2011 at 1:01
  • 1
    Greg, price is an array in this case. Commented Oct 20, 2011 at 1:06

4 Answers 4

1

Updated the jfiddle for you http://jsfiddle.net/qvcA6/1/ There were two issues.

1) The attribute value needs to be surrounded by quotes.

2) The name of your inputs were 'price[]' and not 'price' so the jquery selector didn't match anything

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

2 Comments

that worked for that instance. I thought it would work when the price inputs have a key. But it doesn't. Would it be super complicated to account for all price inputs regardless of their key? jsfiddle.net/qvcA6/8
no that wouldn't be too hard. You can use this: $('[name^="price"]','#myform') the ^= is the 'starts with' selector so it will get all elements having a name that starts with the word price. That should work for you.
1

Here's a fiddle

$(document).ready(function() {
    $("#link-1").click(function(e) {
        $('#myform').find('input[name="price[]"]').val('0.00');
        e.preventDefault(); // use prevent default instead of inline js on the link. 
    }); 
});

1 Comment

thanks for the e.preventDefault(); trick. Didn't know that one! upvoted!
0

The name of your inputs is price[] not price, also it would be more efficient expecially in a long form to specify the tag name when using the attribute equals selector.

$('#myform input[name="price[]"]').val('0.00');

Here is a link your modified fiddle http://jsfiddle.net/qvcA6/7/

Comments

0

See my jsFiddle:

$(function() {
    $("#link-1").click(function() {
        $("input[name^=price\\[]", "#myform").val('0.00');
        return false;
    });
});

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.