Redirecting JavaScript form to search engine

I am struggling with creating a form that enables a user to input text and then directs them to a specified search engine with the input as the query. I am encountering difficulties in getting the JavaScript to properly redirect.

An interesting observation is that if you change the submit input to a button, add onClick="searchForm", and manually click on it, the functionality works. However, this method eliminates the ability to simply type and press enter for searching, which I believe is essential.

If there are alternative methods of achieving this functionality, I would greatly appreciate any suggestions.

Thank you.

EDIT: I have completely revised the code based on meouw's suggestion, as it was much clearer than my initial approach. The HTML structure was jumbled up due to multiple modifications aimed at resolving the JavaScript issue. Even after organizing everything, the problem persists.

I am aware that something crucial is missing because inserting an alert('cat'); after changing the URL in the JavaScript reveals that the browser does indeed redirect for the search. However, upon clicking OK on the alert, the redirection is reversed. It is even possible to navigate back through the browser history to return to the search page.

EDIT AGAIN: Thank you, meouw. Adding 'return false' was the solution I had been overlooking. Your assistance is valued.

FINAL CODE:

<script type="text/javascript">
    function doSearch( f ) {
        var searchTerm = f.searchText.value;

        if( !searchTerm ) {
            //prompt user to enter a search string
            //cancel the request by returning false
            return false;
        }

        var sel = f.whichEngine;
        var selectedEngine = sel[sel.selectedIndex].value;
        var engineUrl;

        switch( selectedEngine ) {
        case 'google_web':
            engineUrl = 'http://www.google.com/search?q=';
            break;
        case 'bing_web':
            engineUrl = 'http://www.bing.com/search?q=';
            break;
        case 'yahoo_web':
            engineUrl = 'http://search.yahoo.com/search?p=';
            break;
        case 'google_images':
            engineUrl = 'http://www.images.google.com/images?q=';
            break;
        case 'bing_images':
            engineUrl = 'http://www.bing.com/images/search?q=';
            break;
        case 'yahoo_images':
            engineUrl = 'http://images.search.yahoo.com/search/images?p=';
            break;
        }

        engineUrl += searchTerm;
        window.location.assign(engineUrl);
        return false;
    }

</script>
<form onsubmit="return doSearch(this)">
    <fieldset>
        <legend>Search</legend>
        <ul>
            <li>
                <input type="text" name="searchText" id="searchText" size="41" maxlength="2048" />
            </li>
            <li>
                <select name="whichEngine" id="whichEngine">
                    <optgroup label="Web">
                        <option id="GoogleWeb" value="google_web" checked="checked">Google Web</option>
                        <option id="BingWeb" value="bing_web">Bing Web</option>
                        <option id="YahooWeb" value="yahoo_web">Yahoo! Web</option>
                    </optgroup>
                    <optgroup label="Images">
                        <option id="GoogleImages" value="google_images">Google Images</option>
                        <option id="BingImages" value="bing_images">Bing Images</option>
                        <option id="YahooImages" value="yahoo_images">Yahoo! Images</option>
                    </optgroup>
                </select>
                <input type="submit" value="Search">
            </li>
        </ul>
    </fieldset>
</form>

Answer №1

The primary issue lies here

window.location.assign(finalSearchString);

should be

window.location = finalSearchString;

window.location.href = finalSearchString;

Additional tips:

Your HTML structure is unconventional
Ensure you return the result of your function to the onsubmit event of the form if you wish to prevent the search from proceeding.
Avoid including labels and links in options - instead of using self-closing option tags, place the text within the option tag and assign a value that can be interpreted by your script. This approach is more secure when adding more options later on.

<form onsubmit="return doSearch(this)">
....
<optgroup label="Google">
    <option value="google_search">Google Web</option>
    <option value="google_images">Google Images</option>
</optgroup>
....
</form>

<script type="text/javascript">

function doSearch( f ) {
    var searchTerm = f.searchText.value;

    if( !searchTerm ) {
        //prompt user to input a search string
        // end request by returning false
        return false;
    }

    var sel = f.whichEngine;
    var selectedEngine = sel[sel.selectedIndex].value;
    var engineUrl;

    switch( selectedEngine ) {
        case 'google_search':
            engineUrl = 'http://www.google.com/search?q=';
            break;
    ....
    }

    engineUrl += searchTerm;
    window.location.href = engineUrl;

}

</script>

Answer №2

Do you need to submit the search form with a specific location?

Make this adjustment in your code:

function startSearch(){
  // ...................
  // ...................
  // ...................

  window.location.assign(finalSearchString);
}

Modify it to this:

function startSearch(){
  // ...................
  // ...................
  // ...................

  if (finalSearchString)
  {
    document.searchForm.action = finalSearchString;
    document.serachForm.submit();
    return true;
  }
  else
  {
    return false;
  }

Lastly, update your form tag like so:

<form name="searchForm" onSubmit="return startSearch();">

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

Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using: <script type="text/javascript"> function handleSelectionChange(selectElement, nextField) { nextField.focus(); } function handleKeyPress(event, currentField, nextField) { i ...

Employing an item as a function

My query pertains to utilizing an express application object (app object) as a callback function. The express application is known for its methods and properties that aid in handling HTTP requests. When integrating the app object with an HTTP server, it se ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

Is it possible to set a value for a jQuery function after the function has

I am a beginner when it comes to javascript & jQuery. I am currently working on a feature for my website where users can display badges they have earned on their own site by simply copying and pasting a bit of code that I provide. Although the javascript p ...

What is the best way to incorporate a search feature within Bootstrap cards?

I've been struggling to incorporate a search feature within my bootstrap cards. Despite trying various online methods, none have proven successful for me so far. Below is my HTML code - any assistance in implementing a search filter into my app would ...

In order to ensure accuracy, the 'to' date must always be after the '

By default, when selecting a start date, the end date should be displayed as greater than the start date. However, in my current code, if I select the start date, the end date is set to be the same as the start date. Below is my code snippet. Thank you in ...

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...

Encountering issues with resolving dependency tree post updating node, specifically with node-sass dependency causing failure

Following the update to the latest version of Node.js, I encountered error messages when attempting to use npm audit fix --force. It appears that resolving dependency tree issues is proving to be difficult. Despite extensive research and trying various s ...

Unexpectedly, the child component within the modal in React Native has been resetting to its default state

In my setup, there is a parent component called LeagueSelect and a child component known as TeamSelect. LeagueSelect functions as a React Native modal that can be adjusted accordingly. An interesting observation I've made is that when I open the Lea ...

What could be causing the malfunction of the v-bind attribute?

I am in the process of developing a straight-forward To-Do List application with VueJS. <template> <div> <br/> <div id="centre"> <div id="myDIV" class="header"> <h2 style="margin:5px">M ...

The Alchemy feature on hover is not functioning

I am currently using alchemy.js to display a graph, but I am encountering issues with showing the "onMouseOver" caption of the graph's node. The console is displaying some errors which you can see here. Here is the code snippet: <html> < ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

Ensuring a consistently positioned footer at the bottom

I understand that this might not seem like a significant issue, but I'm encountering some difficulties. In my main.html file, there are three divs. The first div contains the navigation bar, the second div is an "empty" div that uses JQuery/Javascript ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

Adding Node.js Express responses to a running list

I have a situation in one route where I am using multiple instances of res.send. Is there a way to combine them all into one and then send the aggregated list at the end? The format I prefer is as follows: { "writer": {success message}, "archive": {succes ...

Stop an item from being included based on a boolean value

I need to iterate through an array of IDs called "world". The idea is that if the ID value in world exists in myArray[n].id, then I want to remove the entire element from myArray. If it doesn't exist, then I want to add it to myArray. world = ["124241 ...

Issue with Refreshing Header Row Filter Control in Bootstrap Table

Currently in the process of developing an application that utilizes Bootstrap Table and its extension, Filter Control. One feature I've incorporated is individual search fields for each column to enhance user experience. The challenge I'm facing ...

Inexplicably, HighCharts flips its axis when exporting data

I am facing an issue with the display of my Highchart in the web application. While it appears correctly in the browser, the exported chart flips the axis and shows a different image. Below are the options I have configured for my Highchart: var options = ...

Adjustable Bootstrap Progress Bar - Modify element width on the fly

I have encountered an issue with my progress bars on the webpage. The static HTML version works perfectly fine, but the dynamically created one using jQuery seems to be instantly at 100% without any delay in progression. To illustrate the problem better, ...

Utilizing Regular Expressions in Sails.js Routing

Currently, I am working on a sails.js project and utilizing backbone for the front end. My goal is to have a single route leading to the index page where my backbone application is hosted. '/*': { view: 'home/index' } This setup ...