I'm trying to make a mailto: link change based on a text input and a button.
I managed to make it work without a href, with just plain text from a paragraph, but i can't manage to make it work on the href.
I get either [object HTMLInputElement] or undefined
HTML
<input type="text" id="email_input"><br>
<span id="links"><a id="email">email</a></span><br>
<input type="button" id="btn" value="Submit"><br>
JAVASCRIPT
var emailIN = document.getElementById('email_input');
var emailOUT = document.getElementById('email');
var emailLink = "mailto:"+emailOUT;
btn.onclick = function(){
/* addressOUT.textContent = addressIN.value; */
/* emailOUT.setAttribute("href",emailIN); */
/* emailOUT.textContent = "mailto:"+emailIN.value; */
/* $("a#email").attr('href','mailto:'+emailIN); */
/* document.querySelector("#email").href=emailLink; */
document.getElementById("email").value = "mailto:"+emailIN
emailOUT.href = "mailto:"+emailIN;
}
Here is an example.
document.getElementById('btn').addEventListener('click', function() {
const emailInput = document.getElementById('email_input');
const emailLink = document.getElementById('email');
const href = emailInput.value != '' ? 'mailto:' + emailInput.value : '';
if (href.length > 0) {
emailLink.setAttribute('href', href);
console.log(`Link href is change to ${href}`);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="my-5">
<div class="mb-3">
<label for="email_input" class="form-label">Email address</label>
<input class="form-control" id="email_input" placeholder="name#example.com" />
</div>
<div class="mb-3">
<a id="email" href="">Email Link</a>
</div>
<div class="mb-3">
<button type="button" id="btn" class="btn btn-primary btn-md">Submit</button>
</div>
</div>
</div>
</body>
</html>
Related
I'm trying to make a menu for a Memory Game type game. I created the html page that contains a form consisting of 2 radio buttons with different values. On the submit input I called my function from the javascript file. And in the js file I created an if else function to redirect me, but it doesn't work.
Code:
`
let button = document.getElementById("button");
let solo = document.getElementById("solo");
let multiplayer = document.getElementById("multiplayer");
let level1 = document.getElementById("3x4");
let level2 = document.getElementById("4x4");
let radio1 = document.getElementsByName("radio1");
let radio2 = document.getElementsByName("radio2");
// button.addEventListener("click", gameMenu);
function gameMenu() {
if ((radio1.value = "solo") && (radio2.value = "3x4")) {
// location.href = "sg_34.html";
console.log("solo/3x4");
}
else if ((radio1.value = "solo") && (radio2.value = "4x4")) {
// location.href = 'sg-44.html';
console.log("solo/4x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "3x4")) {
// location.href = 'mp-34.html';
console.log("mp/3x4");
}
else if ((radio1.value = "multiplayer") && (radio2.value = "4x4")) {
// location.href = "mp-44.html";
console.log("mp/4x4");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<link rel="stylesheet" href="./css/styleIndex.css">
<title>Memorizer JS</title>
</head>
<body>
<div class="container">
<h1>Memorizer JS</h1>
<form class="form menu">
<section class="game cf">
<h2>Choose game mode:</h2>
<input type="radio" name="radio1" id="solo" value="solo">
<label class="solo-label four col" for="solo">Solo</label>
<input type="radio" name="radio1" id="multiplayer" value="multiplayer">
<label class="multiplayer-label four col" for="multiplayer">With a friend</label>
</section>
<section class="level cf">
<h2>Level:</h2>
<input type="radio" name="radio2" id="3x4" value="3x4">
<label class="3x4-label four col" for="3x4">3x4</label>
<input type="radio" name="radio2" id="4x4" value="4x4">
<label class="4x4-label four col" for="4x4">4x4</label>
</section>
<input class="submit" id="button" type="submit" value="Play" onclick="gameMenu()">
</form>
</div>
<script src="./scripts/index.js"></script>
</body>
</html>
`
Code pen: https://codepen.io/sebastian-mihai-ciuc/pen/BaVagNM
I created the conditions in an if else structure to check the values in the radio buttons. I expected it to redirect me to other pages or at least display the cases in the console.log.
You should remove form tags for not reloading the window
Heyy,
i'm a beginner in writing with java script and i'm trying to copy Instagram, soo I need help in form and validation stuff and I also want to save it with local Storage.
I can't find the Problem in my Code and I don't know how to write the local Storage Code.
scripts.js
const VornameInput = document.getElementById("Vorname-input");
const NachnameInput = document.getElementById("Nachname-input");
const GeburtstagInput = document.getElementById("Geburtstag-input");
const ueberMichInput = document.getElementById("ueber-mich");
const SpeicherButton = document.getElementById("enter-button");
const EmailInput =document.getElementById("email-input");
const EingabeInput = document.getElementById("Eingabe");
SpeicherButton.addEventListener("click", enterEvent);
const Vorname = VornameInput.value;
const Nachname = NachnameInput.value;
const Geburtstag = GeburtstagInput.value;
const ueberMich = ueberMichInput.value;
const Email = EmailInput.value;
function felderInKonsoleAusgeben () {
console.log("Vorname:", Vorname);
console.log("Nachname:", Nachname);
console.log("Geburtstag:", Geburtstag);
console.log("UeberMich:", ueberMich);
console.log("Email:", EmailInput);
}
function validierung(Vorname,Nachname,Geburtstag) {
if (VornameInput.value == "" || NachnameInput.value == "" || isNaN(Number(GeburtstagInput.valueAsNumber))){
alert ("Bitte fülle alle Felder aus! ");
return false;
}
else
alert ("Eingaben wurden gespeichert");
return true; }
function validierungEmail (EmailInput){
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (input.value.match(validRegex)) {
alert("Gültige Email Adresse!");
return true;
} else {
alert("Ungültige Email Adresse!");
return false; }
function enterEvent(evt) {
evt.preventDefault();
felderInKonsoleAusgeben();
validierung(Vorname, Nachname, Geburtstag);
validierungEmail(EmailInput);
}
html
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Das wird einmal ein Instagram Clone" />
<meta name="keywords" content="Instagram, Instagram 2.0, Clone" />
<meta name="author" content="Emily Schlachter" />
<link rel="stylesheet" href="css/style.css" />
<script src="scripts.js" defer></script>
<title>Instagram 2.0</title>
</head>
<body>
<header>
<div > <a href="instagram-clone_schlachter.html"> <h1>Gramml</h1> </a ></div>
</header>
<ul id="navibereich">
<li id="navi01"> <h2>Mein Profil </h2> </li>
<li id="navi02"> <h2>Entdecken</h2> </li>
<li id="navi01"> <h2>Upload Picture</h2> </li>
</ul>
<div class="label">
<label>Suche:</label>
<input type="text"/>
</div>
<main>
<!-- Eingabefeld -->
<div class="Eingabe" id="Eingabe">
<div class="field">
<input id="Vorname-input" type="text" name="vorname-input" placeholder="Vorname" />
</div>
<div class="field">
<input id="Nachname-input" type="text" name="Nachname-input " placeholder="Nachname" />
</div>
<div class="field">
<input id="email-input" type="text" name="email-input" placeholder="Email-Adresse" />
</div>
<div class="field">
<input id="Geburtstag-input" type="date" name="Geburtstag-input" placeholder="Geburtsdatum" />
</div>
<label>Über mich: <br> </label>
<textarea name="ueber-mich" id="ueber-mich" cols="40" rows="5" maxcols="35" placeholder="Über mich:" > </textarea>
</div>
<div class="Formelles">
<p> <input type="checkbox" name="AGB" value="News"> Datenschutzerklärung und AGB akzeptieren. </p>
</div>
<button id="enter-button" class=" button" type="submit">
Speichern
</button>
</main>
</body>
</html>
I just want to get a validation formand to save the Input in local Storage.
Thanks for your help!
You can add all needed information into an obejct like
const personInfo = {
"vorname": VornameInput.value,
"nachname": ...,
"geburtstag": ...,
"uebermich": ...,
"email": ...
}
Then you can store this object with a key in the local storage with
localStorage.setItem('personInfo',JSON.stringify(personInfo));
To get it back use
const pInfo = localStorage.getItem('personInfo');
Have a look here https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage to learn more about localstorage
I am making a note-taking app and I want 2 text areas to when you type in one the other changes to
what you are doing in one. I want so when I change the title of the page it will change in other places on the page. I'll provide my current code what my page looks like (I want the change to be with my Unititled and an area next to the dropdown arrow) and what I want it to do, I've tried change and input events and I can't seem to figure it out.[My Current Site][1]
What I Want - https://share.vidyard.com/watch/Wj6uTmEiB9LR8iiZy7sVf9
[1]: https://i.stack.imgur.com/3vzEB.png
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Study App</title>
<link rel="stylesheet" href="study.css" />
<link href="https://unpkg.com/boxicons#2.0.7/css/boxicons.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/5.15.1/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-
8"></script>
</head>
<body>
<script src="study.js"></script>
<div class="dropdown">
<nav><label for="touch"><span>Settings</span></label>
<input type="checkbox" id="touch" />
<ul class="slide">
<li><a>
<div class="dark"><button onclick="myFunction()">
<input class="toggle" type="checkbox" /></button></div>
</a></li>
<li></li>
</ul>
</nav>
</div>
</div>
<div class="arrowdown">
<input type="checkbox" id="myCheckbox" onchange="rotateElem()" checked><i class="fas fa-angle-
right dropdown"></i></button>
<div class="pages">
Add Page
</div>
</div>
</div>
<script type="text/javascript">
var checkBox = document.getElementById("myCheckbox");
function rotateElem() {
if (checkBox.checked == false) {
document.querySelector('.fas.fa-angle-right.dropdown').style.transform = 'rotate(90deg)';
} else {
document.querySelector('.fas.fa-angle-right.dropdown').style.transform = 'rotate(0deg)';
}
}
</script>
<div class="tabs"></div>
<div class="sidebar">
<div class="sidebar-top">
<h1><span class="study">Study</span><span class="app">App</span></h1>
</div>
<div class="title">
<textarea id="shortInput" spellcheck="true" placeholder="Untitled" cols="30" rows="1">
</textarea>
</div>
<div class="textbox">
<textarea id="longInput" spellcheck="true" placeholder="Start typing..." cols="30" rows="10"></textarea>
</div>
<script type="text/javascript">
$('.pages').hide();
$(document).ready(function() {
$('input').click(function() {
$('.pages').slideToggle();
});
});
</script>
<script src="study.js"></script>
</body>
</html>
One possible approach would be to store the synchronised value in a variable, and add event listeners to each element for any changes. Then update the value of each element with the new value when the change occurs.
// Store the synchronised content
let value = ''
// Add change listeners to each element
const elements = document.querySelectorAll('.synced')
for (let i = 0; i < elements.length; i++) {
// Different browsers will work better with different events
// but there's no problem with listening for multiple
elements[i].addEventListener('change', handleChange)
elements[i].addEventListener('input', handleChange)
elements[i].addEventListener('keyup', handleChange)
}
// When a change occurs, set the value of all the synchronised elements
function handleChange(e) {
value = e.target.value
for (let i = 0; i < elements.length; i++) {
elements[i].value = value
}
}
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
jQuery version:
// Store the synchronised content
let value = ''
// Get all the of the relevant elements
const elements = $('.synced')
// Different browsers will work better with different events
// but there's no problem with listening for multiple
elements.on('change input keyup', function() {
value = $(this).val()
elements.val(value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
<textarea class="synced"></textarea>
I can't clear up my input field even tho i followed a tutorial step by step , i'm making this to do list and I want the input field to be clear anytime i submit a new to do . so what is wrong with my code ?
ps : i tried to clear the cache and nothing
let addButton=document.getElementById('addButton');
let toDoContainer = document.getElementById('ToDoContainer');
let inputField = document.getElementById('text');
//event listeners
addButton.addEventListener('click',addTodo);
//functions
function addTodo(event,title){
event.preventDefault();
//create the to do
let toDoDiv = document.createElement('div');
toDoDiv.classList.add('todo');
const newToDo =document.createElement('p');
newToDo.innerHTML=inputField.value;
newToDo.classList.add('todo-item');
toDoDiv.appendChild(newToDo);
toDoContainer.appendChild(toDoDiv);
//check mark button
const completedButton = document.createElement('button');
completedButton.innerHTML="success";
completedButton.classList.add("complete-btn");
toDoDiv.appendChild(completedButton);
//check delete button
const trashButton = document.createElement('button');
trashButton.innerHTML="delete";
trashButton.classList.add("complete-btn");
toDoDiv.appendChild(trashButton);
//append todo
toDoContainer.appendChild(tododiv);
inputField.value= "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>to do list </title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<header>
<h1>This is your to do list </h1>
<div class="input">
<input type="text" placeholder="what to do ...?" id="text">
<input type="button" value="add" id="addButton">
</div>
</header>
<div id="ToDoContainer">
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
here is a screenshot
sonEtLumiere is right, you have a typo. It should be:
toDoContainer.appendChild(toDoDiv);
Your variable is called toDoDiv, you have an error in this line (penultimate line):
toDoContainer.appendChild(tododiv);
This will work:
toDoContainer.appendChild(toDoDiv);
I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.
I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName){
if (ingCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName){
if (dirCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
<!-- Required program scripts -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Style Sheets-->
<link rel="stylesheet" href="/styles/navBarStyle.css">
<link rel="stylesheet" href="/styles/myRecipesStyle.css">
<link rel="stylesheet" href="/styles/createRecipeStyle.css">
<link rel="stylesheet" href="/styles/errorMessageStyle.css">
</head>
<body>
<!-- Background image -->
<img id="background" src="/images/foodBackground.jpg" alt="">
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<%- include('../_partial/_messages'); -%>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/>
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
<!-- Required scripts to run app -->
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/errorMessageControl.js"></script>
</html>
Thanks for any help.
In your code you are using getElementById but there is no id called directionSet its a class.
You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.
In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName) {
if (ingCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName) {
if (dirCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
</head>
<body>
<!-- Background image -->
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
</html>