Search code examples
jqueryinputmootoolshiddencheckbox

Convert script from Mootools to Jquery


I have this script written in Mootools.

When any checbox is checked, then hidden input is changed. Script check every checked image, makes string from checkced images - separated by commas. I need this Mootools script convert to jQuery.

jsFiddle Mootools script

HTML :

<form>
    <div class="img_container">
        <img src="http://ynternet.sk/test/bg_1.png" style="border:2px solid gray;" /><br />
        <input type="checkbox" name="bg_1.jpg" checked="yes"  />
    </div>
    <div class="img_container">
        <img src="http://ynternet.sk/test/bg_2.png" style="border:2px solid gray;" /><br />
        <input type="checkbox" name="bg_2.jpg" checked="yes"  />
    </div>
    <div class="img_container">
        <img src="http://ynternet.sk/test/bg_3.png" style="border:2px solid gray;" /><br />
        <input type="checkbox" name="bg_3.jpg" checked="yes" />
    </div>

<input type="hidden" value="bg_1.jpg,bg_1.jpg,bg_3.jpg" name="selected_img">

Mootools

var checks = document.getElements('input[type="checkbox"]');
var hidden = document.getElements('input[type="hidden"][name="selected_img"]')[0];
checks.addEvent('change',function(e){
    var checkbox = e.target;
    var img = checkbox.getPrevious('img');
    var checked = checkbox.get('checked');
    if(checked){
      img.setStyle('border','2px solid gray');
    }
    else{
      img.setStyle('border',null);
    }

    setInputHidden();
});

function setInputHidden(){
    var inputs_checked = document.getElements('input[type="checkbox"]:checked');  
    var arr_names = inputs_checked.get('name');
    hidden.set('value',arr_names.join(','));
    alert(hidden.value);
}

Solution

  • $('input[type=checkbox]').change(function (e) {
        if ($(this).is(':checked')) {
            $(this).parent().find('img').css({
                'borderLeft': '2px solid gray',
                'borderRight': '2px solid gray',
                'borderTop': '2px solid gray',
                'borderBottom': '2px solid gray',
            });
        } else {
            $(this).parent().find('img').css({
                'borderLeft': '0',
                'borderRight': '0',
                'borderTop': '0',
                'borderBottom': '0',
            });
        }
    
        setInputHidden();
    });
    
    function setInputHidden() {
        var arr_names = new Array();
        $('input[type="checkbox"]:checked').each(function () {
            arr_names.push($(this).attr('name'));
        });
        $('input[type=hidden][name=selected_img]').val(arr_names.join(','));
        alert($('input[type=hidden][name=selected_img]').val());
    }