How can I have 2 actions within one form, one button? - javascript

I have a html form and one 'submit' button. I have two tabs that I want to do different things. One tab when submitting should go to one link, whereas the other tab should take the form to another link.
Here is my fiddle to show what I am working with :
https://jsfiddle.net/4s8qevz7/
I have tried putting in actions to go to for, (as of right now) generic links. But no luck.
<form style="margin-top:40px;" id="search-box" action="">
<div class="search-tab" data-search-type="catalog" action="http://catalog.com/" onClick="changePlaceholder(this)">Catalog </div>
<div class="search-tab selected" data-search-type="website" action="https://www.google.com/"onClick="changePlaceholder(this)">Website </div>
My expected results would be depending on the active tab, the form would respect that when the go button is clicked.

1) call preventDefault() in the form submit method
2) get active tab from event.target
3) call form.submit with the correct options based on the active tab.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.tab {
overflow: hidden;
/* Style the buttons that are used to open the tab content */
.tab button {
background-color: #f1f1f1;
float: left;
border: solid 1px #ccc;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
#search-text-form{
margin-top: 2rem;
}
#current-action-section{
margin-top: 2rem;
}
</style>
<script>
function openTab(evt, tabName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</head>
<body>
<section id="search-bar">
<div class="tab">
<button id="openByDefault" class="tablinks" onclick="openTab(event, 'Catalog')" data-action="http://catalog.com">Catalog</button>
<button class="tablinks" onclick="openTab(event, 'Website')" data-action="https://www.google.com">Website</button>
</div>
<div id="Catalog" class="tabcontent">
<h3>Catalog</h3>
<p>Catalog</p>
</div>
<div id="Website" class="tabcontent">
<h3>Website</h3>
<p>Website</p>
</div>
<form id="search-text-form">
<input type="text" id="search-text" placeholder="Search Website"><button id="go">Submit</button>
</form>
<script>
const form = document.getElementById('search-text-form');
form.onsubmit = e => {
e.preventDefault();
const activeTab = document.getElementsByClassName('tablinks active')[0];
const {action } = activeTab.dataset;
console.log(action);
document.getElementById('current-action').innerHTML = `Current Action: ${action}`;
// when you're ready, call whatever api is usually called in the submit function
}
document.getElementById("openByDefault").click();
</script>
</section>
<section id="current-action-section">
<h3 id="current-action"></h3>
</section>
<script>
var emailAddress = "jimmyleespann#outlook.com";
//email;
var text = "https://docs.google.com/forms/d/e/1FAIpQLSdFDFGDFVDGGjdfgdfgdx8P4DOw/viewform?usp=pp_url&entry.745541291="+room+"&entry.1045781291="+rr+"&entry.1065046570=4&entry.1166974658="+hr+"&entry.839337160="+spO2+"&entry.103735076=&entry.515842896="+e1Name+"&entry.631828469="+e1Reps+"&entry.1814472044="+e2Name+"&entry.905508655="+e2Reps+"&entry.1234390406="+isVol+"&entry.197252120="+education+"&entry.1748983288="+notes; var message = 'Dear ' + patientName + '\n\n' + "Thank you for submitting.\n\nHere is an autofill link: " + text; var subject = 'Submission Confirmation'; GmailApp.sendEmail(emailAddress, subject, message);
</script>
</body>
</html>
Updated JSFiddle code that I couldn't get to show up for OP:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
const state = {
targetUrl: 'https://www.google.com' // because this is the default selected tab
}
function setTargetUrl(url){
state.targetUrl = url;
}
function changePlaceholder(div) {
const searchTextEl = document.getElementById("search-text")
searchTextEl.placeholder = `Search ${div.innerHTML.trim()}`;
setTargetUrl(div.dataset.action);
}
function doSubmit(){
console.log('submitForm', state);
}
</script>
</head>
<body>
<form style="margin-top:40px;" id="search-box" onsubmit="submitForm">
<div
class="search-tab"
data-search-type="catalog"
data-action="http://catalog.com/"
onclick="changePlaceholder(this)">
Catalog
</div>
<div
class="search-tab selected"
data-search-type="website"
data-action="https://www.google.com/"
onclick="changePlaceholder(this)">
Website
</div>
<script>
</script>
<a href="t$003f/" target="_blank" style="text-decoration:none">
<div class="search-tab-link"> Login </div>
</a>
<div class="search-tab-content">
<div class="search-bar">
<input type="text" id="search-text" placeholder="Search Website" name="q">
<span id="search-text-icon" onclick="doSubmit()" style="cursor:pointer;">
<img
alt="go"
title="Search"
src="img/search.png"
style="height:1.2rem;"
>
</span>
</div>
<div id="search-old-catalog">
<a href="http://.com/" target="_blank">
Old Catalog
</a>
</div>
</form>
</body>
</html>

I couldn't get your jsfiddle to work, but here's an example of "2 actions within one form, one button." If the checkbox is checked, the action goes to bing.com, otherwise it goes to Wikipedia. Your if statement can use currentTarget as Dov Rine suggested, instead of a checkbox to dynamically change the form action.
function ActionSelect() {
if (document.getElementById('bing').checked) {
document.getElementsByTagName('form')[0]['action'] = 'https://bing.com';
}
}
<form style="margin:40px 50px;" action="https://www.wikipedia.org">
Choose your form action:<br/>
<input type="checkbox" id="bing"> Bing
<p>
<button type="submit" onclick="ActionSelect()">Submit</button>
</p>
</form>

Related

Can I install SPIFFS for Wemos D1 Mini Lite (ESP8285 chip) to use JS, HTML and CSS files as a stand alone webserver

I am looking to create a standalone webserver using the Wemos D1 Mini Lite (this is the only wifi microcontroller I have and cant afford a different one atm).
I know SPIFFS works with ESP32 chips, but can I use it with ESP8285 chips?
Looking to have HTML and CSS for the webserver, with JS scripts to run functions (At the moment only functionality is turning LEDs off and on), all uploaded to the Wemos and run from that.
HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./skeleton.css">
<link rel="stylesheet" href="./theme.css">
<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>Document</title>
</head>
<body>
<div class = "mainDiv border" >
<div class = "headingDiv border">
<h3 id = "Header"> LED ON AND OFF </h3>
</div>
<div class = "checkmarkDiv border">
<div class = "row">
<label for ="colour_red">RED LED</label>
<input type = "checkbox" id = "colour_red">
</div>
<div class = "row">
<label for ="colour_yellow">YELLOW LED</label>
<input type = "checkbox" id = "colour_yellow">
</div>
<div class = "row">
<label for ="colour_green">GREEN LED</label>
<input type = "checkbox" id = "colour_green">
</div>
</div>
<div class = "buttonDiv border">
<button class = "button-primary" id = "button_ToggleLED"> Turn LED: ON </button>
</div>
</div>
</body>
<script src = "./mainJS.js"></script>
</html>
JS CODE
const button_LED = document.getElementById( "button_ToggleLED" )
const cb_red = document.getElementById ( "colour_red" )
const cb_yellow = document.getElementById( "colour_yellow" )
const cb_green = document.getElementById( "colour_green" )
let clickCheck = false
button_LED.addEventListener( "click", (event) => {
//consoleLEDStatus()
if (clickCheck) {
button_LED.innerHTML = "Turn LED: ON"
turnOFFLED()
}
else if (!clickCheck) {
button_LED.innerHTML = "Turn LED: OFF"
turnONLED()
}
clickCheck = !clickCheck
})
// A quick function you can run to check in dev console the status of LED
function consoleLEDStatus() {
console.log(`LED Status:
RED: ${cb_red.checked}
YELLOW: ${cb_yellow.checked}
GREEN: ${cb_green.checked}`)
}
function turnOFFLED() {
// Insert function to turn off LED
}
function turnONLED() {
// Insert function to turn on LED
}
CSS CODE
/* Test class for checking Div borders. Uncomment to see them*/
/*
.border{
border: black 2px solid;
}
*/
.mainDiv{
margin-left: 20%;
margin-right: 20%;
padding: 10px;
}
.checkmarkDiv{
padding: 10px;
}
.buttonDiv{
padding: 10px;
}
.headingDiv{
padding: 10px;
}
#Header{
}
#button_ToggleLED{
width: 200px;
float: center;
}
SPIFFS has been replaced with LittleFS (Little File System) and it works on EPS8266, See LittleFS for more details.
The code example for using LittleFS to serve webpage can be found at FSBrowser example. It is a quite comprehensive example, you probably only need to implement part of it.

Trouble adding active class to buttons on website

I am trying to add an active class to my buttons so that when you click on them the hover animation would stay on the active button. It seems like something in my javascript does not follow through with my call to add the active class to whatever element I put it on. pls help thnx ^_^
https://jsfiddle.net/purpkev/pf1vzx2t/7/
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ukiyo Sushi ツ</title>
<link href = "/style.css" type = "text/css" rel = "stylesheet">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans&display=swap" rel="stylesheet">
<script src = "/script.js"></script>
</head>
<body>
<!--<div class = "hero active">
<div class = "hero1">
<div class = "hero2">-->
<header id = "bg">
<nav class = "navbar">
Ukiyo Sushi ツ
<ul>
<li>About us</li>
<li>Menu</li>
<li>Services</li>
<li>Contact</li>
</ul>
</nav>
<div class = "sushiPlatter">
<h2 id = "caption">Chef's Special Sushi Platter</h2>
<div class = "dots">
<button class = "dot" onclick = "imgslider(1)"></button>
<button class = "dot" onclick = "imgslider(2)"></button>
<button class = "dot" onclick = "imgslider(3)"></button>
</div>
View Menu
</div>
</header>
<!--</div>
</div>
</div>-->
<section class = "idkYet">
<div>
<span>hello I am filler content</span>
</div>
</section>
</body>
</html>
CSS:
.dots{
display: flex;
flex-direction: column;
align-self: flex-end;
margin: 0 1em;
}
.dot{
display: inline-block;
cursor: pointer;
height: 15px;
width: 15px;
background-color: transparent;
border: solid 2px white;
border-radius: 50%;
margin: .2em;
transform: scale(.75);
outline-color: white;
}
.active{
transform: scale(1);
opacity: .25;
}
.dot:hover, .dot:hover, .dot:hover{
transform: scale(1);
opacity: .25;
transition: transform 1s ease-in;
transition: opacity .5s;
}
Javascript:
function buttonClick(){
var button = document.getElementsByClassName("dots");
var dot = button.children;
dot[0].classList.add("active");
for(var i = 0; i < dot.length; i++){
dot[i].addEventListener("click", function(){
var active = document.getElementsByClassName("active");
active[0].className = active[0].className.replace("active", "");
this.className += "active";
});
}
}
edit:
I have tried suggestions in the comments but the active class still does not get added to the active button, here is what my code looks like:
function buttonClick(){
var button = document.getElementsByClassName("dots");
var dot = button[0].children;
dot[0].classList.add("active");
for(var i = 0; i < dot.length; i++){
dot[i].addEventListener("click", function(){
var active = document.getElementsByClassName("active");
active[0].className = active[0].className.replace("active", "");
this.className += "active";
});
}
}
document.getElementsByClassName returns array.
Use button[0].children or button = document.getElementsByClassName("dots")[0]
I am not very good at vanilla javascript. I will do the equivalent of jQuery as follows
$('.dots').on('click', '.dot', function(e) {
el = $(this);
el.parents('.dots').find('dot').removeClass('active');
el.addClass('active');
});
Looks like you're adding eventListeners again and again.
Maybe try this approach, where you send the button element to the function using the "this" keyword....
(see fiddle: https://jsfiddle.net/sre1dua9/1/ )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ukiyo Sushi ツ</title>
<link href = "/style.css" type = "text/css" rel = "stylesheet">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans&display=swap" rel="stylesheet">
<script src = "/script.js"></script>
</head>
<body>
<!--<div class = "hero active">
<div class = "hero1">
<div class = "hero2">-->
<header id = "bg">
<nav class = "navbar">
Ukiyo Sushi ツ
<ul>
<li>About us</li>
<li>Menu</li>
<li>Services</li>
<li>Contact</li>
</ul>
</nav>
<div class = "sushiPlatter">
<h2 id = "caption">Chef's Special Sushi Platter</h2>
<div class = "dots">
<button class = "dot" onclick="window.imgslider(this, 1)"></button>
<button class = "dot" onclick="window.imgslider(this, 2)"></button>
<button class = "dot" onclick="window.imgslider(this, 3)"></button>
</div>
View Menu
</div>
</header>
<!--</div>
</div>
</div>-->
<section class = "idkYet">
<div>
<span>hello I am filler content</span>
</div>
</section>
</body>
</html>
Then just track the last button clicked:
var lastDot = null;
window.imgslider = function(elem, x)
{
var bg = document.getElementById("bg");
var dot = document.getElementsByClassName("dot");
var caption = document.getElementById("caption");
switch(x){
case 1:
bg.style.backgroundImage = "-webkit-linear-gradient(rgba(0,0,0,.375), rgba(0,0,0,.375)),url(/img/header.jpg)";
caption.style.marginLeft = "0em";
caption.innerHTML = "Chef's Special Sushi Platter";
break;
case 2:
bg.style.backgroundImage = "-webkit-linear-gradient(rgba(0,0,0,.375), rgba(0,0,0,.375)),url(/img/pokebowl.jpg)";
caption.style.marginLeft = "2em";
caption.innerHTML = "Spring Poke Bowl";
break;
case 3:
bg.style.backgroundImage = "-webkit-linear-gradient(rgba(0,0,0,.375), rgba(0,0,0,.375)),url(/img/ramen.jpg)";
caption.style.marginLeft = "3.75em";
caption.innerHTML = "Miso Ramen";
}
// do dots
if(lastDot){
lastDot.classList.remove("active");
}
elem.classList.add("active");
// store last dot for next click
lastDot = elem;
}

Image filter with javascript

I am new to web development. I am trying to create my photography webpage. I have created a basic html design.
I want to filter the image when the specific button is clicked. I went through the w3schools code about it but could not get quite clear about it. Not with the JQuery.
Here is my html code with buttons.
Thank you
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">ALL</button>
<button class="btn active" onclick="filterSelection('all')">Nature</button>
<button class="btn active" onclick="filterSelection('all')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column_nature">
<div class="content">
<img src="images/nature.jpg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column_nature">
<div class="content">
<img src="images/swan.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</body>
</html>
Because both of your images had 'nature' on them, a filter would not have had any effect. I adapted your code to the w3schools example, but changed it so that the first image had 'nature' as a filter , and the second had 'bird' as a filter.
Incidentally, there is no underscore between the column and the filter name (If you put one in, as you did in your code) it won't work. I adapted this too.
Best of luck
/*this goes in your script.js*/
filterSelection("all") // Execute the function and show all columns
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("column");
if (c == "all") c = "";
// Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
// Show filtered elements
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}
// Hide elements that are not selected
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
/*this bit will go into your style.css file*/
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
padding: 20px;
font-family: Arial;
}
/* Center website */
.main {
max-width: 1000px;
margin: auto;
}
h1 {
font-size: 50px;
word-break: break-all;
}
.row {
margin: 8px -16px;
}
/* Add padding BETWEEN each column (if you want) */
.row,
.row > .column {
padding: 8px;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
display: none; /* Hide columns by default */
}
/* Clear floats after rows */
.row:after {
content: "";
display: table;
clear: both;
}
/* Content */
.content {
background-color: white;
padding: 10px;
}
/* The "show" class is added to the filtered elements */
.show {
display: block;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: white;
cursor: pointer;
}
/* Add a grey background color on mouse-over */
.btn:hover {
background-color: #ddd;
}
/* Add a dark background color to the active button */
.btn.active {
background-color: #666;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('all')">ALL</button>
<button class="btn active" onclick="filterSelection('nature')">Nature</button>
<button class="btn active" onclick="filterSelection('bird')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column nature">
<div class="content">
<img src="https://images.pexels.com/photos/257360/pexels-photo-257360.jpeg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column bird">
<div class="content">
<img src="https://www.phrases.org.uk/images/swan-song-1.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</body>
</html>
I understand that you're new to programming; so beware that some users may provide you with answers suggesting you install jQuery, or Bootstrap - which while that it entirely true and what I would recommend - I equally understand that these all provide steep learning curves for a beginner.
As such, you can develop in HTML, CSS, and the naked JavaScript library as standard. So I have provided a solution to your problem in the code below, and documented my code also, so that you may better understand it.
Replace your code, with my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gallery</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script src="script.js"></script>
<div id="myBtnContainer">
<button class="btn active" onclick="filterSelection('All')">ALL</button>
<button class="btn active"
onclick="filterSelection('Nature')">Nature</button>
<button class="btn active"
onclick="filterSelection('Swan')">Animal</button>
</div>
<!--grid-->
<div class="row">
<div class="column_nature filter" id="Nature">
<div class="content">
<img src="images/nature.jpg" style="width:40%">
<h4>Nature</h4>
<p>This is me</p>
</div>
</div>
</div>
<div class="column_nature filter" id="Swan">
<div class="content">
<img src="images/swan.jpg" style="width:40%">
<h4>Swan</h4>
</div>
</div>
</div>
<script>
// Function to hide all other elements, bar the parameter provided
function filterSelection(elementToShow){
if(elementToShow != "All"){
// Get an array of elements with the class name, filter.
var x = document.getElementsByClassName("filter");
// For each of them
for(var i = 0; i < x.length; i++){
// Make them invisible
x[i].style.display = "none";
}
// Get and then make the one you want, visible
var y = document.getElementById(elementToShow).style.display = "block";
}
else{ // If the parameter provided is all, we want to display everything
// Get an array of elements with the class name, filter.
var x = document.getElementsByClassName("filter");
// For each of them
for(var i = 0; i < x.length; i++){
//Make them visible
x[i].style.display = "block";
}
}
}
</script>
</body>
</html>
Please note the following; if you add a new button to filter something else, you must give it an * onclick="filterSelection('x')" * where the x is the name of that which you want to filter. Then on the div you want to keep, simply give it a class with the same name as "x".
So for instance, if I had a button:
<button onclick="filterSelection('Mountains')">Mountains</button>
Then I would expect that if I click it, that all filter class divs would be hidden, except for the div that had the class mountains. So I would have to have a div like so:
<div class="filter Mountains">This would be the div that would be displayed on click of the above button, and all others would be hidden.</div>
I hope this helps provide you with the answer you were looking for, although eventually it would be best to look into Bootstrap or jQuery which will be much more sustainable in the long run.

Dynamically creating new child node on button click

I want to create a dynamic menu tree in which a child node can be added by clicking any node (whenever you click a node a dialogue box should open to enter a new child node). Whatever the user enters in the this text box, should get added to the tree.
image of what I want to implement
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="" />
<meta name="author" content="" />
<title>To do list</title>
<!-- BOOTSTRAP CORE STYLE CSS -->
<link href="assets/css/bootstrap.css" rel="stylesheet" />
<style type="text/css">
.btn{
width: 80px;
height: 80px;
text-align: center;
padding: 6px 0;
font-size: 12px;
border-radius: 55px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:40px;">
<div style="text-align:center" >
<input type="button" value="Menu Root" class="btn btn-primary" onclick="foo(this)" id="root">
</div>
</div>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/plugins/bootstrap.js"></script>
<script src="myscript.js"></script>
</body>
</html>
JS: myscript.js
function foo(e)
{
var node = prompt("Enter node name: ", "Node");
if (node != null)
{
var curr_node = document.getElementById(e.id); //get clicked button (parent)
var div = document.createElement("DIV");
var btn = document.createElement("INPUT");
btn.setAttribute("type", "button");
btn.setAttribute("id",Math.random().toString(36).substring(7)); //assign random id
btn.setAttribute("value", node);
btn.setAttribute("class","btn btn-primary");
btn.setAttribute("onclick","foo(this)");
div.appendChild(btn); //add child btn to div
curr_node.appendChild(div); //add child div to parent btn
}
}
I am not getting ny results on my browser nor in console. What's the problem and how should I resolve it?

Accessing Dynamically created elements and id in javascript

I am learning javascript and trying to do this with pure javascript..
I have created an input which when user fill and click on "Add Input Text" it will wrap the text into li tags and also add close button on the each input and add the input content to the div under it, I am using following code..
I am unable to make the close button work which are on the right side of each list items...
Please help.. Thanks
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
var closeThis = document.getElementById("closebtn");
closeThis.addEventListener('click' , function(){
this.parentNode.remove();
});
.container{min-height:400px;width:100%;background-color:#999;color:#fff;float:left}.input-container{padding:10px;background-color:#777;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px}a#closebtn{background-color:#8B8B8B;float:right;padding:1px 3px;margin:0px;color:#fff;text-decoration:none}#input-box{list-style-type:none}#input-box li{color:#FFF;background-color:#404040;padding:5px;width:300px;margin:0px;float:left;clear:both;margin-bottom:10px;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
you need to add a onclick event on your x link and pass the element as parameter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script>
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
var closeThis = document.getElementById("closebtn");
closeThis.addEventListener('click' , function(){
this.parentNode.remove();
});
function close_click(elem)
{
elem.parentNode.remove();
}
</script>
</body>
</html>
i added close_click function in javascript that is being called in every of your created close button.
Change closebtn from an id to a class, because ids must be unique.
You can then replace the closebtn click handler with a delegated event on document.body:
document.body.addEventListener('click', function(event) {
if(event.target.className==='closebtn') {
event.target.parentNode.remove();
}
});
event.target will be the element that has been clicked.
Snippet
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme(){
if(inputDisplay.value == ""){
alert("please put something in the input field.");
}else
inputBox.innerHTML += "<li>" + inputDisplay.value + 'x</li>';
}
function clearInput(){
inputBox.innerHTML = "";
}
function delLast(){
if( inputBox.innerHTML === "") {
alert("There is nothing to delete");
}else{
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
document.body.addEventListener('click', function(event) {
if(event.target.className==='closebtn') {
event.target.parentNode.remove();
}
});
.container{min-height:400px;width:100%;background-color:#999;color:#fff;float:left}.input-container{padding:10px;background-color:#777;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px}a.closebtn{background-color:#8B8B8B;float:right;padding:1px 3px;margin:0px;color:#fff;text-decoration:none}#input-box{list-style-type:none}#input-box li{color:#FFF;background-color:#404040;padding:5px;width:300px;margin:0px;float:left;clear:both;margin-bottom:10px;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick = "clickme()">Add input text</button>
<button onclick= "clearInput()">clear Input Box</button>
<button onclick= "delLast()">Del Last</button>
</div> <!--input-container -->
<div id ="main-content-container">
<ul id= "input-box">
</ul>
</div> <!--input-box -->
<div class="array-div">
</div>
</div> <!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
You need to add the click handler after creating the close button
var inputBox = document.getElementById('input-box');
var inputDisplay = document.getElementById('input-display');
function clickme() {
if (inputDisplay.value == "") {
alert("please put something in the input field.");
} else {
//create a new li
var li = document.createElement('li');
//add the input text to it as text
li.appendChild(document.createTextNode(inputDisplay.value));
//create a new anchor
var a = document.createElement('a');
a.href = "#";
//since id of an element must be unique, use classname
a.className = 'closebtn';
//add the click handler
a.addEventListener('click', closeHandler);
//add the anchor to li
li.appendChild(a);
//add the li to the ul
inputBox.appendChild(li);
}
}
function closeHandler() {
this.parentNode.remove();
}
function clearInput() {
inputBox.innerHTML = "";
}
function delLast() {
if (inputBox.innerHTML === "") {
alert("There is nothing to delete");
} else {
var lastInputText = inputBox.lastChild;
lastInputText.remove();
}
}
.container {
min-height: 400px;
width: 100%;
background-color: #999;
color: #fff;
float: left
}
.input-container {
padding: 10px;
background-color: #777;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px
}
a.closebtn {
background-color: #8B8B8B;
float: right;
padding: 1px 3px;
margin: 0px;
color: #fff;
text-decoration: none
}
#input-box {
list-style-type: none
}
#input-box li {
color: #FFF;
background-color: #404040;
padding: 5px;
width: 300px;
margin: 0px;
float: left;
clear: both;
margin-bottom: 10px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript-learning</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<div class="input-container">
<input type="text" id="input-display">
<button onclick="clickme()">Add input text</button>
<button onclick="clearInput()">clear Input Box</button>
<button onclick="delLast()">Del Last</button>
</div>
<!--input-container -->
<div id="main-content-container">
<ul id="input-box">
</ul>
</div>
<!--input-box -->
<div class="array-div">
</div>
</div>
<!-- container -->
<!-- javascripts -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/underscore/underscore.min.js"></script>
<script src="bower_components/backbone/backbone-min"></script>
<script src="assets/js/script.js"></script>
</body>
</html>

Categories

Resources