ラジオボタンでグラフィカルなトグルボタンを作ってみる
この記事は賞味期限切れです。(更新から1年が経過しています)
HTMLでトグルボタンを実装するにはinput[type=radio]が近道ですが、 リッチな雰囲気にする為に見た目を制御したい。今回はそんなお話です。

ラジオボタンでグラフィカルなトグルボタン
「ラジオボタンがすでにグラフィカルでは?」という細かいつっこみは置いといて頂き、 本稿ではより自由度高く外見をカスタマイズする方法を記していきます。
ラジオボタンでなくともトグルボタンはJavaScriptで作れますが、 択一で選択する仕組みをわざわざ自前で実装するよりも、 その為に作られた物をその為に使って実現してみます。
マークアップ
例えばこんなHTMLとCSSを書きます。 血液型を選択する簡単なトグルボタンです。

HTML
<form class="question">
<h1>あなたの血液型は?</h1>
<ul class="bloodtype-list">
<li><label><input type="radio" name="bloodtype" value="A" checked />A</label></li>
<li><label><input type="radio" name="bloodtype" value="B" />B</label></li>
<li><label><input type="radio" name="bloodtype" value="O" />O</label></li>
<li><label><input type="radio" name="bloodtype" value="AB" />AB</label></li>
</ul>
</form>
Code language: HTML, XML (xml)
CSS
/**
* 重要な箇所のみ抜粋
*/
.bloodtype-list label input {
display:none;
}
.bloodtype-list label {
/* 非選択時のスタイル */
}
.bloodtype-list label.selected {
/* 選択時のスタイル */
}
Code language: CSS (css)
label>input という構造にして、inputをdisplay:none;で隠してしまいます。 選択されたラジオボタンのlabelに「selected」クラスが付加されれば、選択状態を表現できまね。 その部分は、JavaScriptにお任せします。
JavaScript
jQueryを使います。非常に単純な処理です。
var radios = $("input[name=bloodtype]");
radios.on("change", function(e){
// 一旦全てのlabel要素からselectedクラスを除去
radios.closest("label").removeClass("selected");
// 選択されたラジオボタンの親のlabelにselectedクラスを設定
$(e.target).closest("label").addClass("selected");
// 選択変更時に何かしたければここで
console.log("Changed to " + e.target.value);
});
// 選択状態を初期化する
radios.filter(":checked").trigger("change");
Code language: JavaScript (javascript)
これで概ね動くのですが、IE8以下はもう一工夫必要です。
旧IE対策
IE8以下は、非表示にしているラジオボタンのlabel要素をクリックしても 選択状態は変わらず、changeイベントも発火しない様子です。
なので、その挙動を簡単にエミュレートしてあげます。
radios.closest("label").on("click", function(e){
var input = $(this).find("input");
if(! input.prop("checked")){
input.prop("checked", true).trigger("change");
}
});
Code language: JavaScript (javascript)
親のlabel要素をクリックした時に、子のinput要素が選択されていなければ、 checkedにしてchangeイベントに着火します。
jQueryプラグインにまとめてみる
一連の動作をプラグインにまとめてみました。
$.fn.extend({
toggleButtons : function(callback){
var radios = this;
radios.on("change", function(e){
radios.closest("label").removeClass("selected");
$(e.target).closest("label").addClass("selected");
callback.call(this, e);
});
radios.closest("label").on("click", function(e){
var input = $(this).find("input");
if(! input.prop("checked")){
input.prop("checked", true).trigger("change");
}
});
radios.filter(":checked").trigger("change");
}
});
Code language: JavaScript (javascript)
使い方
引数のcallbackは、選択状態が変更された時にコールされます。
$("input[name=bloodtype]").toggleButtons(function(e){
// 選択変更時に何かする
console.log("Changed to " + e.target.value);
});
Code language: JavaScript (javascript)
デモ
JSBinにデモを用意しました。
まとめ
あとはlabelとlabel.selectedの見た目を存分にデザインしてあげましょう。 CSS3で記述するもよし、画像置換するもよし、子にimgを入れて差し替えてもよし。 お好みのコースで心ゆくまでごゆっくりと。
- 2013/06/22
- checkedにあわせて選択するようにコードを調整
コメント
which I am reading at this place.
Je viens de trouver un article avec les dernieres infos sur le jeu Plinko en France.
Si tu t'interesses a Plinko, cette lecture est faite pour toi.
Decouvre tout cela via le lien ci-dessous :
<a href="https://9mail.new2new.com/?p=350" rel="nofollow ugc">https://9mail.new2new.com/?p=350</a>
Amuse-toi avec les infos !
Do you ever run into any internet browser compatibility issues?
A small number of my blog audience have complained about my blog not
operating correctly in Explorer but looks great in Opera. Do
you have any tips to help fix this problem?
and truly excellent data in favor of visitors.
yet I never found any interesting article like yours. It's pretty worth
enough for me. Personally, if all website owners and bloggers
made good content as you did, the net will be a lot more
useful than ever before.
bookmarking for revisiting. I wonder how a lot attempt you set to
make this kind of wonderful informative web site.
from youtube.
topic. You understand a whole lot its almost tough to argue with you (not that I personally will need to…HaHa).
You definitely put a new spin on a subject which has been written about for ages.
Excellent stuff, just excellent!
It was inspiring. Keep on posting!
Does building a well-established website like yours require a large amount of work?
I'm completely new to blogging however I do write in my diary everyday.
I'd like to start a blog so I can share my personal experience and thoughts
online. Please let me know if you have any kind of suggestions or
tips for new aspiring bloggers. Thankyou!
You obviously know what youre talking about, why throw away your
intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?
What host are you using? Can I get your associate hyperlink to your host?
I desire my site loaded up as quickly as yours lol
post's to be exactly what I'm looking for. Does one offer guest writers
to write content for you personally? I wouldn't mind composing a post or elaborating on a lot of
the subjects you write about here. Again, awesome weblog!
오늘은 제대로 리프레시할 수 있는 부산토닥이에 대해서 알려드리려고 합니다.
일단 여성만 이용하실 수 있는 서비스이고 24시간 이내에 언제든지
가능합니다.
Usually I don't read post on blogs, but I would like to say that this write-up very compelled me to try and do
so! Your writing taste has been amazed me. Thank you, quite nice post.
as no one else recognise such targeted about my difficulty.
You're wonderful! Thanks!
net, but I know I am getting experience all the time by
reading such pleasant posts.
site regularly, this website is really good and the users are really sharing fastidious
thoughts.
browser compatibility problems. When I take a look at your
website in Safari, it looks fine however, when opening in IE, it
has some overlapping issues. I merely wanted to give you a
quick heads up! Aside from that, wonderful website!
attention. I'll probably be returning to see
more, thanks for the information!
and was curious what all is required to get setup? I'm assuming having a blog like yours
would cost a pretty penny? I'm not very web
savvy so I'm not 100% certain. Any recommendations or advice would be greatly appreciated.
Appreciate it
Your writing style is awesome, keep doing what you're doing!
web page, as here every data is quality based material.
Does managing a well-established website like yours require a large amount of work?
I am completely new to running a blog however I do write in my diary daily.
I'd like to start a blog so I will be able to
share my personal experience and views online. Please let
me know if you have any kind of suggestions or tips
for new aspiring blog owners. Appreciate it!
Glance complex to more brought agreeable from you! However, how could we communicate?
Amazing .. I will bookmark your web site and take
the feeds additionally? I am satisfied to seek out numerous useful info here within the put up, we
need develop extra techniques in this regard, thanks for sharing.
. . . . .
I surprise how a lot effort you set to create one of these excellent informative site.
(from what I've read) Is that what you're using on your
blog?
create this website yourself or did you hire someone to do it for you?
Plz answer back as I'm looking to design my own blog and would like
to know where u got this from. thank you
stuff previous to and you're just extremely fantastic.
I really like what you have acquired here, really like what you're stating and the way in which you say it.
You make it enjoyable and you still take care of to keep it wise.
I can not wait to read much more from you. This is really a
great website.
Whenever I look at your site in Safari, it looks fine but
when opening in Internet Explorer, it's got some overlapping issues.
I simply wanted to provide you with a quick heads up!
Other than that, fantastic blog!
blog. Is it very hard to set up your own blog?
I'm not very techincal but I can figure things out pretty quick.
I'm thinking about setting up my own but I'm not sure where to start.
Do you have any points or suggestions? Many thanks
fine material for readers.
Perjanjian strategis RI–UE ini berpengaruh juga ke dunia
online, termasuk pelaku usaha seperti situs judi bola online yang terus berkembang.
Saya pribadi tertarik dengan ekonomi digital, terutama dalam bidang situs judi bola parlay.
Semoga banyak sektor ikut tumbuh dengan adanya perjanjian ini,
termasuk dalam hal kemudahan ekspor digital.
Oh ya, buat yang cari situs judi bola resmi dan terpercaya bisa gabung ke komunitas
diskusi. Mantap banget kontennya!.
which is beneficial in support of my know-how.
thanks admin
and i could assume you are an expert on this subject.
Well with your permission let me to grab your RSS feed to keep up to date with forthcoming post.
Thanks a million and please carry on the enjoyable work.
This great article has really peaked my interest. I am going to book mark your blog and keep checking for new details about once per week.
I subscribed to your RSS feed as well.
I've got some recommendations for your blog you might be interested in hearing.
Either way, great website and I look forward
to seeing it improve over time.
счета.
Here is my blog post ... <a href="https://spinbetter.buzz/" rel="nofollow ugc">https://spinbetter.buzz/</a>
Also, thanks for permitting me to comment!
<a href="http://wiki.envirobatbdm.eu/Sever-bonus_6W" rel="nofollow ugc">http://wiki.envirobatbdm.eu/Sever-bonus_6W</a>
Оформление интуитивен, словно ветер судьбы направляет тебя от выбора к выбору. Транзакции, будь то пополнения или выплаты, проходят быстро, как поток воды, и это завораживает. А поддержка всегда отвечает мгновенно, как надежный товарищ, который никогда не подведёт.
Для меня <a href="https://selectorcasino.com/" / rel="nofollow ugc">Селектор</a> стал пространством, где удовольствие и смысл соединяются. Здесь каждый момент — это часть истории, которую хочется переживать снова и снова.
While playing virtual gambling games, I realized that the key to winning is smart planning.
Resources that became indispensable to me:
<a href="https://nizamevents.com/page-573/" / rel="nofollow ugc">https://nizamevents.com/page-573/</a>
These materials helped me minimize risks. They covered topics like optimal game tactics, which allowed me to avoid mistakes. If you also want to enhance your skills, I recommend exploring theoretical aspects. It’s your first step toward success.
May luck be on your side!
While playing slot machines, I realized that the foundation to winning is the right strategies.
Guides that became indispensable to me:
<a href="https://universalgoz.com/novibet-casino-246/" / rel="nofollow ugc">https://universalgoz.com/novibet-casino-246/</a>
These tips helped me play more efficiently. They covered topics like machine volatility, which allowed me to avoid mistakes. If you also want to play more mindfully, I recommend learning from other players’ experience. It’s your first step toward a winning strategy.
Wishing you success in the game!
вы найдете решение. Обращайтесь
за поддержкой!
Enquanto jogava em maquinas caca-niqueis, percebi que o chave para um jogo eficaz e fazer um planejamento inteligente.
Guias que se tornaram uteis para mim:
<a href="https://csnakliyat.com/2025/07/01/online-casino-nederland-zonder-cruks-biedt-spelers-24/" / rel="nofollow ugc">https://csnakliyat.com/2025/07/01/online-casino-nederland-zonder-cruks-biedt-spelers-24/</a>
Esses materiais me ajudaram a minimizar os riscos. Eles abordaram topicos como volatilidade das maquinas, o que me permitiu entender como o sistema funciona. Se voce tambem quer aprimorar suas habilidades, recomendo explorar os aspectos teoricos. Esse e o seu momento chave rumo a um estrategia vencedora.
Jogue com inteligencia e aproveite o processo!
Feel free to surf to my web-site - <a href="https://uztm-ural.ru/catalog/poroshki-metallov/" rel="nofollow ugc">https://uztm-ural.ru/catalog/poroshki-metallov/</a>
Enquanto jogava em cassinos online, percebi que o fundamento para um desempenho bem-sucedido e ter as estrategias certas.
Artigos que se tornaram uteis para mim:
<a href="http://kobayashitoyoko.com/32920/" / rel="nofollow ugc">http://kobayashitoyoko.com/32920/</a>
Esses analises me ajudaram a melhorar minhas chances. Eles abordaram topicos como RTP das slots, o que me permitiu jogar com mais confianca. Se voce tambem quer jogar com mais consciencia, recomendo estudar os conselhos de especialistas. Esse e o seu ponto de partida rumo a um estrategia vencedora.
Desejo sucesso no jogo!
## A Brief History of Harvard University
Founded in 1636, **Harvard University** is the oldest and one of the most
prestigious higher education institutions in the United States.
Located in Cambridge, Massachusetts, Harvard has built a global reputation for academic excellence, groundbreaking research,
and influential alumni. From its humble beginnings as a small college
established to educate clergy, it has evolved into a world-leading
university that shapes the future across various disciplines.
## Harvard’s Impact on Education and Research
Harvard is synonymous with **innovation and intellectual leadership**.
The university boasts:
- **12 degree-granting schools**, including the renowned **Harvard Business School**, **Harvard Law School**,
and **Harvard Medical School**.
- **A faculty of world-class scholars**, many of whom are Nobel laureates,
Pulitzer Prize winners, and pioneers in their fields.
- **Cutting-edge research**, with Harvard leading initiatives in artificial intelligence, public health,
climate change, and more.
Harvard’s contribution to research is immense, with billions
of dollars allocated to scientific discoveries and technological advancements each
year.
## Notable Alumni: The Leaders of Today and Tomorrow
Harvard has produced some of the **most influential figures** in history, spanning politics, business, entertainment,
and science. Among them are:
- **Barack Obama & John F. Kennedy** – Former U.S.
Presidents
- **Mark Zuckerberg & Bill Gates** – Tech visionaries (though Gates did not
graduate)
- **Natalie Portman & Matt Damon** – Hollywood icons
- **Malala Yousafzai** – Nobel Prize-winning activist
The university continues to cultivate future leaders who shape industries and drive global progress.
## Harvard’s Stunning Campus and Iconic Library
Harvard’s campus is a blend of **historical charm and modern innovation**.
With over **200 buildings**, it features:
- The **Harvard Yard**, home to the iconic **John Harvard Statue** (and the famous “three lies” legend).
- The **Widener Library**, one of the largest university libraries in the
world, housing **over 20 million volumes**.
- State-of-the-art research centers, museums, and performing arts venues.
## Harvard Traditions and Student Life
Harvard offers a **rich student experience**, blending academics
with vibrant traditions, including:
- **Housing system:** Students live in one of 12 residential houses, fostering a
strong sense of community.
- **Annual Primal Scream:** A unique tradition where students
de-stress by running through Harvard Yard before finals!
- **The Harvard-Yale Game:** A historic football rivalry that unites alumni and students.
With over **450 student organizations**, Harvard students engage in a diverse range of extracurricular activities, from entrepreneurship to performing arts.
## Harvard’s Global Influence
Beyond academics, Harvard drives change in **global policy, economics, and technology**.
The university’s research impacts healthcare,
sustainability, and artificial intelligence, with partnerships across industries worldwide.
**Harvard’s endowment**, the largest of any university, allows it to fund
scholarships, research, and public initiatives, ensuring a legacy of impact for generations.
## Conclusion
Harvard University is more than just a school—it’s a **symbol of excellence, innovation, and leadership**.
Its **centuries-old traditions, groundbreaking discoveries,
and transformative education** make it one of the most influential institutions in the world.
Whether through its distinguished alumni,
pioneering research, or vibrant student life, Harvard continues to shape the future
in profound ways.
Would you like to join the ranks of Harvard’s legendary scholars?
The journey starts with a dream—and an application!
<a href="https://www.harvard.edu/" rel="nofollow ugc">https://www.harvard.edu/</a>
非常に助かります。radios.filter(":checked")とするのですね、勉強不足でした。コメントしてよかったです。</p>
非常に助かります。radios.filter(":checked")とするのですね、勉強不足でした。コメントしてよかったです。</p>
例えば、デフォルトで「O型」を選択状態にするには、どのようにすればよろしいでしょうか?
回答のほど、よろしくお願い致します。</p>
例えば、デフォルトで「O型」を選択状態にするには、どのようにすればよろしいでしょうか?
回答のほど、よろしくお願い致します。</p>
デフォルトで「checked」されていない状態にしたいのですが、
javaの勉強不足のため分かりません…。。申し訳ないです。。
早めにご回答頂けるとありがたいです。
宜しくお願い致します。</p>