ブックマークレットで始める業務改善⑫ ここまでの総復習
前回はこちら。
これまで学習したことを活用して、問題を解いてみましょう!✏️
まとめ記事:
⑦ CSSセレクターを使いこなそう
⑨ JavaScriptで要素を絞り込もう
⑩ JavaScriptで要素を操作しよう
総復習の問題
以下の「お客様問い合わせ登録フォーム」で、以下の処理を行うブックマークレットを作ってください。
「お問い合わせ日」に、今日の日付を入れる。以下のプログラムで今日の日付を取得できます。
const date = new Date().toLocaleDateString('ja-JP');「登録者」に、画面左上に表示されているユーザーIDを入力する。
「顧客エリア」は関東を選ぶ。(ほとんどの顧客は関東在住なので、デフォルトで関東を選んでおきたい、という状況を想定しています。)
「お客様番号」にフォーカスを当てて、すぐに入力を開始できるようにする。
上記4つと「問い合わせ内容」と「登録」ボタンを除いて、他の入力欄(テキスト入力、ラジオボダン、登録以外のボタン)をすべて非表示にする。(使っていない項目がやたらとたくさんある状況を想定しています。)
まとめると、以下の状態を目指します。
解答例はにんじんの下です。
解答例:
javascript:(function(){
const date = new Date().toLocaleDateString('ja-JP');
document.querySelector("#received-date").value = date;
const user_id = document.querySelector("div.header span").innerText;
document.querySelector("#registered-by").value = user_id;
document.querySelector("#kanto").checked = true;
document.querySelector("#customer-number").focus();
document.querySelector("#customer-tel").parentNode.parentNode.style.display = "none";
document.querySelector("#customer-email").parentNode.parentNode.style.display = "none";
document.querySelector("#hokkaido-hokkaido").parentNode.parentNode.style.display = "none";
document.querySelector("#category_product").parentNode.parentNode.style.display = "none";
document.querySelectorAll("textarea").forEach(function(e) {
if (e.parentNode.parentNode.innerText.trim() !== "問い合わせ内容") {
e.parentNode.parentNode.style.display = "none";
}
});
document.querySelectorAll("a.button").forEach(function(e) {
if (e.innerText.trim() !== "登録") {
e.style.display = "none";
}
});
})();
上記の回答例とまったく同じでなくても、目的が達成できていればOKです。parentNode で階層を上がってから display = "none" するのがポイントですね。相対的な位置関係をうまく使いこなせるようになると、できることが大きく広がります。
次回は作成したブックマークレットの配布方法について解説します。
次回はこちらです。
このシリーズのすべての記事は、こちらのマガジンにまとめています。
🐶スキしていただけると励みになります!
この記事が気に入ったらサポートをしてみませんか?