What is the best way to create a function that will initiate the download of a particular file based on a specific key provided by the

I need assistance in creating a function for my text box and button setup. Can someone please guide me on how to achieve this?

The user will be provided with a specific alphanumeric key from the website. They must input this key into the text box and then click on the button to access and download a specific file associated with that key. If the entered key matches the one assigned to a file, that file will be downloaded. While there are other files available, only the one paired with the correct key will be downloaded. Any help would be appreciated...

Here is my code:

<center>
        <input class="keyBox" type="text" placeholder="Enter your download key">
        <br><br>
        <div class="text-center">
            <button type="submit" class="btn btn-style btn-primary">Download</button>
        </div>
        </button>
  </center>

Answer №1

Assuming you have a server with an API endpoint that requires the key as a query parameter, this code should work for your needs. Make sure to adjust the URL as necessary for your specific requirements.

<!-- Insert this code after the HTML in your original post -->
<script>
    function onClick(event) {
        // Be sure to change the button's type to "button".
        // This will eliminate the need for this line.
        event.preventDefault()

        const inputElement = document.querySelector('input')
        const filename = inputElement.value

        location.href = `/path/to/${filename}`
    }

    const button = document.querySelector('button')

    button.addEventListener('click', onClick)
</script>

If the API endpoint sends the correct Content-Disposition headers, the browser will attempt to download the file rather than navigating to the URL.

For more precise element selection, consider using id attributes to avoid any confusion with document.querySelector. You can then utilize document.getElementById instead.

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

Can the root directory of a node module be customized or specified?

When publishing a node module with source files in a src directory, users typically need to specify the full path from the module when importing a file into their project. For example: Directory Structure: my-module --src ----index.js ----something-else ...

Update the content of a div twice simultaneously

My AJAX call is currently working fine, but the response time is slow. To prevent users from clicking multiple times while waiting for a response, I want to display a message like "Converting please wait" before the data is received. Below is the code that ...

Place the information within a div container

If I already have something like <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> <div class="key-element"></div> & ...

Expanding and collapsing DIV elements using JavaScript upon clicking navigation menu items

At present, the current code unfolds the DIVs whenever a user clicks on a menu item. This results in the DIV folding and unfolding the same number of times if clicked repeatedly on the same link, without staying closed. My desired functionality is to have ...

Using Jquery for a synchronous "Ajax" request doesn't seem to be functioning

As a newcomer to javascript, I am currently in the process of developing a react/flux app and utilizing jquery for synchronous "ajax" calls (sjax?) to the backend. However, I am encountering inconsistent behavior which seems to be caused by my ajax call no ...

When running the `vue-cli-service test:unit` command, an error involving an "Unexpected token" message related to the usage of the spread operator

Within my code, I am utilizing the destructuring operator. However, during the module build phase, I encountered an "Unexpected token" error. Any suggestions on how to resolve this issue without completely rewriting my code to avoid using the destructuring ...

Malfunctioning string error in Django view caused by boolean inconsistencies

Looking to extract variables from a post request made by Javascript. Upon inspecting the received variables in my view, I found the following: >>> print request.body {"p":"testprd","cash":false,"cheque":true,"debit":false,"credit":true} The valu ...

Guide on ensuring Bootstrap tooltip remains visible using just JavaScript

Greetings, I recently found myself searching for ways to ensure that the tooltips on my webpage remain visible at all times. During my quest for a solution, I stumbled upon this enlightening discussion on Stack Overflow. Interestingly, all the proposed sol ...

Align images to the left in Typora for a cleaner look

Typora typically aligns all images in the center by default. https://i.stack.imgur.com/TrqIM.png In my search through the github.css, I was unable to locate any instances of img. $ grep img "/Users/me/Library/Application Support/abnerworks.Typora/themes ...

Issue 415 encountered when attempting to transmit JSON data to Spring MVC using AJAX

I am encountering an issue while trying to send a JSON object to Spring MVC. Despite my AJAX function gathering input field data from a form and attempting to send the JSON to the controller, I keep receiving a 415 error code. <script type="text/javas ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Ways to iterate through a JSON array and modify URLs

When the page loads, a single API call is made to retrieve the current status of all favorite links and display the appropriate message (e.g. click to subscribe, click to unsubscribe). Here is the finalized code! Thank you for all your assistance, please ...

When attempting to send an array value in JavaScript, it may mistakenly display as "[object Object]"

I queried the database to count the number of results and saved it as 'TotalItems'. mysql_crawl.query('SELECT COUNT(*) FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, count) { var ...

jQuery slideToggle effect causes neighboring elements to move

After clicking on the element I've set as the trigger for slideToggle, it moves a few pixels to the right without any apparent cause. It seems like there might be an issue with the CSS, but I'm having trouble pinpointing the exact problem. You c ...

sending a symfony2 form through ajax for processing

Using Symfony2, doctrine2, and twig. Attempting to submit a form using Ajax but always receiving the message: "This is not ajax!". Can't seem to find the issue. Any help would be appreciated. Twig code: <form id="form_newsletter" action="{{ path ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

Safari not updating Angular ng-style properly

I created a simple carousel using Angular and CSS animations which works well in Chrome. However, I recently tested it in Safari and noticed that the click and drag functionality does not work. I've been trying to fix this issue for days and could use ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

Is there a way to directly update the value of a nested object array using v-model in VUE?

Looking to update a value in JSON using v-model { class: "data.child", "myform.input1": [true, "<input1 value>"] } <input type="text" v-model="<what should be inserted here?>" > //update the value directly in my ...

transition from jQuery to Zepto

I have been utilizing multiple jQuery plugins in my codebase... Recently, I decided to switch over to Zepto, but encountered an issue Uncaught TypeError: Object function (a,b){return A.init(a,b)} has no method 'data' when checking the console ...