简体   繁体   中英

How do I use two .siblings with the same input type?

I want to get "The walking dead" also but it only gets the first hidden. Can i put a class on .this or how should I do?

$(".articel input[type='button']").click(function(){                    
        var price = $(this).siblings("input[type='hidden']").attr("value");
        var quantity =  $(this).siblings("input[type='number']").attr("value");
        var name = $(this).siblings("input[type='hidden']").attr("value");
        var ul = document.getElementById("buylist"); 
        var prod = name + " x " + quantity + " " + price + "$";

        var el = document.createElement("li"); 
        el.innerHTML = prod; 
        ul.appendChild(el);

<form class="articel">
        Quantity: <input type="number" style="width:25px;"><br>
        Add to cart: <input type="button" class="btn">
        <input type="hidden" value="30">
        <input type="hidden" value="The walking dead">
</form>

The conventional way to identify form fields is by the name property.

HTML:

<input type="hidden" name="title" value="The walking dead">

jQuery:

var name = $(this).siblings('input[name=title]').val();

Your current selector, siblings("input[type='hidden']") , selects all hidden field siblings, but since you have no way to discern them, attr will always just yield the value of the first match.

You could also have iterated over your collection of elements, or accessed them by index siblings('input[type=hidden]:eq(1)') or siblings('input[type=hidden]').eq(1) , for instance, but it is a poor design that will break your code if you add another hidden field for something else. You really should prefer to name your elements so that you can access them in a meaningful way and know your data. That way you'll be free to move around and modify your markup according to new requirements, without breaking your script.

By the way, I'm using .val() above, which is shorthand for .attr('value') .

One option is to use special selectors, eg :first and :last :

var price = $(this).siblings("input[type='hidden']:first").attr("value");
var name = $(this).siblings("input[type='hidden']:last").attr("value");

However, you always can set a class name to the elements:

<input type="hidden" class="price" value="30">
<input type="hidden" class="name" value="The walking dead">

var price = $(this).siblings(".price").attr("value");
var name = $(this).siblings(".name").attr("value");

I would add an class name to your hidden inputs (price, name). This way the html source code is more readable and also the js code will be more readable.

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