What is the best way to manage Querystring in JavaScript?

I'm working with a JavaScript code snippet:

    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;
         }
    }

In this code, I am adding t1 and t2 as query parameters. My question is, if I enter data in Textbox1 but not in Textbox2, the URL generated will be

'myurl?t1=' + value of textbox1 + '&t2' + This will be blank;
I want to make this dynamic - meaning if there is no value in Textbox2, I do not want to append the query parameter t2, same goes for t1. Is it possible?

Answer №1

Implement conditions with if statements.

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

Alternatively, it's advisable to avoid using JavaScript altogether and utilize a form with action="get". This is the primary purpose of forms.

Answer №2

document.URL = 'updatedURL?param1=' + param1 + (''!=param2 ? '&param2=' + param2 : '');

Essentially, utilize the (? true:false) logic structure to determine if variable param2 is empty or not. If it's not empty, append '&param2='+param2 to document.URL, otherwise add nothing.

Answer №3

Setting the document's URL to include parameters t1 and, optionally, t2 if it exists.

Answer №4

Personally, I find this function extremely useful for generating queries:

function GenerateQuery(URL, Data) {
    // Formats URL as "URL?Key1=Value1&Key2=Value2"
    var List = [];
    for (var key in Data) {
        if (!Data.hasOwnProperty(key)) continue;
        var encodedKey = encodeURIComponent(key);
        var encodedValue = encodeURIComponent(Data[Key]);
        List.push(encodedKey+'='+encodedValue);
    }
    if (List.length)
        return URL+'?'+List.join('&');
    return URL;
}

To utilize it, you could do something like this:

var query = {};
if (term1) query['term1'] = term1;
if (term2) query['term2'] = term2;
window.location = GenerateQuery('myurl', query);

(Alternatively, consider using a <form> as suggested by another user :-)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for displaying a sub-menu upon hovering

I am attempting to display the list of sub-menu items when hovering over the main menu item. I have tried using the following CSS code, but it did not work as expected. Any assistance will be greatly appreciated. CSS: summary.header__menu-item.list-menu__ ...

Executing JavaScript in Selenium is a common task that can be accomplished by

Attempting to automate a process using Python and Selenium has been successful for me on various websites in the past. However, I am currently facing a challenge with executing JavaScript on a specific site despite finding tutorials online. https://i.ssta ...

Maintaining Image Aspect Ratio with CSS Max-width Property

I'm currently facing an issue where I am using max-width to resize images, but they are not scaling proportionally. Is there a way to achieve this with JavaScript/jQuery? Additionally, is it possible to do this without initially knowing the image&apos ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

I am experiencing an issue where the custom form validation directive in AngularJS is not functioning properly within my modal

To enhance the validation of my input boxes, I created a custom directive called nx-validate. This directive is designed to be added to a bootstrap div.form-group, which will then check if the <input/> field is $dirty or $invalid, and apply the appro ...

When using Owl Carousel in Chrome, the carousel unexpectedly stops after switching tabs

Hi there, I'm currently testing out the auto play feature in owl carousel. One issue I've encountered is that when I switch to another tab in Chrome and then return to my webpage with the carousel, it stops functioning unless I manually drag the ...

The Vue.js component is only refreshing after I manually refresh the browser page

As a newcomer to Vue.js and other reactive frameworks, I am still learning the ropes. I have a component that needs to update whenever there is a change. The goal is to display a balance from a specific login. <li :key="balance">Balance {{ balance ...

Retrieve the minimum and maximum values from a multi-dimensional array

If my array consists of the following subarrays: array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] I am looking to determine the maximum and minimum values in this array. For example, in this case: max = 33, min = 0 While I have come across exampl ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...

I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data. state: { DailyCycleDate: [] }, getters: { DailyCycleDate : state => { console.log('Getter') console.log('Length of Array: &apo ...

Having issues with AJAX and .change() function not functioning correctly?

I am working on two drop-down menus. The first menu displays the provinces in the country, and when a province is selected, the second menu should show the districts within that province. The following code is for displaying the provinces: $(document).re ...

Is it recommended to run JavaScript functions obtained from REST APIs?

Our single page application is built on Angular 4 and we are able to change input fields based on customer requirements. All the business rules for adjusting these fields are coded in JavaScript, which runs on the Java Platform and delivers the output thro ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...

What distinguishes using String.split(" ") from String.split(/ +/g)?

"cats and dogs".split(" ") => ["cats", "dogs"] "cats and dogs".split(/ +/g) => ["cats", "dogs"] Is there any distinction between these two methods? ...

What is the best way to incorporate a set of buttons and dynamically update them by using next and previous buttons?

Currently, I have code for two sets of buttons. How can we add functionality for next and previous buttons? <div id="chart-section-wrapper" class="container"> <div id="chart-section"> <div class=& ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Place a check mark in the corner of the button

I am looking to add a checkmark on my button in the right corner. I have set the input value and it displays a button with a check mark, but I want it to be positioned in the right corner. .buttoner{ background-color: #4CAF50; b ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

Issue encountered when integrating JavaScript into Django view form update

I have successfully implemented a Django view to add an invoice to my application, complete with added JavaScript functionality that is functioning properly. <p> <label for="id_total_without_vat">Price</label> <input ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...