Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

html - make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).

The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.

I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)

Any help is much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

HTML :

<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>

jQuery :

$(".chb").change(function() {
    $(".chb").prop('checked', false);
    $(this).prop('checked', true);
});

if you want user can unchecked selected item :

$(".chb").change(function() {
    $(".chb").not(this).prop('checked', false);
});

Demo :

http://jsfiddle.net/44Zfv/724/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...