Send a user to a certain URL depending on his text field input - javascript

Basically I want the ff. done:
User inputs a text in my text field. If his text matches a text in my "list," he is sent to a certain URL once he hits the submit button.
I found a similar code on this site but his is just one specific text value. [ Get input text field from HTML into JavaScript and go to URL ]
I want mine to determine the user's text input from a list I provide. My list will have a lot of texts/urls and it will continue to grow, so manually inputting values into the script won't work for me.. I want to be able to edit the list (possibly in an admin panel or something?) instead of the js code.
Example:
input text: aaaa, go to URL1
input text: mmne, go to URL2
input text: lhfj, go to URL3
input text: tigf, go to URL4
input text: gred, go to URL5
Can anyone help me with this please? Thanks!

Hope this helps you
var Something =$("#TextBoxID").val();
if(Something == "aaaa")
{
window.location.href = 'URL1'; //Will take you to URL1
}
......
......

if you want to configure the list on an admin console you need to have some kind of server side technology like php (or node.js if you want to keep using javascript). You need to think of where this data will be stored. A possibility would be fetching the list of text/url pairs using ajax (e.g. with jQuery) and storing the data in some database or in your case also a plain text file probably would suffice. The functionality you are looking for is not possible with plain HTML and JavaScript on cient side.

Use a function like this, if you store your URLs on the client side (HTML/JS page):
function determineAndGoToURL(text) {
var url = "#";
switch(text) {
case "aaaa":
url="www.google.com";
break;
case "bbbb":
url = "www.bing.com";
break;
default:
url = "www.yahoo.com";
break;
}
window.location.href = "http://" + url;
}
If you have an updated list of URLs on the server side, get them from server-side to client side, and iterate over them with a for statement.
I'd suggest, you'd get them from the server as JSON, and use JSON.parse(text) to create an object out of them, and then iterate.

Related

Simple MEAN Stack issue

I have a express route;
router.get('/uni/:queryst', function (req, res) {
var choice = req.params.queryst);}
Where basically I use the queryst value from the URL to use it to query something in my database. On the front end, I need to have an input field where the user types the choice and hits submit and then it translates to something like /uni/valuehere on the browser and sending GET to express where it gets caught by the router I wrote above. I don't know how can I make the input field of HTML turn into a URL of the format /uni/valuehere .
As for testing the code initially I was directly typing the URL manually with the value I intended to verify to check if the data passed. Well, users are not going to type URL's directly to search, they will need a form and that is what I can't get my head around to how to turn the input field into a URL in a format /uni/WhateverTheUserHasTypedInTheFieldShouldAppearHere
Thanks in advance for the help. I am self learning the MEAN stack and have come a long way. I need support of experienced developers as I am currently stuck here.
While sending the request write (in controller):
$http.get('/uni/'+queryst).success(function(response){
// Write code using response
});
While on the server side write:
$http.get('/uni/:queryst',function(req,res){
var choice= req.params.queryst
// Code ....
});

How to save entered text in JS/Html

How do i save entered/ inputted text using JavaScript/ html.
What do I want:
Name or code etc to be entered in a box (prompt box eksample) and then I want it to be displayed/ printed on the page and I want it to remain there so other people that visit can see it.
What I have:
I have code that shows a prompt box where you can enter text then displays it in green. However what i want is for the entered text to remain on the website for others to see...
function mobCode() {
mobCode = prompt("Insert Code", "Code here");
document.getElementById("mC").innerHTML = mobCode;
document.getElementById("mC").style.color="green";
}
<p id="mC"> Mob Code </p>
<button type="button" onclick="mobCode()"> Click to Add </button>
What you will probably have to do is write a script that will send the entered input to a database you build which can store that information,and then have your js access the database to display it in a certain area of your page.
Check out this Q & A one of the answers is a nice article to help explain the idea behind it: Send data from javascript to a mysql database
If you want to deal easier with persistence of the data, instead of setting up database and using server side script you can look at Facebook's Parse. The free plan is quite usefull for small projects. There is a JavaScript SDK that can be used directly from your javascript code.
Also you can view statistics from the Parse dashboard.
Here is some saple code for example:
// Create a new Parse object
var Post = new ParseObject("Post");
var post = new Post();
// Save it to Parse
post.save({"title": "Hello World"}).then(function(object) {
alert("Yay! It worked!");
});

Make sure user doesn't put in malicious html in code

I'm using a textarea to get input from the user and display it on the screen. How can I make sure that if they put in something like
<h1>YAY, I hacked in</h1>
I only display it as it is, and it doesn't display as an <h1>. There must be a function for this. Help? :D
As I commented, if you're about to send that data to a server, you should use one of the various XML Parsers available and strip + validate the input.
If you however, need to purely validate on the client, I suggest you use document.implementation.createHTMLDocument, which creates an fully fledged DOM Object on the stack. You can then operate in there and return your validated data.
Example:
function validate( input ) {
var doc = document.implementation.createHTMLDocument( "validate" );
doc.body.innerHTML = input;
return [].map.call( doc.body.querySelectorAll( '*' ), function( node ) {
return node.textContent;
}).join('') || doc.body.textContent;
}
call it like
validate( "<script>EVIL!</script>" );
You need to address this on the server side. If you filter with JavaScript at form submission time, the user can subvert your filter by creating their own page, using telnet, by disabling JavaScript, using the Chrome/FF/IE console, etc. And if you filter at display time, you haven't mitigated anything, you've only moved the breakin-point around on the page.
In PHP, for instance, if you wish to just dump the raw characters out with none of the user's formatting, you can use:
print htmlentities($user_submitted_data, ENT_NOQUOTES, 'utf-8');
In .NET:
someControl.innerHTML = Server.HtmlEncode(userSubmittedData);
If you're trying to sanitize the content client-side for immediate/preview display, this should be sufficient:
out.innerHTML = user_data.replace(/</g, "<").replace(/>/g, ">");

HTML form with intermediate web service service call before submit

I have an HTML form to update the address in the account that submits to a Java servlet.
The problem is that, the form should not accept free flowing address text. Instead the user should enter the zip code/house number/street name, and hit a search button.
This search needs to go to a webservice, perform authentication and get a list of valid addresses that match the search criteria.
This list of addresses should be displayed to the user in the same form (either unhide a hidden element or use a modal dialog), so the user can pick his address.
Only after the valid address is picked, the user should be able to hit the form submit button which sends the data back to the servlet.
I am not sure how to have these 2 buttons do different actions in the form. I am very new to JavaScript and any pointers or examples are much appreciated.
For your webservice build an output of the values based on a search result (a basic string). Put this data in a JSON statement or just a javascript array.
Return something that looks like this.
['SearchResult1', 'SearchResult2', 'SearchREsult3']
On your search box. Bind a function on change or blur.
$('#SearchBox').bind('change', function(){
var val = $(this).val();
//Please reference the Jquery Ajax function as im typing this from memory and i always mix one or two things up :).
$.ajax({
"type" : "post",
"url" : "yoururlhere",
"data" : { "search":val },
success : function(dataset){
//When it comes back here check to see if its valid data etc etc
//After you validate you can populate a picklist on the page with the values. Or do anything you want with the values like this
for(x in dataset){
$('#DocumentElement').append('<p>'+ dataset[x] +'</p>');
}
}
});
});
This should start you out. After that you can just do more things on the callback, or modify the dom in a way which suits you better :).

Create a textfile from the input of an html-form with the browser (client-side)

I have an html site with a form in it and I want the user to be able to create a text/xml file depending on the input. But I wan't to avoid setting up a webserver only for this task.
Is there a good way, to do that, e.g. with Javascript? I think you can't create files with Javascript, but maybe create a data url and pass the text, so the user can save it to file?
Or is there another way to achieve this simple task without a webserver?
Solved it, somehow. I create a data url data:text/xml;charset=utf-8, followed by the XML.
function createXML() {
var XML = 'data:text/xml;charset=utf-8,<MainNode>';
var elements = document.getElementsByTagName('input'),i;
for (i in elements) {
if (elements[i].checked == true) {
XML += elements[i].value;
}
}
XML += '</MainNode>';
window.open(XML);
}
So the url looks like data:text/xml;charset=utf-8,<MainNode><SubNode>...</SubNode>...</MainNode>
Unfortunately this doesn't work for me on Chromium(Chrome) and on Firefox. It just displays the XML instead of showing a save dialog. But I think that's because of my settings and at least you can save it as a XML-file manually.
I haven't tried this but it should work.
After getting form data, system will call page A.
page A will have javascript that gets query strings and builds the page accordingly.
After finishing page build, user can save current page with following statement in javascript
document.execCommand('SaveAs',true,'file.html');

Categories