Rich
Rich

Reputation: 103

jQuery on change of radio button update previous input value

I have multiple products on a page that contains a form with product info.

The default value of the product input is the name of the product, with the default - CD appended at the end. If a user selects 'Digital Download' I need to update the value of the product and swap '- CD' to '- Digital'.

I've made a rough jsfiddle with a slight variation to show the hidden inputs. You'll notice both inputs are changing when it should only be the input inside the product being selected.

http://jsfiddle.net/4ffh9bss/

cheers!

<div class="product">
    <form action="" method="post">
        <input class="product-input" name="product" type="hidden" value="Cool music vol 1 - CD" />
        <label>Select format</label> 
        <input type="radio" name="type" value="CD" checked="checked">CD 
        <input type="radio" name="type" value="Digital">Digital Download<br/>
        <input type="submit" class="product-buy" value="Buy now!" />
    </form>
</div>

<div class="product">
    <form action="" method="post">
        <input class="product-input" name="product" type="hidden" value="Cool music vol 2 - CD" />
        <label>Select format</label> 
        <input type="radio" name="type" value="CD" checked="checked">CD 
        <input type="radio" name="type" value="Digital">Digital Download<br/>
        <input type="submit" class="product-buy" value="Buy now!" />
    </form>
</div>


$(".product").each(function() {
    $('input:radio').bind("change",updateFormat);

        function updateFormat(e){
            e.preventDefault();                     
            var $productValue = $('.product-input').val();
            var $productValueSplit = $productValue.split('-')[0];
            var $radioValue = $("form input[type='radio']:checked").val();

            console.log($productValueSplit + ' - ' + $radioValue);
        }
});

Upvotes: 0

Views: 372

Answers (1)

Verhaeren
Verhaeren

Reputation: 1661

I don't like much the way you structure your HTML. It makes me do something funky to get what you want, but that's up to you. I'm able to achieve what you want with this code:

$('input:radio').each(function(){
    $(this).on("click", function(){
        var ind = $(this).closest(".product").index();
        var $productValue = $('.product-input').eq(ind).val();
        var $productValueSplit = $productValue.split('-')[0];
        var $radioValue = $("form").eq(ind).find('input:checked').val();
        $('.product-input').eq(ind).val($productValueSplit + ' - ' + $radioValue);
    });
});

FIDDLE: http://jsfiddle.net/4ffh9bss/4/

Upvotes: 1

Related Questions