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

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());
});

Related

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)

Getting the text within an input box

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..." />

Javascript binding Higher-order function with input onchange not working

My goal is to call a function with a string argument, calling function will return a function which will receive the event object from html input object, and I want to use the string argument in the second function.
const person = {
name:'',
age:''
};
const regForm = (field) => {
console.log('field : ', field);
return event => {
person[field]=event.target.value;
document.getElementById("demo").innerHTML = JSON.stringify(person);
}
};
<input onchange="regForm('name')"/>
<input onchange="regForm('age')"/>
<p id="demo"></p>
The issue is your onchange attribute currently has a string-based value and it is effectively evald when the change event is fired. As #PeterSeliger comments, regForm simply returns a function.
regForm could return anything, and so the default change handler makes no assumptions about your answer. You maybe be expecting that the returned function would be called with the event, but instead the default handler simply discards the value.
One solution would be to use JavaScript's onchange property, instead of HTML's onchange attribute -
const person = {
name:'',
age:''
}
const regForm = field => event =>
person[field] = event.target.value
const form =
document.forms.sample
form.name.onchange = regForm("name")
form.age.onchange = regForm("age")
form.onsubmit = event => {
event.preventDefault()
console.log("Submitted", JSON.stringify(person))
}
<form id="sample">
<input name="name" placeholder="enter your name" />
<input name="age" placeholder="enter your age" />
<input type="submit" />
</form>
And since you are familiar with event delegation, ie event.target, you can remove additional duplication. Looks like regForm just kinda disappeared! -
const data =
{}
const form =
document.forms.sample
form.onchange = event =>
data[event.target.name] = event.target.value
form.onsubmit = event => {
event.preventDefault()
console.log("Submitted", JSON.stringify(data))
}
<form id="sample">
<input name="name" placeholder="enter your name"><br>
<input name="age" placeholder="enter your age"><br>
<input name="foo" placeholder="enter your foo"><br>
<input name="bar" placeholder="enter your bar"><br>
<input type="submit" />
</form>
Output
Submitted {"name":"1","age":"2","foo":"3","bar":"4"}
Functions that take other functions as input and/or return other functions as output are called higher-order functions. There are a variety of terminologies and techniques for dealing with them. For related reading, see What do multiple arrow functions mean?
const preventDefault = f => event =>
( event.preventDefault()
, f(event)
)
const logKeypress = event =>
console.log(event.which)
document
.querySelector('input[name=foo]')
.addEventListener('keydown', preventDefault(logKeypress))
<input name="foo" placeholder="type here to see ascii codes" size="50">
In oder to come close to what the OP might have wished to achieve, one should break down the code into the state-change handling task(, maybe a render task) and the listener-initializing task ...
const person = {
name:'',
age:''
};
function renderPersonStateChange(personReference, key, value) {
personReference[key] = value;
document.body.querySelector('#demo').textContent = JSON.stringify(personReference);
}
function handleTextInputStateChange(evt) {
const elm = evt.currentTarget;
const key = elm.name;
renderPersonStateChange(person, key, elm.value);
}
// initialize event listeners
document.body.querySelectorAll('input').forEach(elm =>
elm.addEventListener('change', handleTextInputStateChange, false)
);
<input name='name' placeholder="enter person's name"/>
<input name='age' placeholder="enter person's age"/>
<p>
<code>
<pre id="demo">
</pre>
</code>
</p>
If one wishes tobind the reference that's state should be changed, the above code then slightly alters (only for the change-handler and the event-initialization parts) towards ...
const person = {
name:'',
age:''
};
function renderPersonStateChange(personReference, key, value) {
personReference[key] = value;
document.body.querySelector('#demo').textContent = JSON.stringify(personReference);
}
function handleStateChangeForBoundPerson(evt) {
const personReference = this;
const elm = evt.currentTarget;
const key = elm.name;
renderPersonStateChange(personReference, key, elm.value);
}
// initialize event listeners
document.body.querySelectorAll('input').forEach(elm =>
elm.addEventListener('change', handleStateChangeForBoundPerson.bind(person), false)
);
<input name='name' placeholder="enter person's name"/>
<input name='age' placeholder="enter person's age"/>
<p>
<code>
<pre id="demo">
</pre>
</code>
</p>

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>

get an element id and then use it in a getElmentByID to trigger a function on click

function getId(e){
var xid = e.target.id;
console.log(xid);
}
<form onclick="getId(event)">
<label for="name" id="I am an Span">Nombre</label><br>
<input type="text" name="name" id="tbx_nombre"> <br>
<span id="nombre"></span> <br>
</form>
<div id="result"></div>
When the user click on a texbox the function gets the id of the element, then the deleteSpan method is call with the splitted id of the textbox which is now the id of the span to be changed to an emply string.
I get this error Cannot set property 'onclick' of null at getId
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name"></span>
...MORE INPUTS AND SPAN TAGS...
</form>
JS
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
document.getElementById(xid).onclick = function(){deleteSpan(spanId)};
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
You are getting that error because when you try to set the click handler on the span by ID, you don't currently have the correct ID. It's null, because the click target is currently the form (which doesn't have an ID) instead of the input.
As others mentioned, the click event listener should be attached to the input.
But you also don't need to set a separate click handler within getId--you can just call deleteSpan in the getId function. In fact, if you set it inside another handler like you have, it won't work the first time (unless that's your desired outcome).
function getId(e){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form>
<input onclick="getId(event)" type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>
onclick attribute event handler should be at input instead of form
<form>
<input type="text" name="name" id="tbx_name" onclick="getId(event)"><br>
<span id="name"></span>
</form>
or even better, use addEventListener for the inputs which have id format as tbx_{{value}}
var allInputs = document.querySelectorAll("input[id^='tbx_']");
allInputs.forEach( s => s.addEventListener( "click", e => getId ));
You can invoke above code when the form has loaded (at document load or window load).
You have to set the attribute onclick in input instead of form to get the expected id. Otherwise you have to check if the target node is INPUT or not:
function getId(e){
if(e.target.nodeName == 'INPUT'){
var xid = e.target.id; // => tbx_name
var spanId = xid.split("_").pop(); // =>name
deleteSpan(spanId);
}
}
function deleteSpan(spanId){
document.getElementById(spanId).innerHTML = "";
}
<form onclick="getId(event)">
<input type="text" name="name" id="tbx_name"><br>
<span id="name">Span</span>
</form>

Categories

Resources