Replacing checkboxes with images?

五迷三道 提交于 2019-12-25 04:35:07

问题


I am trying to replace three check boxes within an html form with three different images. The idea being that the user can select the pictures by clicking on them rather than clicking on a check box. I've been putting togther some code but can't figure out how to make all the checkboxes selectable. At the moment only the first images works when it is clicked on. Can anyone help me? I'm a real novice with javascript I'm afraid. See fiddle here

The form

<form id="form1" action="" method="GET" name="form1">
<div class="col-md-3">
             <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr"><input type="checkbox" id="imgCheck"  name="pic1" value=9></div><div class="col-md-3">
             <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr"><input type="checkbox" id="imgCheck"  name="pic2" value=12></div><div class="col-md-3">
          <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr"><input type="checkbox" id="imgCheck"  name="pic3" value=7></div>
   <input type="submit" name="submit" value="Add" />
</div>
</form>

The javascript

$('#blr').on('click', function(){
        var $$ = $(this)
        if( !$$.is('.checked')){
            $$.addClass('checked');
            $('#imgCheck').prop('checked', true);
        } else {
            $$.removeClass('checked');
            $('#imgCheck').prop('checked', false);
        }
    })

回答1:


First, as Amar said, id should be unique. Use classes for multiple elements. Also pay attention for semicolons and closing html tags.

To your question: use the function .siblings() to get the relevant checkbox element.

$('.blr').on('click', function () {
    var $$ = $(this);
    if (!$$.is('.checked')) {
        $$.addClass('checked');
        $$.siblings('input.imgCheck').prop('checked', true);
    } else {
        $$.removeClass('checked');
        $$.siblings('input.imgCheck').prop('checked', false);
    }
});

See demo here: http://jsfiddle.net/yd5oq032/1/

Good luck!




回答2:


Why use JavaScript at all? You can do this with CSS, the :checked attribute and a label element.

input[type=checkbox] {
  display: none;
}

:checked+img {
  border: 2px solid red;
}
<label>
  <input type="checkbox" name="checkbox" value="value">
  <img src="http://lorempixel.com/50/50/" alt="Check me">
</label>



回答3:


This is happening because you're using the same ID more than one. IDs should be unique. Instead of using id="blr", try using class="blr". I updated the fiddle:

http://jsfiddle.net/0rznu4ks/1/



来源:https://stackoverflow.com/questions/29615650/replacing-checkboxes-with-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!