Using JavaScript or jQuery to modify the URL of a webpage

Here is the HTML code I am working with:

<form id="search-new">
          <input type="text" name="search" placeholder="Search on the Site" value="">
          <input id="search-submit" type="button" value="&rsaquo;">
        </form>

Now, let's take a look at my jQuery script:

<script type="text/javascript">
  $(document).ready(function(){
    $('#search-new').submit(function(e) {
      e.preventDefault();
      //edited
      window.open = ('http://www.psicotropicus.org/'+'/search'+encodeURIComponent($('#search-submit').val()), '_blank');
      return false;
    });
  });
</script>

The idea behind this is that upon clicking submit, the JavaScript/jQuery will fetch the value of #search-submit and append it to the URL before redirecting the user.

Still facing an issue with _blank not functioning correctly.

Thank you for any help in advance.

Answer №1

To open a new window, use the window.open method with the second parameter set to _blank.

window.open('url', '_blank');

Another option you can try is:

<script type="text/javascript>
  $(document).ready(function(){
    $('#procurar').submit(function(e) {
      e.preventDefault();
      //edited
      window.open = ('http://www.psicotropicus.org/'+'/busca'+encodeURIComponent($('#procurar-submit').val()), '_blank');
      return false;
    });
  });
</script>

Most recent update:

<script>
  $(document).ready(function(){
    $('form#procurar-novo').submit(function(e) {
      //e.preventDefault();
      //edited
      var url = 'http://www.psicotropicus.org'+'/busca'+ encodeURIComponent('&' + $('input[name=procurar]').val());
       window.open(url, '_blank');
      return false;
    });
  });
</script>

<form id="procurar-novo">
          <input type="text" name="procurar" placeholder="Search on Site" value="">
          <input id="submitsss" type="submit" value="&rsaquo;">
</form>

Please make sure to use appropriate names and ids for form elements :)

Answer №2

It appears that the form tag in your code does not have an action specified. One alternative could be to change the type of the second input element from type=submit to type=button. This way, you can create a click event on that button and take full control of the subsequent actions without worrying about preventing default submit behavior. Here is a suggested approach:

$(document).ready(function(){
  $(document).on('click', '#procurar-submit', function() {
    window.location.href = 'http://www.psicotropicus.org/busca'+$('input[name="procurar"]').val();
  });
});

If you want to open the link in a new window using '_blank', you can modify the code as follows:

$(document).ready(function(){
  $(document).on('click', '#procurar-submit', function() {
    window.open('http://www.psicotropicus.org/busca'+$('input[name="procurar"]').val(), '_blank');
  });
});

Remember to be cautious of pop-up blockers.

EDIT I updated the selector for obtaining the value from the text field. Consider adding a unique class or id to the text field for better identification among others. You can refer to this example for more clarity.

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

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

Utilizing React's useState to store data in local storage

I am trying to figure out how to save data from a photos database API into local storage using the useState hook in React. Despite my attempts, I have not been successful with the useState method as the data in local storage gets cleared upon page refres ...

Transform a dropdown menu into an inverted footer

I stumbled upon a unique dropdown menu design that I want to tweak and reverse, making it an innovative "dropup" menu that opens from the bottom to the top. Currently, this is what I have: HTML <div class="get-started"> <a href="#" id="get-s ...

Ways to display the result in a new tab

I am using colorbox with a form that will be submitted to another website. I would like for the response from that web page to load in a new tab with a new URL. ...

How to properly utilize $.ajaxComplete and $.ajaxError functions?

I have been utilizing the code snippet below for my ajax form submissions: $.ajax({ url: "", data: ilmoittautumisdata, type: "POST", success:function(){ }); error:function(){ }); }); However, I recall being advised to discontinue using success and erro ...

Having trouble getting AngularJS $setPristine to work with the controller as syntax?

When using $scope, $setPristine works fine, but when using 'controller as syntax' it doesn't seem to have the same effect In View: <h2>With Controller as syntax</h2> <div ng-controller="FirstCtrl as first"> <form n ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Desiring the ability to retrieve a JSON response from a Laravel controller for use in my javascript code

I am trying to figure out the best way to fetch data from my Laravel controller and show it using JavaScript on a webpage. How should I approach this? Here is the code snippet of my controller and ajax call: var jq = jQuery.noConflict(); var id = jq(" ...

Attempting to switch between classes with the click of a button

I am attempting to create a basic animation that involves changing an image from A to B to C when a button is clicked. However, I am encountering an issue with the error message Cannot read properties of undefined (reading 'classList'). I am puzz ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Include JavaScript within the header section

It is commonly recommended to include .js files in the head section of HTML for good practice. The issue I am facing is that one of my .js files (or code+script) contains a function called beginning, and it is structured like this (now all placed in the h ...

Error: Unable to assign value to '18dit075' property as it is not defined in Node.js

var id = req.query.id; var username = req.query.name; var password = req.query.password; console.log(req.query); var data = { people:{ } } data.people[id] = { username: username, password: password, ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

The URL is being modified, yet the page remains static in the React application

I've been working on setting up a router with react-router-dom, but I'm facing an issue where my URL gets updated without the page routing to the specified component. Here's a snippet from my App.js: import "./App.css"; import { Br ...

What is the best way to confirm that a specific method was called on a JavaScript object using Selenium?

My goal is to use selenium to verify that a specific method (with parameters) was called on a JavaScript Object, similar to expectation mocking with JMockit but for Javascript and selenium. Unfortunately, the object I am dealing with is a heavily obfuscat ...

Retrieve information by utilizing query string parameters in Next.js

When using my getInitialProps function, I make two requests to fetch data. Now, I want to add a condition to make an additional request if the query params key is for a legal person. For example, if the URL is https://www.example.com.br/?legal-person, I n ...

Transforming a form containing recurring elements into JSON

Sorry if this topic has already been discussed, I wasn't able to locate any information I currently have an html form structured like so: <form> <div> First Name <input name="FirstName" type="text"> Age <input name="Age" t ...

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

Is employing setTimeout a legitimate technique for circumventing a stack overflow issue when implementing callbacks?

Let's imagine a scenario where I deliberately create a complex sequence of callbacks: function handleInput(callback) { ... } function fetchData(url, callback) { ... } function processResponse(callback) { .... } function updateDatabase ...

Creating a dynamic JPanel with jQuery: A step-by-step guide

While attempting to utilize jPanel for a collapsible panel generated dynamically from an XML content, I encountered an issue where the dynamically created panels were not appearing as expected. Refer to the image below: Here is my container: <div id=" ...