Home > database >  How to use JavaScript to jump to the URL after the input box is sent, and the input box can still co
How to use JavaScript to jump to the URL after the input box is sent, and the input box can still co

Time:01-10

I currently have a requirement that after entering a keyword ~ ​​the keyword will be placed at the end of a set of URLs as a parameter, and the set will redirect to the specified page to appear. But what I hope to achieve is that even if I jump to another page, the keyword I just entered will not disappear, and it will still stay in the input input box! The following is my current writing method, but it failed~ It seems that the last jump should be changed The parameters behind the URL are extracted and placed in the input box. But I am a novice in programming and I don’t know how to rewrite it to achieve it. I hope I can get your help, thank you

$("#js-search").on('click',function(){
   let keyword = $("#keyword").val()
// Here, the entered keywords will be placed after the URL to jump to the specified page
     window.location.href = `/help_center?keyword=${keyword}`;
   $("#keyword").val(keyword)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="keyword">
<button id="js-search">send</button>

CodePudding user response:

As I understand your question, Once you have redirected the user to another page, You are actually sending them to a different page you will no longer have access to the current page's DOM.

If your question is How to read the passed query param in redirected page? then you use the following code:

// ?keyword=hello
const params = (new URL(document.location)).searchParams;
const keyword = params.get("keyword"); //hello

If you actually updating the current page with the query parameter, Then you can follow the below code:

$("#js-search").on('click',function(){
   const keyword = $("#keyword").val();
   window.location.href = `?keyword=${keyword}`; // Updating the query param
});

// Setting updated query param
const params = (new URL(document.location)).searchParams;
$("#keyword").val(params.get("keyword"));
  • Related