Using pure javascript to prefill a textbox with a url hash - javascript

I have a textbox on a web page. I would like to get the value of a URLs hash e.g. 12345 and place it as the value of the textbox upon loading the page (if there is a value), otherwise, I would like the textbox to remain blank.
I have tried using this code:
var hash = window.location.hash.substr(1);
function onoff(){
// pre-fill chat id textbox
if(hash){
var hash_value = window.location.hash.replace('#','');
document.getElementById("chat").value = hash_value;
} else {
document.getElementById("chat").value = '';
}
}
And in the html code(I am having trouble in calling the function).
<input type="text" id="chat" maxlength="5" required="">
If I were to change the value of the hash, would it be possible to have this fill the text box on load?

Sure thing! Just pass your function into window.onload:
var hash = window.location.hash.substr(1);
window.onload = function onoff(){
// pre-fill chat id textbox
if(hash){
var hash_value = window.location.hash.replace('#','');
document.getElementById("chat").value = hash_value;
} else {
document.getElementById("chat").value = '';
}
}
<input type="text" id="chat" maxlength="5" required="">
Hope this helps! :)

Execute your function on DOMContentLoaded. Note that this function can be limited to this:
function onoff(){
document.getElementById("chat").value = window.location.hash.substr(1);
}
document.addEventListener("DOMContentLoaded", onoff);
To also capture pure changes to the hash (in which case the page is not reloaded), also capture the corresponding hashchange event:
window.addEventListener("hashchange", onoff);

Related

i try to make a form in NodeJs for searching a user in mongodb by telephone number using query routing, i don't know why this not working?

What is the wrong with this code? I got the exactly mobile number on the console but not on query routing on /search_user?mob ?
<input type="tel" name="message" id="mobile_input" value="">
<!--getting mobile no. from the input tag -->
<script type="text/javascript" defer>
e => {
e.preventDefault();
var mobInput = document.querySelector('#mobile_input');//get the input tag.
var moby = mobInput.value;//get mobile no.
console.log(moby);//be sure from the variable mob
mobInput.value='';//reset the input tag.
return moby;
}
</script>
<!-- query routing on /search_user?mob -->
Search
I tried something like this and this seems to work.
<form>
<input type="tel" name="message" id="mobile_input">
<button type="submit" onclick="handleSearch(document.getElementById('mobile_input').value)">Search</button>
</form>
<!--getting mobile no. from the input tag -->
<script type="text/javascript" defer>
// const handleChange = (value) => {
// var mobInput = value
// console.log(mobInput)
//
// }
const handleSearch = (input) => {
var searchValue = input;
console.log("This is the search value " + searchValue)
var url = '/search_user?mob=' + searchValue;
console.log(url)
window.location.href = url;
}
</script>
Explanation: I changed the a href element for a button element. Every time the button is clicked (onclick) the function handleSearch is called. This function takes as input the value of the input element with ID "mobile_input". Of course, you can clean up the function a bit more. After merging the url basis ('/search_user?mob=') with the input value (searchValue), the handleSearch function should redirect to the url (calling window.location.href). This last one you can of course change for the correct call to the server. Hope this helps.
Side note: you will see that there is a commented-out handleChange function. You could call this function in the input element to keep track of your changes in the console. this function is called using onChange, just like you use onClick with the search button.
For more info:https://www.w3schools.com/jsref/event_onchange.asp

HTML Text Input Value not changing in Backend JavaScript

I am new to web development . I have a question I am trying to build a website that takes input on the front end from the HTML page and actively changes the value on the backend javascript file . The functions I have on the backend rely on the front end input . The input never changes it just stays the default value "google.com". For Reference here is some code of what I am trying to accomplish .
HTML WebPage
<input type="text" id="input" value="google.com" placeholder="somewebsite.com">
Backend JavaScript File
var ajaxWebSiteValue = document.getElementById("input");
function getURL(){
var URL = "http://" + ajaxWebSiteValue.value ;
return URL;
}
It not clear what exactly you want to achieve here because heading, description and code snippet looks contradictory to each other.
1.If you are changing the input value on UI but not getting updated value in backend then use
function getURL(){
var ajaxWebSiteValue = document.getElementById("input");
var URL = "http://" + ajaxWebSiteValue.value ;
return URL;
}
2.If you want to change the value of input from backend.
function getURL(){
var ajaxWebSiteValue = document.getElementById("input");
ajaxWebSiteValue.value = "http://" + ajaxWebSiteValue.value ;
}
Also make sure that you are calling getURL() function from somewhere.
is that is what you want to achive??
var ajaxWebSiteValue;
function myFunction(){
ajaxWebSiteValue = document.getElementById('input').value;
document.getElementById("ajaxWebSiteValue").innerText = ajaxWebSiteValue;
document.getElementById("returnedURL").innerText = getURL();
}
function getURL(){
var URL = "http://" + ajaxWebSiteValue;
return URL;
}
<input type="text" id="input" value="google.com" placeholder="somewebsite.com" />
<p id="ajaxWebSiteValue"></p>
<p id="returnedURL"></p>
<button id="change" onclick="myFunction()">change</button>

How can I make a text field for a JavaScript function?

I THINK i have managed to write a script. I just can not make a textfield in HMTL to enter the missing data. It it supposed to receive the keyword from a text field on submit click and navigate to the URL.
I have tried multiple ways of forms and everything. Should have installed VB.net and this would have been done in 5 min.
function urlMaker(keyword) {
var base = "https://www.example.com/list.php?q=";
var ending = "&dhd=1&hdd=low&dtt=list";
var url;
url = base + keyword + ending;
window.location.assign(url);
}
In short words:
I need to know how to create a HTML page with a textfield and a submit button. When I submit it takes the text from the field and run the function and feeds it with the keyword from the textfield. When function has ran it redirects browser.
I'm guessing you have a form like this.
Just attach a submit event-listener to it:
document.querySelector("#search").addEventListener("submit", urlMaker)
function urlMaker(event) {
let keyword = document.querySelector("#keyword").value;
let base = "https://www.example.com/list.php?q=";
let ending = "&dhd=1&hdd=low&dtt=list";
let url;
event.preventDefault();
url = base + keyword + ending;
window.location.href = url;
}
<form id="search">
<input type="text" id="keyword" />
<button type="submit">Search</button>
</form>

How to remember form data that has not been submitted?

How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});

Transferring HTML element values, to other files

Let's say I have this piece of code from first.html
<input type="text" id="name">
Go to next page
How can I make it that when you go to second.html, javascript alerts the value of [name] from first.html OR the html adds an h1 tag with the value of [name] from first.html
You can use document.getElementById() function to get input and access it's value property to read what was entered there.
The onclick attribute on your anchor element will execute a custom function which will take the href property of the anchor and append the url-encoded value of the input field.
Then it will go to that new URL.
The return false ensures that built-in href event does not execute.
function link(anchor) {
var name = document.getElementById("name").value
var url = anchor.href + "?name=" + encodeURIComponent(name);
window.location.href = url;
}
<input type="text" id="name">
Go to next page
To read the passed in variable on the receiving page, use the technique described in this SO post:
How can I get query string values in JavaScript?
you could use onclick function on anchor tag.
<input type="text" id="name">
<a onclick="goToNextPage()">Go to next page</a>
<script>
function goToNextPage()
{
var value = document.getElementById('name').value;
window.location.href="second.html?name="+value;
}
</script>
Or you could use form.submit() to post the form values to request.
As HTML is only markup language, not programming language. So, you would need either php/ javascript to fetch that value on second page.
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
and then call that function in your second page as.
<script type="text/javascript">
document.write(qs("name"));
</script>

Categories