Search code examples
jqueryajaxmagento

Selecting a radio button when clicking an image


I want to select radio button when I click on his image but it's not working. This is what I've tried:

<ul id="options-31-list" class="options-list">
    <li>
        <a class="mydata" href="" data="84">
            <img class="small-image-preview" src="value_id/84/file/o2.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="84" value="84" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a class="mydata" href="" data="85">
            <img class="small-image-preview" src="value_id/85/file/vodafone.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="85" value="85" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a class="mydata" href="" data="86">
            <img class="small-image-preview" src="value_id/86/file/t-mobile.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="86" value="86" onclick="opConfig.reloadPrice();">
    </li>
</ul>

I have the same data="" attribute for both: for image and for input, is there any way to make the input (that radio) to be checked when I click on image?

Thank you

UPDATE: I found some code that work, but only for three clicks on image, so when click to the last one the script is stop, can't select the first or second again, I don't know why... I think must to uncheck all radio buttons and than check the one selected ... can someone help me with this?

jQuery(".mydata").click(function(){ 
jQuery(this).parent().children("input").attr('checked','true');              
})

Solution

  • This jquery code can help you:

    $("a").click(function() {
        $(this).next().prop("checked", true);
    });
    

    Demo: http://jsfiddle.net/k5rkxkos/

    Update

    In pure Javascript (because you said that you are not expert in jquery ;) ), you can do:

    var a = document.getElementsByTagName("a");
    for ( var i = 0; i < a.length; i++ ) {
        a[i].onclick = function() {
            var id = this.getAttribute("data-id");
            document.getElementById(id).checked = true;
        }
    }
    

    Demo: http://jsfiddle.net/k5rkxkos/1/

    Update

    This is the updated code according to your change:

    var a = document.getElementsByTagName("a");
    for ( var i = 0; i < a.length; i++ ) {
        a[i].onclick = function(e) {
            e.preventDefault();
            var id = this.getAttribute("data");
            document.querySelector('input[data="' + id +'"]').checked = true;
        }
    }
    

    Note: You must add the input name attribute.

    Demo