problem with dynamically add button with value & remove button option - javascript

I made a text field.
getting value from text field and displaying on a button.
-. Problem : i. when click a button so dynamically one button field should generate with remove option and that value should display on that input/button field.
ii. the button should generate upto 5 time max.
here is my code.
$(document).ready(function() {
var $button = $('#display_here').on('click', function() {
$("#added_value_1") = $(this).text();
});
$('#myvaluefirst').on('input', function(e) {
$button.text($(this).val());
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Welcome</title>
<link rel="stylesheet" href="">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" name="myvaluefirst" id="myvaluefirst">
<button type="button" id="display_here" name="display_here">value will display here</button><br>
<!-- This button should generate dynamically max 5 time whenever above button has been click.
and this button should display whenever text has been pass or not after the above button clicked. -->
<button type="button" id="added_value_1" name="added_value_1">Your value is</button>
<button type="button" id="remove_this_1" name="remove_this_1">Remove</button>
problem is: whenever 'value will display here' button clicked then one button should dynamically generate with remove option & value of that button max 5 time only.

The below code gives you a dynamically filled button that on click generates a clone of itself along with a remove button.
$(document).ready(function() {
addFillValueListener();
addGenerateButtonListener();
});
function addFillValueListener() {
const button = document.getElementById('generateButtons');
document.getElementById('myValueFirst').addEventListener('keyup', function () {
button.value = this.value;
});
}
function addGenerateButtonListener() {
const button = $('#generateButtons').get(0);
button.addEventListener('click', function () {
const remainingButtons = +button.getAttribute('data-remainingButtons');
if(remainingButtons > 0) {
button.setAttribute('data-remainingButtons', remainingButtons-1);
cloneAndAppendDynamicButton(button, remainingButtons);
generateAndAppendRemoveButton(remainingButtons);
}
remainingButtons == 0 && console.log('Maximum buttons reached');
});
}
function cloneAndAppendDynamicButton(button, i) {
const clonedNode = button.cloneNode(),
div = $('#dynamicButtonsDiv').get(0);
clonedNode.id = 'dynamicButton' + i;
clonedNode.setAttribute('data-occurance', i);
div.appendChild(clonedNode);
}
function generateAndAppendRemoveButton(i) {
const rem = document.createElement('input'),
div = $('#dynamicButtonsDiv').get(0);
rem.type = 'button';
rem.value = 'Remove';
rem.setAttribute('data-occurance', i);
rem.id = 'removeButton' + i;
rem.addEventListener('click', removeOccurance);
div.appendChild(rem);
}
function removeOccurance() {
const occurance = this.getAttribute('data-occurance');
$('#dynamicButtonsDiv > [data-occurance="'+ occurance +'"]').remove();
}
#dynamicButtonsDiv {
display: flex;
flex-direction: row;
flex-wrap: wrap;
width: 300px;
}
#dynamicButtonsDiv > * {
width: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="myValueFirst" id="myValueFirst">
<input type="button" id="generateButtons" data-remainingButtons="5" value="Dynamic">
<div id="dynamicButtonsDiv"></div>

Related

how to change button class when i click on it using Jquery?

so I am using Jquery to try and change bootstrap buttons classes when I click on them using the toggleClass but the problem is I only can toggle between only 2 classes and that not what I want, I want to toggle between at least 5 classes or even more each time I click on the button, but I can't find a way to do it
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>toggle</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("button").click(function () {
$(this).toggleClass("btn btn-success btn btn-info btn btn-primary");
});
});
</script>
<style>
#p {
position: absolute;
top: 50%;
left: 50%;
}
</style>
<body>
<button id="p" class="btn btn-success">Random button</button>
</body>
</html>
You can put all the classes you want to apply into an array and store the array index of the currently applied class in a variable or using jQuery's .data() method.
Then, whenever the button is clicked, you retrieve and increase the index to get the next class and apply it to the button. Try this
$(document).ready(function () {
var classes = ['btn-success', 'btn-info', 'btn-primary'];
$("button").click(function(){
let idx = $(this).data('class-index') ?? 0; // index of the currently applied class
let cls = classes[idx+1] ?? classes[0]; // get the next class
$(this).data('class-index', classes.indexOf(cls)); // store the class index
$(this).removeClass(classes).addClass(cls); // remove old class and apply new one
});
});
button { outline: none!important; }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<button id="p" class="btn btn-success">Random button</button>
You could increment a counter each time the button is clicked and add a class based on the count. 0 = green, 1 = red. Toggle is only for switching between two states like a physical toggle would

Make each textarea unique to its own button

I'm trying to create an online commenting system where each user can comment on a post and I want a popup text area to be unique to its own button.
Each element is meant to open a text field where a user is to input text to be posted (say in reply to a preceding post or comment).
There are three buttons (representing each user) which when clicked is intended to display a text field specific to the button (or user).
The problem:
After clicking a button, a modal will popup, try typing some text into the field and close the field, without clearing the text in the field, then open another field by clicking on another button. You'll notice that the text typed into one textarea will also be visible in another instance when you click on another button.
What I'm trying to achieve is to make a textarea unique to its direct button instead of a text constantly showing for all buttons clicked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>multi textarea</title>
</head>
<body>
<button>Open a textarea</button>
<button>Open a textarea</button>
<button>Open a textarea</button>
<div class="textarea_modal_backdrop">
<textarea name="" id="" cols="80" rows="20"></textarea>
</div>
</body>
</html>
<script src="./script.js"></script>
CSS:
.textarea_modal_backdrop{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #444c;
display: grid;
place-items: center;
visibility: hidden;
opacity: 0;
}
.textarea_modal_backdrop.textarea_modal_backdrop_active{
visibility: visible;
opacity: 1;
}
JS:
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');
for (var i = 0; i < allButtonElms.length; i+=1) {
allButtonElms[i].onclick = () => {
modalBackdrop.classList.add('textarea_modal_backdrop_active')
}
}
document.addEventListener('click', (event) => {
if (event.target.matches('.textarea_modal_backdrop')) {
modalBackdrop.classList.remove('textarea_modal_backdrop_active')
}
})
I'll be grateful if everyone can join in sharing their ideas on how this issue can be solved.
Thank you all!
one way can be to
stored textarea values in an array of value
add a dataset on button to identify value link to textarea
when textarea is closed save data in values array
const values = [];
var currentButton = 0;
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');
const textarea = document.querySelector('textarea');
for (var i = 0; i < allButtonElms.length; i+=1) {
allButtonElms[i].onclick = (e) => {
var target = e.target || e.srcElement;
currentButton = target.dataset.number;
if (!values[currentButton]) {
values[currentButton] = "";
}
textarea.value = values[currentButton];
modalBackdrop.classList.add('textarea_modal_backdrop_active')
}
}
document.addEventListener('click', (event) => {
if (event.target.matches('.textarea_modal_backdrop')) {
values[currentButton] = textarea.value;
modalBackdrop.classList.remove('textarea_modal_backdrop_active')
}
})
.textarea_modal_backdrop{
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: #444c;
display: grid;
place-items: center;
visibility: hidden;
opacity: 0;
}
.textarea_modal_backdrop.textarea_modal_backdrop_active{
visibility: visible;
opacity: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>multi textarea</title>
</head>
<body>
<button data-number="0">Open a textarea</button>
<button data-number="1">Open a textarea</button>
<button data-number="2">Open a textarea</button>
<div class="textarea_modal_backdrop">
<textarea name="" id="" cols="80" rows="20"></textarea>
</div>
</body>
</html>
<script src="./script.js"></script>

Splicing/Removing selected array elements removes the other elements after the selected element

I am making an offline application of a music website using JS and I am handling song queues using arrays. I added song blocks with skip buttons so users can choose which song to skip without spamming another skip button that only allows them to skip the first song of the queue. The problem is, splicing the array with the index of the selected song the users wanted to skip removes the rest of the songs after it.
Example array: ["songA","songB","songC","songD","songE"]
If the user choose to skip songC, the song queue will become ["songA","songB"] and the songC to songE will be removed, but in reality the expected outcome should be ["songA","songB","songD","songE"].
I have no idea what is wrong with the code and I have searched similar topics regarding this problem but still no results. I am still new to JS and my code's a bit rough but I'm pretty sure that's not the cause of the issue.
JS:
//function of skip buttons on song blocks
songPlaylist.addEventListener("DOMNodeInserted", function() {
iconList = document.querySelectorAll(".deleteIcon");
iconList.forEach(function(element) {
element.addEventListener('click', function() {
var nameOfSong = this.parentNode.childNodes[0].dataset.name;
var indexByName = songQueue.indexOf(nameOfSong);
var selectedBlock = this.parentNode;
if (songQueue.length == 1) {
songQueue.shift();
songPlaylist.removeChild(songPlaylist.firstChild);
var emptyMsgSpan = document.createElement("div");
emptyMsgSpan.className += "emptyMsgSpan";
var emptyMsg = document.createTextNode("Playlist is empty! How 'bout adding some music?");
emptyMsgSpan.appendChild(emptyMsg);
document.getElementById("playlistContainer").appendChild(emptyMsgSpan);
setTimeout(function() {
audioPlayer.src = "";
}, 1000);
} else {
songQueue.splice(indexByName,1); // <--- press first block output delete everything
// press any block after first deletes everything beneath it
songPlaylist.removeChild(selectedBlock);
for (var blockIndex = indexByName; blockIndex <= songQueue.length; blockIndex++) {
document.getElementById("playlistContainer").children[blockIndex].childNodes[1].dataset.index -= 1;
}
};
});
});
});
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">
<link rel="stylesheet" href="index.css">
<link href="https://fonts.googleapis.com/css?family=Bai+Jamjuree" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Jost&display=swap" rel="stylesheet">
<!--<div>Icons made by Roundicons from www.flaticon.com</div>-->
<title>Mue - Custom Playlist</title>
</head>
<body>
<div id="bg">
<div class="titleBar">
<button style="background: none; border: none; cursor: pointer;" onclick="location.reload(); return false;">
<span>MUE</span>
</button>
</div>
<div class="songNameDisplay">
<span id="nowPlaying"></span>
</div>
<div class="trackContainer">
<div class="btn play"></div>
<div class="audioTrack">
<div class="trackBtn"></div>
</div>
<div id="skipBtn">
<div class="triangle1"></div>
<div class="triangle2"></div>
<div class="rect"></div>
</div>
</div>
<button id="fileBtn" class="fileBtn"><span>Upload</span></button>
</div>
<audio id="audioPlayer" controls autoplay></audio>
<input type="file" id="file" />
<div id="playlistContainer"></div>
</body>
<script src="index.js"></script>
<script>
const bg = document.getElementById("bg");
window.addEventListener('scroll' , function() {
let offset= window.pageYOffset;
bg.style.backgroundPositionY = offset * 0.5 + "px";
});
</script>
</html>
Thanks in advance.

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