tags:

views:

96

answers:

4

Hi All, I have a js code:

    window.onload = function() {
        document.getElementById("Button1").onclick = function() {
            var t1 = document.getElementById("Text1").value;
            var t2 = document.getElementById("Text2").value;

            document.URL = 'myurl?t1=' + t1 + '&t2' + t2;
         }
    }

Here i am adding t1,t2 as query param..now my question is lets say i have entered some data in Textbox1 but not in textbox2, in that case the url I am getting is 'myurl?t1=' + value of textbox1 + '&t2' + This will be blank; I want to make it dynamic, i.e.if there is not value in Textbox2 then I dont want to append queryparam t2, same goes for t1 also..isit possible?

A: 
document.URL = 'myurl?t1=' + t1 + (''!=t2 ? '&t2' + t2 : '');

simply, use (? true:false) logic construction to test if var t2 is empty or not. If it's not empty add to document.URL '&t2'+t2, otherwise pass nothing.

falkon
can u pls explain this a bit
Wondering
+1  A: 

Use if clauses.

var url = "";
if (t1)
    url += "&t1=" + escapeURIComponent(t1);
if (t2)
    url += "&t2=" + escapeURIComponent(t2);
document.URL = "myurl" + url.replace(/^&/, "?");

Or even better, don't use JavaScript at all. Just use a form with action="get". This is exactly what they're for.

Matti Virkkunen
A: 

document.URL = 'myurl?t1=' + t1 + (t2?'&t2' + t2:'');

Michael
A: 

I personally use this function for creating queries:

function CreateQuery(URL, D) {
    // Returns a URL in format "URL?Key1=Value1&Key2=Value2"
    var L = [];
    for (var k in D) {
        if (!D.hasOwnProperty(k)) continue;
        var eK = encodeURIComponent(k);
        var eV = encodeURIComponent(D[Key]);
        L.push(eK+'='+eV);
    }
    if (L.length)
        return URL+'?'+L.join('&');
    return URL;
}

To use it, you might go e.g:

var q = {};
if (t1) q['t1'] = t1;
if (t2) q['t2'] = t2;
window.location = CreateQuery('myurl', a);

(Or use a <form>, which is probably still the better option as another user has suggested :-)

David Morrissey