LoginSignup
0
0

More than 3 years have passed since last update.

JavaScript URLでパラメーターを送信、受信する

Posted at

リンクをクリックしてページ遷移先のフォームのチェックボックスにチェックを入れる方法

送信

script.js


const test01 = document.getElementById('id名'); //id名を探す。

if (test01){
  test01.addEventListener('click', function send(){ //id名をクリックした際に送る。
  const param02 = "送りたい内容";
  window.open().location.href = "〇〇.html?"+param02; 
  //「指定の〇〇.html + ? + 送りたい内容」をURLでパラメーターを送信できます。
  return false;
});

window.open() ・・・JSで別タブ開く指示
location.href ・・・現在ページURLを参照

受信

URLのパラメーターを"document.location.search"で取得できます。
ただし、URLのパスの後ろのパラメーターの文字列をまとめて取得することしかできないため、
各パラメータの値の取得は取得した文字列を解析する必要があります。

script.js


if (document.location.search) {
  const query03 = document.location.search.substring(1); 
  if (query03)
  document.getElementById(query03).checked = true;
}

substring(1)で2文字目以降の文字列を取り出しています。

今回は送りたいパラメータが1つだけであったため、param02とquery03をそのまま使えた。
複数のパラメータを送る際は処理をしなければならない。

参考サイト:
http://www.ipentec.com/document/javascript-get-parameter

0
0
0

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
0