Search code examples
javascripthtmljqueryformsradio-button

Append Link on Radio Form Options


Issue 1

I am new to jquery and front end in general. I am trying to change the value of a link based on which radio button is selected. When a user selects a radio button I want append the submit link with the value of the respective radio selection. It is imporant that the value changes in the event that the user selects another radio button in that selection.

i.e. If user clicks on option 1(value="sex=male") then I want the submit link to be

Issue 2

I know how to do this with jquery but I want to know the most optimal solution that ties back into issue 1. Once a user selects a radio button I want the 'order summary' to say the users selection.


Solution

  • The simplest way I can see is the following:

    $('input[type="radio"]').change(function () {
        var queryString = $('input[type="radio"]:checked').map(function () {
            $('#' + this.name).text(this.name + ': ' + this.value);
            return this.name + '=' + this.value;
        }).get().join('&');
        $('#link').attr('href', function () {
            return 'example.com/cart?' + queryString;
        });
    });
    

    JS Fiddle demo.

    Bear in mind I've changed the span to an a (to use the native href property), and also corrected some of the HTML errors, and reduced the unnecessary HTML (all the br elements weren't necessary, use CSS for presentation).

    References: