Search code examples
javascripthrefmulti-select

post or get multiple values with multiple links


I'm new with this so please be patient with me...

I want to be able to pass multiple variables to another page using links, for example:

<a href="value1">some text</a>,<a href="value2">some text2</a>,<a href="value3">some text3</a>,<a href="value4">some text4</a>

I want to be able to use this as "multi-selector" so that the user would be able to click (select) what ever text they want and somehow with a submit button send those selected values via post or get.

I don't want to use a menu or list as I'm trying to show text and each link holds different parts of the text, kind of parragraphs in a chapter, so the user would click a paragraph (wich is a link, or at least looks like one) and send it's value to other page, however I want multiple parragraphs so that the user would be able to select and if possible unselect paragraphs.

Hope someone would point me to the right direction if possible


Solution

  • Here's how I might go about implementing this:

    HTML:

    <a data-id="value1" href="value1">some text</a>,<a data-id="value2" href="value2">some text2</a>,<a data-id="value3" href="value3">some text3</a>,<a data-id="value4" href="value4">some text4</a>
    <input type="button" id="submit" value="submit"></input>
    

    Javascript:

    var els = document.getElementsByTagName("a");
    var sz = els.length;
    
    var o = {};
    for(var n = 0; n < sz; ++n) {
        els[n].onclick = function(e) {
            e.preventDefault();
            var s = e.currentTarget.getAttribute("data-id");
            if(o[s] !== undefined) {
                delete o[s];
            } else {
                o[s] = "";
            }
        };
    }
    document.getElementById("submit").onclick = function(e) {
        var s = "";
        for(key in o) {
            s += key + "&";
        }
        var location = s.substring(0, s.length-1);
        // redirect user using location as parameter list or send ajax request
    };
    

    (I use a map rather than an array in the above to avoid having to traverse an array on every click)

    http://jsfiddle.net/5y7wK/