0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

readonlyのセレクトボックスを値変更不可にするjavascript

Last updated at Posted at 2021-06-08

概要

htmlのselectタグにreadonly属性をつけても、見た目それっぽくなるだけで変更できてしまう。
それを解決する方法の1つである「選択中以外の選択肢をすべてdisabledにする」の汎用コード。

本題

jQuery版

$(function(){
  $("form select[readonly] > option:not(:selected)").attr('disabled', 'disabled');
})

素のjs版

@sgn9 さんにコメントで頂きましたので並べておきます

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('select[readonly] option')
    .forEach(e => e.disabled = !e.selected);
});

ポエムな背景

そこそこ汎用的だと思うのだけどそのへんに転がってると思ったら見当たらなくて久しぶりにセレクタ調べました

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?