clickable buttons instead of radio buttons

2019-08-20 07:27发布

问题:

I want click able buttons instead of radio buttons. I saw an example on jsfiddle but only problem is I don't have labels tags in my code. I don't have access to code, so I cant add them either. I can only add javascript and css to my CMS. Is there any way to achieve results?

<div class="button1">
    <input type="radio" checked="" value="1" name="question">question 1
</div>
<div class="button2">
    <input type="radio" value="2" name="question">question 2
</div>

I got solution here but its not working in IE.

$(function() {
    $('.container input[type="radio"]').each(function(index) {
        console.log($(this));
        $(this).attr('id', 'radio' + index);
        var label = $('<label />', {'for': 'radio' + index}).html($(this).parent().html());
        $(this).parent().empty().append(label);
    });
    $('label').click(function () {
       $('label').removeClass('selected');
       $(this).addClass('selected');
    });        
});

回答1:

To get this functionality, you have to wrap your inputs (and the description) in a label. Assuming that your radio is always in a seperate container, this is possible with this piece of code:

$('.container input[type="radio"]').each(function(index) {
    console.log($(this));
    $(this).attr('id', 'radio' + index);
    var label = $('<label />', {'for': 'radio' + index}).html($(this).parent().html());
    $(this).parent().empty().append(label);
});

working jsfiddle: http://jsfiddle.net/VyvpP/



回答2:

If, what I think you're asking is that you have a radio button in the guise of a clickable button, this should do you:

-webkit-appearance:none

http://jsfiddle.net/54ek6/

You can hide the radio button with -webkit-appearance:none; and using :before psuedo classes, add in the labels.

This does not work on IE. (Just so you know!)



回答3:

if you want something like this:

just copy and paste:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">   </script>
 <script>
$(document).ready(function(){
  $("#rad").click(function(){
    $(this).hide();
  });
});
</script>
</head>
<body>
<input type="radio" checked="" value="1" name="question" id="rad">
</body>
</html>