1

I have a simple search form that looks like this:

<form action="http://www.theurltosearch.com" method="post">
 <input class="search-box" name="query" type="text" value="search all reports" />
 <input type="submit" name="search" />
</form>

What I'm trying to accomplish

The search is pointing to whats really a filtering system using tags.

In order for the user to properly see the results of what they queried the query url has to look something like this http://www.theurltosearch.com/#/Kboxes the # and the K are important as its how the tagging system returns results where K stands for keyword.

For multi term queries the url has to look like this separated by a comma http://www.theurltosearch.com/#/Kboxes,Kmoving

A user should also get results when they enter a string query something like http://www.theurltosearch.com/#/K%22more%20stuff%22

Right now if someone used the search it would just take them to the url and not actually display any results matching their query.

How can I manipulate the url string to return the results how I've shown above?

My actual attempt

<script type="text/javascript">
    window.onload = function(){
      var form = document.getElementById("reports-search");
      form.onsubmit = function(){
        var searchText = document.getElementById("search-reports");
        window.location = "http://www.urltosearch.com/#/K" + searchText.value;
        return false;
      };
    };
</script>

<form id="reports-search" method="get"> 
 <input class="search-box" id="search-reports" type="text" value="search all reports" /><!--search term was analysis-->
 <input type="submit" name="search" />
</form>

returns

http://www.urltosearch.com/#/Kanalysis

and displays all results with the analysis tag

This attempt works succesfully if someone is searching a single keyword but not if the user is searching multiple or a string

How do I change the JS to achieve the other options?

4
  • Since you're using a custom url scheme and eschewing the standard one used for GET params, you'll have to form the URL yourself. You should edit your question so that it includes an example of input and the desired url. It's also unclear if the number (#) will be extracted from the form. Commented Sep 28, 2016 at 21:35
  • @enhzflep thanks I played around and updated my attempt and am closer than I was before, could you take a look? Commented Sep 29, 2016 at 13:30
  • no problem :) That's better. But hey, what does the input look like? I.e is it just a bunch of space-delimited words, or perhaps space and/or comma delimited. Also, is http://www.theurltosearch.com/#/K%22more%20stuff%22 an example of input, or just the resultant url of a search for "more stuff"? Commented Sep 29, 2016 at 13:35
  • @enhzflep thats a good question the input is a search box where users can type in a keyword or a phrase. After looking at how the tagging system I'm trying to link to actually works I don't think I need the multi keyword option i.e theurltosearch.com/#/Kstuff, Kmorestuff users can add tags once they get to that screen now I just need a way for the search to return results for string queries i.e. the url you posted in your above comment that url is the result if a user input more stuff and hit submit in the search Commented Sep 29, 2016 at 13:54

1 Answer 1

1

Okay, here's a dog'n'bird implementation (ruff,ruff, cheap,cheap).

I've allowed the user to enter multiple terms, each separated with the pipe character | If you wish to allow the user to enter a url in essentially the same format as they'd receive by 'normal' keywords, you may wish to check the entered text first and if found, simply pass it straight through without changing it.

You'll notice, I've wrapped all search terms with " ", regardless of whether the term is multi-word or not. You could easily differentiate between a single-word term and a multi, by searching the string for a space character after the string.trim has removed leading/trailing spaces. I.e

if (trimmedTerm.indexOf(' ') == -1)
{
  // single word search term
}
else
{
  // multi-word search term here
}

Anyway, here's a working demo, hope it gives insight.

function byId(id){return document.getElementById(id)}
// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need


window.addEventListener('load', onDocLoaded, false);

function onDocLoaded(evt)
{
	byId('goBtn').addEventListener('click', onGoBtnClicked);
}

function onGoBtnClicked(evt)
{
	// get the user input
	var inputString = byId('userInput').value;
	// split it into an array of terms, based on the | char
	var searchTerms = inputString.split('|');
	// init the result
	var result ='';
	// for each element in the array of search terms, call the function to trim wrap with "" and encode
	forEach(searchTerms, addCurTermToResult);
	// update the output display
	byId('output').textContent = 'http://www.theurltosearch.com/#/' + result;

	function addCurTermToResult(curTerm, index)
	{
		if (index != 0)                     // put a comma before all terms except the first one
			result += ',';
		var trimmedTerm = curTerm.trim();   // remove leading/trailing spaces
		result += 'K' + encodeURI('"' + trimmedTerm + '"' );	// wrap with "" then URI encode it, suitable for use as a URL
	}
}
.panel
{
	border: solid 1px black;
	border-radius: 8px;
	padding: 8px;
	background-color: #eef;
	display:inline-block;
}

.panel textarea
{
  width: 500px;
  height: 200px;
}
<div class='panel'>
		<textarea type='text' id='userInput' placeholder='Enter tags or a url. tags should be seperated with the | character'></textarea>
		<div style='text-align: center'><button id='goBtn'>Submit</button></div>
		<hr>
		<label>URL: <span id='output'></span></label>
	</div>

Sign up to request clarification or add additional context in comments.

6 Comments

this is the right direction. I need the url to actually go to that page though with the relevant keywords or string not just output. I tested it in the code in the snippet with the keyword "yes" I noticed it outputs with theurltosearch.com/#/K%22yes%22 this wont display anything with the yes tag for the user but if the url looks like this theurltosearch.com/#/Kyes it would
Good. Well, then simply set window.location.href to the result and voila! You're there. As for the second point you raise - I explicitly covered this in my answer i.e single/multi-word terms - the non "" wrapped version would be result += 'K' + encodeURI(trimmedTerm); ;)
I'm sorry I feel like I am inexperienced I added 'result = window.location.href;' right below the byId('outpu').textContent = . . . . line (after the semi colon of course) and the output is still not being pushed to the address bar. I'm sure I'm missing something simple
Nothing to apologise for. Oops! I've a hbbit of misusing the language and being confusing. You're so, so, so close - you just wiped out the computed result and replaced it with the current url. You need to go the other way i.e set the current url from the computed result. So, change byId('output').textContent = 'http://www.theurltosearch.com/#/' + result; to window.location.href = 'http://www.theurltosearch.com/#/' + result; It's well worth your time checking out the debugger and how to use it too. An incredibly useful tool. :)
Ah yes that makes sense, thank you very much, I would have never gotten this far/efficient on my own haha
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.