Search code examples
javascriptjquerycheckboxhyperlinkgenerated

Jquery generate link from radio button with variables


Ive got an important question. I want to generate a hyper link. here is an example:

Radio group one:
[X] Black
[ ] White
Radio group two:
[ ] Black 
[X] White
[ ] Yellow
Radio group three:
[ ] Black 
[ ] White
[X] Red

This would be the result:

<a href="www.example.de/example/BLACK-SITE/WHITE-SITE/RED-SITE">My generated Link</a>

I hope you understand what I mean :) would be great to get any ideas how to fix this. Thank you kind regards, Nicole :)

Here is my Code so far:

     <script>

    $(document).ready(function(){



    $('#back1').change(function(){
        if(this.checked)
            $('#backimg1').show();
            $('#backimg2').hide();
            var back = '/schwarz-17'; 

    });

    $('#back2').change(function(){
        if(this.checked)
            $('#backimg1').hide();
            $('#backimg2').show();
            var back = '/weiss-18'; 

    });     



    $('#front1').change(function(){
        if(this.checked)
            $('#frontimg1').show();
            $('#frontimg2').hide();
            $('#frontimg3').hide();
            var back = '/teil-21'; 

    });

    $('#front2').change(function(){
        if(this.checked)
            $('#frontimg1').hide();
            $('#frontimg2').show();
            $('#frontimg3').hide();
            var back = '/halb-23'; 

    });

    $('#front3').change(function(){
        if(this.checked)
            $('#frontimg1').hide();
            $('#frontimg2').hide();
            $('#frontimg3').show();
            var back = '/ganz-26'; 
    });
});



 <a id="link" onclick="location.href=this.href+'?key='+back+front;return false;" href ="http://www.tronitechnik.de/duschen">

Solution

  • If you have 3 radio box with respectives id's : radio1, radio2, radio3 :

    $(document).ready(function(){
    
    var link1 = "default1" ;
    var link2 = "default2" ;
    var link3 = "default3"
    var baseLink = "www.example.de/example/" ;
    var finalLink ;
    
    $('#radio1').on('change', function() {
        link1 = $(this).val();
        changeLink();
    });
    
    $('#radio2').on('change', function() {
        link2 = $(this).val();
        changeLink();
    });
    
    $('#radio3').on('change', function() {
        link3 = $(this).val();
        changeLink();
    });
    
    function changeLink(){
        finalLink = baseLink + link1 + "/" + link2 + "/" + link3 ;
        $("#link").attr("href",finalLink);
    }
    
    }
    

    I advise you to verify the link before doing the $("#link").attr("href",finalLink);