Form Text Area creates a URL - javascript

I have a pretty simple need here.
I want to have a text area, that is populated with a line of ID's - each id will be on a new line.
How can I generate a URL from that?
12345
09876
Once submitted should generate to be https://xx.com/12345&09876
I have been using this Form value creates a URL and have changed it to text area, but cant get each line break to be changed to the '&' in the url string.
Any help would be amazing!
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page;
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />

You can split by \n to get the characters in each line and join by &, then remove the last character:
var url = txt.value.split("\n").join("&").slice(0, -1);
console.log(url);
<textarea id="txt">
12345
09876
</textarea>
In the case of a form:
txt.addEventListener('input', function(){
form.action = txt.value.split("\n").join("&").slice(0, -1);
console.log(form.action);
})
<textarea id="txt">
12345
09876
</textarea>
<form id="form">
<button>Submit</button>
</form>
In your particular case:
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
<script type="text/javascript">
function goToPage() {
var page = document.getElementById("page").value.split("\n").join("&");
alert(page);
window.location = "https://google.com/" + page;
}
</script>

You can replace text in a string using the JavaScript replace function, as follows:
var newString = oldString.replace(/(\r\n|\r|\n)/g, '&');
This line takes the string variable oldString (which should contain the data with all of the linebreaks) and changes all of the linebreaks to ampersands. It uses something called a Regular Expression to find all of the line breaks.
So for your HTML:
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page.replace(/(\r\n|\r|\n)/g, '&');
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />

try splitting your text area by \n by doing so:
var split_text = your_text_area.split("\n"); // Replace your_text_area
The string which will be passed in the text area will be splitted by \n (newline) and every line will be inserted in the split_text variable, which is an array.
Then, you can generate a URL from the array like this:
var url = '';
for(let i = 0; i < split_text.length; i++)
{
url += split_text[i];
if((i+1) != split_text.length) // <-- Not the most optimized way to do it
{
url += "&";
}
}

Related

How to make a loop with Javascript that runs through every value of an html text field in a form

I'm creating a form that has two input text fields for URL values. The purpose of the form is to concatenate the URL value(s) in field 1 (Starting URL) with the URL value(s) in field 2 (Closing URL); each starting URL has a unique corresponding closing URL. If a user has multiple pairs of starting and closing URLs, I would have to make a loop, but I am having trouble doing so. So, say the user has 2 pairs of URLs they wish to concatenate together. The user would enter each URL value into their respective fields with a single space separating each starting and closing URL from one another. Upon clicking the "concatenate" button, each pair of starting and closing URLs is supposed to spit out a unique URL in the hmtl element "results". So, for example, say the user has the following two pairs of starting and closing URLs in the form:
Starting URLs: https://www.google.com/ https://www.microsoft.com/en-us/
Closing URLs: https://mail.google.com/mail/u/0/ https://outlook.live.com/owa/
Upon clicking the button "concatenate", the goal is to see the following two lines of concatenated URLs under "results":
https://www.google.com/&URL=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F%20
https://www.microsoft.com/en-us/&URL=https%3A%2F%2Foutlook.live.com%2Fowa%2F
The function "encodeURIComponent" is being used to encode each closing URL that the user enters. Please let me know if you can help or if any clarity is needed. Code work is below.
function concatenate() {
var a = document.getElementById('url1').value;
var b = document.getElementById('url2').value;
var index;
var res1 = a.split(" ");
var res2 = b.split(" ");
for (index = 0; index < a.length; index++)
text += "<li>" + res1[index] + "&url=" + encodeURIComponent(res2[index]) + "</li>";
}
}
document.getElementById('result').innerHTML = text
}
<!DOCTYPE html>
<html>
<body>
<form id="concatenationform" method=post>
<h2>Tag Concatenation Form</h2>
<p>Enter Starting URL(s) Below
<br>
<input type=text id=url1 name=url_1 size=50>
<br>
<p>Enter Closing URL(s) Below
<br>
<input type=text id=url2 name=url_2 size=50>
<br>
<button onclick="return concatenate()">Concatenate</button>
</p>
<br>
<p id="results"></p>
</form>
</body>
</html>
Lots of issues here as following:
1. Braces don't match.
2. Button is submitting form
3. Text is not defined
4. Looping on a which is a long string and results in iterating on each character
Here is the fixed code based on issues mentioned above:
html (Button type is button so no submission, no return):
<form id="concatenationform" method=post>
<h2>Tag Concatenation Form</h2>
<p>Enter Starting URL(s) Below
<br>
<input type=text id=url1 name=url_1 size=50>
<br>
<p>Enter Closing URL(s) Below
<br>
<input type=text id=url2 name=url_2 size=50>
<br>
<button type="button" onclick="concatenate()">Concatenate</button>
</p>
<br>
<p id="results"></p>
</form>
Javascript (fixed braces, declared text and looping through array):
function concatenate() {
var a = document.getElementById('url1').value;
var b = document.getElementById('url2').value;
var index;
var text = '';
var res1 = a.split(" ");
var res2 = b.split(" ");
for (index = 0; index < res1.length; index++) {
text += "<li>" + res1[index] + "&url=" + encodeURIComponent(res2[index]) + "</li>";
}
document.getElementById('results').innerHTML = text;
}
JSFiddle

Censoring / Highlighting using JavaScript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

get last word typed in Javascript

I'm wondering how to get the last word typed in Javascript. I have a text area my_text and when the user hits the spacebar it will get the last word that the user typed. This is what I'm trying so far
function getLastWord() {
var input = document.getElementById(my_text.value);
//var lineIn = document.getElementById(my_text).innerHTML;
var lastWordTyped
var changeColorOfWord;
if (input == null) {
input == " ";
}
lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
When the function gets called on a spacebar hit, it says that input is null so when it gets the lastWordTyped var, it shows up null and errors out, does anybody know why this may be happening?
Preferably no JQuery
Here's some of the HTML to go with it.
<body>
<br />
<!-- Text area -->
<textarea class="text_edit" id="my_text" onkeypress="return myKeyPress(event)" onkeydown="return onKeyDown(event)"></textarea>
<br />
<!-- Submit button -->
<input type="button" value="Run Code" onclick="view_text()" />
<!-- Empty div to put the text in -->
<div id="view_text">
</div>
Ok, so I got the error to go away now i just need it to change the font color of the word typed lol..
Did you mean
var input = document.getElementById("my_text").value;
Try this:
<textarea id="MyText" rows="10" cols="50" onkeyup="getLastWord(event);"></textarea>
var Old = "";
var New = "";
function getLastWord(e)
{
New = document.getElementById("MyText").value;
if(e.keyCode == 32)
{
Old = New.replace(Old, "");
alert(Old);
Old = New;
}
}
DEMO

Assigning an id to a regex pattern

I need to assign an ID into a pattern so that someone could write something in my first text field, and then write a key word in the second textfield, then the key word will be the pattern searched by the RegExp.
JavaScript
function getInput(textfield)
{ // get value from field
var inString = document.getElementById("string").value;
var inSubstring = document.getElementById("substring").value;
// search for pattern
var patt1 = /Id/g;
// document.writeln(patt1);
var result = inString.match(patt1);
// choose paragraph and write the result
document.writeln(result);
// document.getElementById("Answer").innerHTML = result;
}
HTML
<body>
<form id="form1" name="form1" method="post" action="">
<label>Enter a string
<input id="string" name="string" type="text" />
</label>
<input name="Button" type="submit" value="Submit" id="Button" onclick="getInput('textfield')" />
<br />
<br />
<label>Enter a substring to search
<input id="substring" name="substring" type="text" />
</label>
</form>
<p id="Answer"> </p>
</body>
Use a RegExp object instead of an inline regex :
function getInput(textfield)
{ // get value from field
var inString = document.getElementById("string").value;
var inSubstring = document.getElementById("substring").value;
// search for pattern
var patt1 = new RegExp(inSubstring, "g");
// document.writeln(patt1);
var result = inString.match(patt1);
// choose paragraph and write the result
document.writeln(result);
// document.getElementById("Answer").innerHTML = result;
}
I believe you want this regex to change:
var patt1 = /Id/g;
And support a variable id to be searched.
You can use RegExp object with word boundaries:
var patt1 = new RegExp('\\b' + id + '\\b', 'g');
OR else you can just dump the regex and use String#indexOf like this:
index = inString.indexOf(id);

Categories

Resources