Prefilled HTML forms FROM buttons - javascript

I hope this question has an obvious answer to anyone who knows his way around JS and HTML :)
I have a very specific problem. I am trying to add to the header on a site buttons that will function like 'quick searches' which will basically on click send pre-filled form values to my search page and have the search page also populate these values in the ajax form inside.
Here is a sample search page that's outside of the results page:
http://www.thediamondsexperts.com/index.php?route=product/diamondsearch/jewelry
You'll notice that when you change the values there and click Search, the values also appear in the ajax form on the sidebar of the search results page.
What I simply want to do is create different variations for pre-set searches, and put them as buttons in the header.
When I try to put a few invisible forms in it won't work because of the multiple form values with the same ids but in general I think there must be a simple way to do this server side.
For instance, copy the current function that accepts the search, have it with pre-set values instead of populating the values from the form and then simply calling that function onClick. Does that make sense?
I need to create something simple enough though that would be easy for the admin to later change and customize more buttons so a client-side solution would be best.
Your help is much appreciated!

All you need is a form with hidden inputs and a submit button:
<form>
<input type="hidden" name="param1" value="Predefined value 1" />
<input type="hidden" name="param2" value="Predefined value 2" />
<input type="hidden" name="param3" value="Predefined value 3" />
<button type="submit">Search!</button>
</form>
This will only show the button, but the values will still be sent to your form's action.
...there must be a simple way to do this
server side
...a client-side solution would be best
...copy the current function that accepts
the search, have it with pre-set
values instead of populating the
values from the form and then simply
calling that function onClick. Does
that make sense?
Not really, not to me at least. If you can clarify I'd be glad to help more.
When you say "multiple form values with the same ids", I fear you may be confused: There is no requirement for a form input to have an "id", I think you mean "name", and there's no need to have multiple inputs with the same name in a form unless you want to send an array of values.
I didn't want to go overboard and talk about how the ajax works on that site, because that's another thing altogether and all you seemed to be concerned about was the preset search buttons. Hopefully this helps you figure it out, GL.
EDIT: I'm having a tough time figuring out what you're really asking, if you are trying to duplicate the behavior on that site, please tell us what server side language is available to you, if you're using or open to using any javascript libraries, and what you have tried so far. A full fledged spoon-feeding tutorial is really out of scope, you will get better, clearer help if you share the code from your current attempts.

If you want to pass values from one page to another and handle it client-side, use "get" for the form submit method, and use the handy "gup()" function to grab the param values. You can get more info on gup() here:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
On your initial page, you can either use inputs with type="hidden" or just get the values from the visible inputs (as on your sample page). Then submit to your results page. Given an initial page with something like this...
<form method="get" action="results.html">
<input type="text" name="caratFrom" value="0.7" />
<input type="submit"/>
</form>
... here's sample usage for the results page:
var caratFrom = gup('caratFrom');
// etc.
Then simply assign those values to whatever elements you want, e.g. an input:
<!-- HTML -->
<input type="text" name="caratFromResult" value="" />
// Javascript
document.getElementById('caratFromResult').value = caratFrom;

Related

Submit form before redirecting to another page with JavaScript

I have a complex form; within it there's also an 'add more items' link that takes the user to another form-page (independent). What happens at the moment is that when they have edited the main form without saving it and they go to the independent form, when they come back to the main form page they have lost the edits.
<form id="form_1">
[...]
Add something else.
<input type='submit'/>
</form>
add-something-else page:
<form id="form_2">
<input type='submit'/ onsubmit='go_back_to_form_1'>
</form>
Saving everything in sessionStorage would be overkill (I think), and scripts like FormPersistence.js mess about with other functionalities of my form (i.e. Django formset). I have tried to achieve what I want by attaching this function to my 'add something else' button:
$.when(document.forms["form1"].submit()).then(function(){
window.location.pathname = '/add-something-esle/'
})
For some reasons, though, when I go back to form1 I see that the form wasn't saved. How can I achieve what I want?
A <form> is made up of input elements, and you can persist all the <input .../>s to session/local storage and recover them all on page reloads; I remember answering a similar question before; but here is the summary from that answer:
basically you set an event listener on input elements you want (i.e. query selector); make sure they have id (or something similar) unique because we are going to use it as key t store the value;
here is an example:
function persist(event) {
// `id` is used here
sessionStorage.setItem(event.target.id, event.target.value);
}
// you may use a more specific selector;
document.querySelectorAll("form input").forEach((formInput) => {
// `id` also used here for restoring value
formInput.value = localStorage.getItem(formInput.id);
formInput.addEventListener("change", persist);
});
this snippet will persist all <form> tag's inputs values into session storage;
you can also use more specialized selector in .querySelectorAll() to meet your need
Full page reloads clear all form state. You need a way to persist the state between full page reloads. You can use sessionStorage for that.

Is there any way to edit a URL to embed a form entry?

I know it is possible to embed form values into the URL as parameters if the form has an ID assigned to it. But what if it does not have an ID?
For example the "Search" field in this page:
http://au.autodesk.com/speaker-resource-center/call-for-proposals/voting
<input type="text" placeholder="Search " class="form-control ng-valid ng-dirty search-box" ng-model="search.$" ng-change="updateButtons()">
I know it is possible to embed form values into the URL as parameters if the form has an ID assigned to it.
That is not true.
Server-side (and occasionally client-side) code on a page may read the query string as a means to set default values for form controls (typically so that a form can be corrected and resubmitted if there were errors in the previous attempt).
In these cases, the name attributes will usually map onto the query string (because the form will generate the query string from the name attributes). Often an input will be given an id that is the same as its name.
It is entirely under the control of the site's authors.
There is no way to set values of inputs on another site without the other side providing a mechanism to allow you to do that.
There's a few different ways to do that. Looking at that HTML, it's the first text-type input inside the div, so the first method that comes to mind is this:
You could pull out the div (using the class "search-area") and then target the first text input box within that div. I don't know whether you're using jQuery or native JS or exactly what language/library/framework you're using.
JQuery would be something like:
var inputElement = $(".search-area")[0].first()
This SO answer may help:
jQuery: how to find first visible input/select/textarea excluding buttons?
Edited to add: Answer is targetting the input element. As the answer from someone else mentions.. You can't actually do what you're wanting to do with the URL.
Edited again. Misread the question. I'll leave this here in case someone else needs to know how to target an input field that doesn't have an ID. Alternatively, I have no problems if someone wants to delete this answer.

How can I modify the query from a user submitted search input with a Chrome extension?

So, I'm writing a Chrome extension for a school assignment and I'm stuck on this part where I think I need to parse a string. This is my first time working with HTML, CSS, and JS, so I'm just scouring the web for tips on how to make this happen.
Basically, in our assignment we need to create an extension for Chrome which essentially opens up a new page where we have a search bar. There's this website, https://www.manualslib.com/, and the terms we input into that search bar need to be used to directly search that site.
The problem is that this website's URL for searches is a bit different than what I'm used to: when you search for something, the website takes the first letter of my search term, puts it in between slashes, and then adds at the end the whole search. For example, if you search genetics there, the URL will look like https://www.manualslib.com/g/genetics.html.
So I guess I need to parse the string somehow to get the search term's first character, right? According to w3schools, using the split() method would be a good idea. The problem is I'm not really sure how the syntax works here. As I said, it's my first time dabbing in web developing, so I'm not familiar at all with the way people do stuff here. Any help is appreciated.
This is the code I have for the search bar (this code merely redirects to the webpage, it doesn't search anything):
<div id="tfheader">
<form id="tfnewsearch" method="get" action="https://www.manualslib.com/">
<input type="text" class="tftextinput" name="str" ; size="21" maxlength="120">
<input type="submit" value="search" class="tfbutton">
</form>
</div>
What kind of changes do I have to make? Do I need to create a .js file where I write the function that parses the string? Or is the parsing function written inside the HTML file? Any help is appreciated, thanks in advance!
var query = 'genetics';
var url = 'https://www.manualslib.com/{0}/{1}.html'
.replace('{0}', query.substring(0, 1))
.replace('{1}', query);
console.log(url);
The onsubmit event might help you.
To redirect to another site, just set window.location, like this:
search_form.onsubmit = function() // will be called as soon as the form is submitted
{
var searchText = typehead.value; // the text entered in the search bar
var redirectTo = "https://www.manualslib.com/"+searchText[0]+"/"+searchText+".html";
window.location = redirectTo;
}

method of including data in a url

URLs include data about where have you been in a website and when you re-visit, they show the exact information. For example I was in Google Maps, searched "Barcelona" and then "fly" to the Isle Of Man. If you open this url https://www.google.com/maps/place/Barcelona/#54.2584676,-4.4790783,10z/data=!4m2!3m1!1s0x12a49816718e30e5:0x44b0fb3d4f47660a you will see Barcelona in the search box (place/Barcelona) but the map will zoom in the Isle Of Man (#54.2584676,-4.4790783 lon-lat I guess)?
So it shows you where I have been, not just a map and an empty search box. This happens to most websites, urls include data about photos, profiles, modules etc. I am not talking about simple anchors like (site.com/page.html#header). I am NOT talking about AJAX.
I want to learn more on how you can store data in a url and when you visit it, the page loads specific parts AND data.
What is the name of that method? How does it work? How do I implement it?
One of the things I believe you're referring to is the GET method.
To add data to the query string (that's what the string is called that is usually after the question mark (?) and the divided by the and sign (&) depending on the number of attributes you want to pass to it.
One way of passing attributes to the query string is by using the GET method in a form for example as follows:
<form method="get" action="other-page.php">
<input name="example" type="text" />
<input name="other" type="text" />
<input name="submit" type="submit" value="submit" />
</form>
Once you click submit on the above form, the name attributes of the inputs will become the attributes of the query string and their values will be whatever has been added as value for those fields. So if you filled in 'this' for example and 'that' for other, then the query string would look like this:
domain.com/page?example=this&other=that
This information can then be retrieved on the other page that the form has been sent to (you will see the name of that other page under action="other-page.php in the form tag).
Assuming it's a page written in php, this is how you can get the values of the attributes:
echo $_GET['example']; // this would output 'this'
echo $_GET['other']; // this would output 'that'
In your example, google for example uses the lon and lat attributes to place you on the right spot on the map. Though looking at their query string, they look like using a different method than the classic GET as I explained above.
The hashtag however (#) is there to point to specific sections of a page (assuming it's not being manipulated by some javascript code, but that's a whole different story). If you setup a link like this one:
Click here to go to section 2
...then further down on the page you added...
<a id="section2"></a>
...and clicked the link above, the page would jump down to section 2 for you.
Please have a look at the history-API, espacially history.pushState():
https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries

Form submission string concat/modify

So not sure if this is possible but I have a pretty complex form. With multiple levels of processing ie: If you click a radio button 'x' amount options so up in a drop down etc etc.
Well the problem I have is all the form fields need a name, and went I submit the form I'm sending alot of junk. IE Url could be '?meat=3434?fruit=34495?salad=034943' you get the idea. But in the end all I'm looking to is pull the 'salad' value into the url without all the other byproducts. IE: '?salad=034943'
I've tried a few things, pulling all the inputs radios etc out of the form and placing them in a div. The making a form with just a hidden value so I can pull through Mootools (But that made conflicts because I'm using Mootools Form.Validator so then that fails) Then I tired to make two forms, One that would just be all show, then I would pull the value I want into the processing form. Which I thought would work but apparently it still will process both forms.
Any ideas/techniques of how to accomplish this would be greatly appreciated! (because I'm losing my mind)
Disable any form field you don't want sent and it won't show up in the URL.
In HTML it's:
<INPUT type="text" name="foo" DISABLED>
In javascript set document.forms[...].elements[....].disabled = true.
If you hide the field with CSS it will still be sent like normal.
the elegant way you do this is mount your GET url to submit by yourself..
this way you can send only what you want..
dont send any junk.. you can have problems in the future with a variable that you didnt know you were sending..
you can use this util function of jQuery
var params = { width:1680, height:1050 };
var str = jQuery.param(params);
// str is "width=1680&height=1050"

Categories