Med
Med

Reputation: 117

change value to input repeated many time with the same class (jQuery)

I have two "li" with the same class "product cg-product-wrap" each of them contains an input "variation_id". I want when i click on< span class="link"> of the "li" change the content of their input and not all input using jQuery.

here is the HTML code

    <li class="product">
    <div class="cg-product-wrapper">
        <a href="#"><span class="link">objet1</span></a>
        <form class="cart variation_color_shop" method="post" enctype="multipart/form-data">
            <input type="hidden" name="variation_id" class="variation_id" value="1">
            <button type="submit" class="single_add_to_cart_button btn_acheter">
                Acheter
            </button>
        </form>
    </div>
</li>
<li class="product">
    <div class="cg-product-wrapper">
        <a href="#"><span class="link">objet2</span></a>
        <form class="cart variation_color_shop" method="post" enctype="multipart/form-data">
            <input type="hidden" name="variation_id" class="variation_id" value="2">
            <button type="submit" class="single_add_to_cart_button btn_acheter">
                Acheter
            </button>
        </form>
    </div>
</li>

and here is the jQuery code

(function($) {
    $(document).on('click', '.link', function(e) {

        $('.variation_color_shop').find('input[name="variation_id"], input.variation_id').val('newval').change();
    });

})(jQuery); 

Is there any solution for that?

Upvotes: 0

Views: 1441

Answers (1)

L. Monty
L. Monty

Reputation: 882

Use $(this) to encounter the context and find the right input like

(function($) {
    $(document).on('click', '.product', function(e) {
       $(this).find('.variation_color_shop input[name="variation_id"], .variation_color_shop input.variation_id').val('newval').change();
    });

})(jQuery); 

where $(this) represents the clicked li

EDIT

Follwing code applies to you the changed structure in your question

 (function($) {
        $(document).on('click', 'span.link', function() {
           $(this).parents('li.product:first').find('.variation_color_shop input[name="variation_id"], .variation_color_shop input.variation_id').val('newval').change();
        });

    })(jQuery); 

This time you are getting by $(this) the clicked span (with class 'link'). Via jQuerys parents-function you can navigate to ancestors (in your case the li) and then find inside of it what you are searching for.

Often it is usefull to combine the parents-function with the :first-selector to reduce runtime and ensure you don't get ancestors which you were not aware of.

Upvotes: 2

Related Questions