Search code examples
htmlcsswordpressgravity-forms-plugin

Change background-image on radio button checked


I am currently creating a form in Wordpress using gravity forms and an image plugin, that allows me to insert images instead of radio buttons. However, I would like the image to change when the radio button is checked. My issue is that I have no idea how to approach this, and how can I target the background-image when it is directly styled in the HTML?

   <div class='ginput_container ginput_container_radio'>
    <ul class='gfield_radio' id='input_1_2'>
     <li class='gchoice_1_2_0'><input name='input_2' type='radio' value='' id='choice_1_2_0' tabindex='1' /><label for='choice_1_2_0' id='label_1_2_0'><span class="image-choices-choice-image-wrap" style="background-image:url(http://image1.com)"><img src="http://image1.com" alt="" class="image-choices-choice-image" /></span><span class="image-choices-choice-text"></span></label></li>
     <li class='gchoice_1_2_1'><input name='input_2' type='radio' value='' id='choice_1_2_1' tabindex='2' /><label for='choice_1_2_1' id='label_1_2_1'><span class="image-choices-choice-image-wrap" style="background-image:url(http://image2.com)"><img src="http://image2.com" alt="" class="image-choices-choice-image" /></span><span class="image-choices-choice-text"></span></label></li>
     <li class='gchoice_1_2_2'><input name='input_2' type='radio' value='' id='choice_1_2_2' tabindex='3' /><label for='choice_1_2_2' id='label_1_2_2'><span class="image-choices-choice-image-wrap" style="background-image:url(http://image3.com)"><img src="http://image3.com" alt="" class="image-choices-choice-image" /></span><span class="image-choices-choice-text"></span></label></li>
    </ul>
   </div>

I would highly appreciate any help I can get to solve this issue.

Let me know if you need further information, thanks


Solution

  • You could be more specific on which image you want to change and from which radio button do you want to trigger the event. But still I'll give it a shot.

    <input name='input_2' type='radio' value='' id='choice_1_2_0' tabindex='1' />
    
    <div class="image-choices-choice-image-wrap" style="background-image:url(https://cdn.kimkim.com/files/a/content_articles/featured_photos/d1ea2d6f6d1aa470f661fa661bd0e2fb14fd2d2c/medium-886981758498052b0532dc3a96b98adf.jpg);height:200px;width:400px">
    

    <script>
    $('#choice_1_2_0').click(function(){
            // If radiobuton is checked
      if ($(this).is(':checked'))
      {
        // Change background image
        $('.image-choices-choice-image-wrap').css("background-image", "url(https://cdn.kimkim.com/files/a/content_articles/featured_photos/7a4f69e48562c9adbee4f090033454a8ab23c135/medium-e5cbb5b7a25c93f53245e256729efff8.jpg)");
      }
      });
    </script>
    

    Don't forget to add jQuery if you already haven't

    Live Demo: https://jsfiddle.net/jvh6xvzs/12/