LoginSignup
2
2

More than 5 years have passed since last update.

動的に作成したcheckboxをクリックするとリンクを飛ばす

Last updated at Posted at 2015-12-12

手始めにHTMLにチェックボックスを配置してリンクを飛ばす

<input type='checkbox' class='chk'>
<input type='checkbox' class='chk'>
$(function() {
    $('.chk').change(function() {
        location.href = "http://qiita.com";
    });
});

内容的には,chkクラスがクリックされたらQiitaに飛ぶというものです
例のように複数あっても問題無いです.

PHPで動的に作って属性からリンクを取ってリンクを飛ばす

フォーム側

<?php
for ($i = 0 ; $i < 3 ; $i++) {
    echo "<input type='checkbox' class='chk' data-id='" . $i . "'>";
}
?>

表示されるもの



HTMLソース

<input type='checkbox' class='chk' data-id='0'>
<input type='checkbox' class='chk' data-id='1'>
<input type='checkbox' class='chk' data-id='2'>

data-idになっているものがデータベースに格納されているIDを想定

$(function() {
    $('.chk').change(function() {
        link = $(this).attr('data-id');
        location.href = "search.php?id=" + link;
    )};
)};

チェックボックスが押されたら検知をして,$(this)に押されたチェックボックスをものとして持っているのでdata-idの要素を引っ張ってくる

受け取り側

<?php
$id = $_GET['id'];
?>

URLのパラメータ名はGETメソッドなのでできる技ですね

2
2
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
2
2