Search code examples
javascripthtmljspcheckboxhref

Sending checkbox data through <a href>


I need to send checkbox values (in a number from 1 to N checkboxes) through an <a href></a>.

I was thinking about using javascript for that, but I don't know if it is possible to use the checkbox values in a context external from <form></form>.

Any suggestions?

EDIT-1: i want to get the checkbox values and then navigate to a URL with those values as GET parameters, i.e. index.php?c1=1&c2=0&c3=0


Solution

  • Don't do it the hard way. Just put them in a GET form the usual way and submit the form on click of the link.

    <form name="myform" action="index.php">
        <input type="checkbox" name="c1" value="1" />
        <input type="checkbox" name="c2" value="1" />
        <input type="checkbox" name="c3" value="1" />
        <input type="checkbox" name="c4" value="1" />
        <input type="checkbox" name="c5" value="1" />
        <a href="#" onclick="myform.submit(); return false;">send</a>
    </form>
    

    Alternatively, to be completely free of JS (so that it also works in screenreaders, ancient mobiles and such), use a regular submit button, but throw in some CSS to make it look like a link:

    <form action="index.php">
        <input type="checkbox" name="c1" value="1" />
        <input type="checkbox" name="c2" value="1" />
        <input type="checkbox" name="c3" value="1" />
        <input type="checkbox" name="c4" value="1" />
        <input type="checkbox" name="c5" value="1" />
        <input type="submit" value="send" class="link" />
    </form>
    

    with e.g.

    input[type=submit].link {
        background: none;
        border: none;
        color: blue;
        text-decoration: underline;
        cursor: pointer;
    }