Getting the text within an input box - javascript

How can I get the text within an input box and go to the page ending with it? For example, if someone types "home" in an input box it directs the user to the URL https://mysitename.com/home.

You can do this using document.location.href.
let btn = document.querySelector('button');
let ipt = document.querySelector('input[type=text]');
btn.onclick = function() {
document.location.href = "https://mysitename.com/" + ipt.value;
}
<input type="text" placeholder="link name">
<button>go</button>

You can check this solution. This will append the input value to your current host name.
If you want predefined hostName then your can set the value to this variable. const hostName = "your host name here"
You can use window.location.href = yourNewUrl to redirect to new address. I've commented out the redirection line. You need to uncomment that.
const form = document.querySelector('#myForm');
const inputField = document.querySelector('#name');
form.addEventListener('submit', handleSubmit);
function handleSubmit(event) {
event.preventDefault();
const pageName = inputField.value;
inputField.value = '';
const hostName = window.location.hostname;
const url = `${hostName}/${pageName}`;
console.log(url);
// window.location.href = url;
}
<form id="myForm">
<input type="text" id="name" placeholder="type name and hit enter">
</form>

Simply type and direct to that link
by .addEventListener event change as you wish,
var mySearchInput = document.getElementById('mySearchInput');
mySearchInput.addEventListener('blur', (event) => {
document.location.href = "https://mysitename.com/" + mySearchInput.value;
})
<label>Link</label>
<input type="text" id="mytext" placeholder="Type link here..." />

Related

Collect URL.pathname from user input and append to existing url

I'm trying to Collect URL.pathname from user input and add to existing url, but when I do so, it doesn't seem to work when I output new URL.
<form id="myForm">
<input id="inputId" type="search" placeholder="Enter BSC Contract Address...">
<button onclick="getEndString()" id="submit" type="submit">Go</button>
</form>
let apiUrl = new URL('https://api.pancakeswap.info');
let myInput = document.getElementById("inputId");
let myForm = document.getElementById("myForm");
apiUrl.pathname = `/api/v2/tokens/` + getEndString(myInput.value);
function getEndString(x) {
return x;
}
myForm.addEventListener("submit", (e) => {
e.preventDefault();
console.log(apiUrl.toString());
});
Remove the onclick listener from the <button> element.
<form id="myForm">
<input id="inputId" type="search" placeholder="Enter BSC Contract Address...">
<button id="submit" type="submit">Go</button>
</form>
Move the assignement of the pathname into the event handler. The reason for this is that you want to read the value of the input and create the value for the pathname whenever you submit. Doing it outside of the event handler will only trigger the assignment whenever the script is loaded, but not after that.
let apiUrl = new URL('https://api.pancakeswap.info');
let myInput = document.getElementById("inputId");
let myForm = document.getElementById("myForm");
myForm.addEventListener("submit", (e) => {
e.preventDefault();
apiUrl.pathname = `/api/v2/tokens/` + myInput.value;
console.log(apiUrl.toString());
});

Set form action with JavaScript

I have a basic form. I have hidden inputs outside the form. I want to set the form action with JavaScript to include the values from the hidden parameters as variables in the GET of the form when the user press the enter/submit button.
The form's current action is "https://example.com". I want to use JavaScript to take the values from the hidden inputs and concatenate them to the form's action so that the information stored outside the form is submitted with the form.
For example, the desired output for the form's action would be "https://example.com?firstParameter=parameter&secondParameter=secondParameter".
Here is what I have so far.
<form action="https://example.com" method="GET">
<input type="text"></input>
<button type="submit"></button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
<script>
function setFormAction() {
var firstParameter= $("#firstParameter").val();
var secondParameter= $("#secondParameter").val();
var url = "https://example.com?";
if(firstParameter!== ""){
url = url + "&firstParameter=" + firstParameter;
}
if(secondParameter!== ""){
url = url + "&secondParameter=" + secondParameter;
}
// form action = url; (Need help here)
}
</script>
A simpler solution might be to add names to the hidden inputs then append them to the form so they get submitted by default process.
HTML
<input type="hidden" id="firstParameter" name="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" name="secondParameter" value="anotherParameter">
JS
$('form').submit(function(){
const $form = $(this);
$('#firstParameter, #secondParameter').each(function(){
if(this.value){
$form.append(this)
}
});
});
Try the following:
document.querySelector('form').setAttribute('action', url);
function setFormAction() {
var firstParameter = $("#firstParameter").val();
var secondParameter = $("#secondParameter").val();
var url = "https://example.com";
if (firstParameter !== "") {
url = url + "&firstParameter=" + firstParameter;
}
if (secondParameter !== "") {
url = url + "&secondParameter=" + secondParameter;
}
document.querySelector('form').setAttribute('action', url);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://example.com" method="GET">
<input type="text" />
<button type="button" onclick="setFormAction()">Test</button>
</form>
<input type="hidden" id="firstParameter" value="parameter">
<input type="hidden" id="secondParameter" value="anotherParameter">
Use encodeURIComponent() in case of user input to sanitise it.
I think you should avoid using form submission if you are not actually submitting a form in the general sense and use a simple button with an event to a function. You can then declare states which do different things with the submission like:
<button id="submit-button">Submit</button>
let state = 'default'
function onFormSubmit()
{
if (state == 'default') doDefaultThings()
else doLessDefaultThings()
}
async function doDefaultThings()
{
//collect necessary data
let url = "https://example.com" //append here
let res = await fetch(url)
//do other things or redirect
}
document.getElementById('submit-button'
.addEventListener('click', onFormSubmit)

How do I change a parameter in a URL upon submitting in JavaScript

I want the following URL to be manipulated and opened in a new tab once I pass the value of email ID and click submit. The searchText in myUrl is the param for email ID:
HTML:
<textarea name="email" id="email" cols="30" rows="10"></textarea>
<button id="myButton">submit</button>
JavaScript:
const myUrl = new URL('something.com?searchText=weijsdo#hotmail.com&site=something&mobileVersion=&locale=&forceAaaApplication=');
you can use this:
HTML:
<button id="myButton" onclick="sbButtonClick()">submit</button>
JavaScript:
const textarea = document.getElementById("email");
let myUrl = null;
function sbButtonClick() {
myUrl = new URL(`something.com?searchText=${textarea.value}&site=something&mobileVersion=&locale=&forceAaaApplication=`);
// do something with myUrl
}
Edit
to get multiple email addresses one of the easiest ways is this way:
const textarea = document.getElementById("email");
function sbButtonClick() {
// split the text by line breaks so each address should be in a separate line
const emailArray = textarea.value.split("\n");
// here you open tab for each email address
for (let address of emailArray) {
window.open(`something.com?searchText=${address}&site=something&mobileVersion=&locale=&forceAaaApplication=`);
}
}

How I can display the form data in the same page without submit the form?

I have a form in HTML and I want to display the form text input data on the same page but before pressing the submit button.
Mean, When Users put the data in the form it must display below the form on same page.
It's mean that I want to show all data before submitting the form.
I know this code will not work as i want
var strText = document.getElementById("textone");
document.write(strText.value);
var strText1 = document.getElementById("textTWO");
document.write(strText1.value);
}
This is how I would do it by directly manipulating the DOM:
const input = document.getElementById('textInput');
const textElement = document.getElementById('displayText');
function updateValue(e) {
textElement.textContent = e.target.value;
}
input.addEventListener('input', updateValue);
<input type="text" id="textInput">
<p>value from input:</p>
<div id="displayText"></div>
There are also javascript libraries like VueJS and ReactJS that can help you do this more easily and efficiently.
This is an example of something like what you would want to do in VueJS: https://v2.vuejs.org/v2/examples/index.html
I've prepared an example of general functioning, I hope you like it. It may not be exactly what you want, but if it is, please tell me.
const myForm = document.getElementById("myForm");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const nameOutput = document.getElementById("nameOutput");
const emailOutput = document.getElementById("emailOutput");
let nameSpan = document.getElementById("name");
let emailSpan = document.getElementById("email");
myForm.addEventListener("submit", e => {
e.preventDefault();
alert(`NAME: ${nameInput.value}, EMAİL : ${emailInput.value}`)
// select name , mail
nameSpan.innerText = nameInput.value;
emailSpan.innerText = emailInput.value;
// clear ınputs
nameInput.value = "";
emailInput.value = ""
})
showData();
function showData() {
nameInput.addEventListener("keyup", e => {
nameOutput.value = e.target.value;
})
emailInput.addEventListener("keyup", e => {
emailOutput.value = e.target.value;
})
}
<form id="myForm">
<input type="text" id="nameInput" placeholder="your name">
<input type="text" id="emailInput" placeholder="your email">
<button type="submit" id="getInputValue"> Get Input Value </button>
</form>
<div id="values" style="margin-top: 100px;">
<input type="text" placeholder="NAME" id="nameOutput">
<input type="text" placeholder="EMAİL" id="emailOutput">
</div>
<div>
<p>Your name : <span id="name"></span></p>
<p>Your email : <span id="email"></span></p>
</div>

How to save data from a form with HTML5 Local Storage?

I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is this:
<form action="http://issuefy.ca.vu/on/login.php" class="form-login" method="post" />
<input name="email" type="email" id="email" required="" placeholder="Email" />
<input name="password" type="password" required="" placeholder="Contraseña" />
</form>
LocalStorage has a setItem method. You can use it like this:
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
When you want to get the value, you can do the following:
var storedValue = localStorage.getItem("email");
It is also possible to store the values on button click, like so:
<button onclick="store()" type="button">StoreEmail</button>
<script type="text/javascript">
function store(){
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
}
</script>
Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.
function persistInput(input)
{
var key = "input-" + input.id;
var storedValue = localStorage.getItem(key);
if (storedValue)
input.value = storedValue;
input.addEventListener('input', function ()
{
localStorage.setItem(key, input.value);
});
}
Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.
var inputElement = document.getElementById("name");
persistInput(inputElement);
Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.
Here,Simple solution using JQUERY is like this..
var username = $('#username').val();
var password = $('#password').val();
localStorage.setItem("username", username);
localStorage.setItem("password", password);
To save the data you have to use
localStorage.setItem method and to get the data you have to use
localStorage.getItem method.
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));

Categories

Resources