Revert innerHTML to default after javascript event - javascript

I have an event listener that takes input from the user and replaces the default text "Your Username" with the user input.
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {username.innerHTML = `${this.value}`}
</script>
If the user backspaces all input, I want the innerHTML of the div to revert to the default (i.e. "Your Username"). How can I do this?

Store the original HTML in initialization, then use it in the change listener if valye is an empty string:
var search = document.querySelector('.search');
var originalHTML = username.innerHTML;
search.addEventListener('input', changeText);
function changeText() {
username.innerHTML = this.value !== '' ? this.value : originalHTML;
}

You need to add a conditional on your eventListener, if input value is null, something like this can do the trick:
<input type="text" class="search">
<div id="username">Your Username</div>
<script>
var search = document.querySelector('.search');
search.addEventListener('input', changeText);
function changeText() {
if(input.value == "") {
username.innerHTML = "Your Username";
} else {
username.innerHTML = `${this.value}`
}
}
</script>

You can add your default text with || operator.
function changeText() {username.innerHTML = `${this.value || 'Your default value'}`}
This will set the text to the default value if this.value is null or undefined or empty.

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Validate empty string in form

I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}
In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">

Trying to get user input to print in a P element

I would like to be able to take user input of a first and last name and upon clicking a submit button update a P element with that first and last name. almost like "Hello firstname lastname!"
The code I've provided is what my click function currently looks like.
function newName(){
var Name = input.value;
if (Name==""){
document.getElementById("hello").innerHTML="Hello" + Name;
}
};
You need to use the trim() to remove blank spaces and then check the condition.
var firstName = document.querySelector('#firstName');
var lastName = document.querySelector('#lastName');
function updateName() {
if (firstName.value.trim() && lastName.value.trim()) {
document.getElementById("hello").textContent = `Hello ${firstName.value} ${lastName.value}`;
}
};
<input type="text" placeholder="Firstname" id="firstName" />
<input type="text" placeholder="Firstname" id="lastName" />
<button onclick="updateName()">Click</button>
<p id="hello">
</p>
function getName(){
let name = input.value;
if (name != ""){
document.getElementById("name").textContent = Hi ${name};
}
}
This would be the most concise way to do it. Since this is simple test function.
function newName(){
if(input.value !== undefined || ""){
document.getElementById("hello").innerHTML= 'Hello '+ input.value }
};
Your code should look like below. JS Fiddle here for quick reference: https://jsfiddle.net/sagarag05/5nteLzm6/3/
function newName(){
let fullName = input.value;
if (fullName != ""){
document.getElementById("fullName2").textContent = `Hello ${name}`;
}
}

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Categories

Resources