Dan382
Dan382

Reputation: 986

Using jQuery to alter form value

I'm wanting to find each instance of ".simple-product-tile" on a page, then for each append part of the href (the product code at the end of the url) to the nearest forms value which is blank by default.

HTML:

<div class="simple-product-tile">

    <!-- I need the product code at the end of the href 'demo2xx' -->
    <a href="/demo-product-demo2xx"></a>
    <form action="/basket/addproduct" id="product-form" method="post">
        <div class="tbx tbx-quantity">

            <!-- Append above product code to the empty value -->
            <input id="productId" name="productId" value="" type="hidden">
        </div>
        <button class="btn-add-to-basket" title="Add to basket" type="submit">
            <span class="btn-cnt">Add to basket</span> 
        </button>
    </form>
</div>

Using some very basic jQuery I can change each value to an example code '000000':

$(".simple-product-tile form input#productId").each(function() {
    $(this).val('000000');
});

How do I cut out 'demo2xx' from the closest href and turn it into a variable I can apply to the nearest value?

I assumed I could use .slice() to cut out the required string from href, but as the product codes are different lengths I no longer think this will work.

Upvotes: 1

Views: 46

Answers (1)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

You can do like this:

$(".simple-product-tile").each(function() {
    var url = $(this).find("a").attr("href");  // Taking HREF value.
    var lastItem = url.split("-").pop(-1);    // Taking last part of the string.
    $(this).find("#productId:first").val(lastItem);  // Assigning value to input.
});

Here I would advice to keep productId unique to the page. Because ID should be unique on a DOM. I would suggest to make it class="productId". And change the jquery selector accordingly .productId instead of #productId.

Upvotes: 1

Related Questions