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?
-
It won't break the url if the value of one of them is empty. And change document.URL to window.location or the browser won't open that page (FF)baloo– baloo2010年06月02日 08:31:30 +00:00Commented Jun 2, 2010 at 8:31
-
yep.but its just an example, not the real application.Wondering– Wondering2010年06月02日 10:33:15 +00:00Commented Jun 2, 2010 at 10:33
4 Answers 4
Use if clauses.
var url = "";
if (t1)
url += "&t1=" + encodeURIComponent(t1);
if (t2)
url += "&t2=" + encodeURIComponent(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.
1 Comment
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.
Comments
document.URL = 'myurl?t1=' + t1 + (t2?'&t2' + t2:'');
Comments
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 :-)