简体   繁体   中英

How to select all elements in name array?

I am trying to sum a collection of radio selections using jQuery.

<input name="cost[alpha]" type="radio" >
<input name="cost[beta]" type="radio">
<input name="cost[delta]" type="radio">
...
$('input[name="cost[*]"]').each( function() {
    ...
}

This does not function as it tries to resolve an input with the name "cost[*]". Ideally I would like to iterate over any element in the cost array. Is there a preferred way of doing this with jQuery? I have other elements in my form that use the radio type so selecting radios in general is not a valid option.

Make the attribute selector the " starts with " selector ( ^= ):

$('input[name^="cost"]').each(function() {
    ...
});

If you find that you have other input elements that start with "cost" or even "cost[", then perhaps you want to think about changing the way you're querying for the elements. One alternative would be adding a special class name to the elements you're targeting and forget about their names altogether. For example:

<input name="cost[alpha]" type="radio" class="form-cost">
<input name="cost[beta]" type="radio" class="form-cost">
<input name="cost[delta]" type="radio" class="form-cost">

And then your selector is very simple and very targeted:

$('input.form-cost').each(function() {
    ...
});

You might get the best performance out of simply wrapping the elements in a container with a unique id or class name, and querying for input elements that it contains (as suggested by Allende in the comments):

<div id="cost-inputs">
    <input name="cost[alpha]" type="radio">
    <input name="cost[beta]" type="radio">
    <input name="cost[delta]" type="radio">
</div>

$('#cost-inputs input').each(function() {
    ...
});

尝试在jQuery中使用包含选择器

$("input[name*='cost[']").each(function(){});

Try:

var sum = 0;
$("input[name^='cost']").each(function() {
     sum += Number($(this).val());
});

About "Starts With Selector": [name^="value"]
https://api.jquery.com/attribute-starts-with-selector/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM