Want to Create an Array button - javascript

I am trying to create a button using array but when i try to write text in text input and try to create a button it doesn't change the value.
function ready() {
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns() {
var btn = $("<button>" + family[i] + "</button>")
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i = 0; i < family.length; i++) {
btns();
}
$(submit).on("click", function() {
var textBtn = text.val();
family.push(textBtn);
btns();
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>

Is this what you are looking for? The code is commented to show you the steps
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
// for each family add a button
const buttons = family.map(el => $(`<button data-search="${el}">${el}</button>`));
$('#buttons').append(buttons);
function addButton() {
// get the value of the text input
const val = $('#button-text').val();
// if the value is not empty
if (val.trim().length) {
// create the new button and append it
const btn = $(`<button data-search="${val}">${val}</button>`);
$('#buttons').append(btn);
// add the val to the family array
family.push(val);
// add the button to the buttons array
buttons.push(btn);
// reset the input field
$('#button-text').val('');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttons">
</div>
<div>
<input type="text" id="button-text"/>
<button onClick="addButton()">Add Button</button>
</div>

The issue with your existing code is that you have declared the variable i in your for loop, but you are not incrementing the value when you manually add the new button.
If you update your submit button click event as follows, you will accomplish what you are looking for:
$(submit).on("click", function(){
var textBtn = text.val();
family.push(textBtn);
console.log(family);
btns();
i++; // Added the increment of 'i' here.
});
However, I am sure there's a much more eloquent way of solving this problem that doesn't involve keeping track of the array index.

Few things here
You may not need to create the input and the button using js. You can create it using html only
The i in the for loop is global, put a keyword before it and then pass the family[i] to the btns function
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns(val) {
var btn = $("<button>" + val + "</button>")
$(btn).attr("data-search", val)
$(btn).appendTo("#buttons")
}
for (let i = 0; i < family.length; i++) {
btns(family[i]);
}
$("#submitBtn").on("click", function() {
var textBtn = $("#submitIp").val();
btns(textBtn);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit">
<input type='text' id='submitIp' name='text'><button id='submitBtn'>Submit</button>
</div>
</div>
</div>
</div>
</body>

here, your loop is the main problem...you need to add element singularly
function ready(){
var family = ["demo1","demo2","demo3","demo4","demo5","demo6"];
function btns(){
var btn = $("<button>" + family[i] + "</button>");
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i=0; i < family.length; i++){
btns();
}
$(submit).on("click", function(){
var textBtn = text.val();
// family.push(textBtn);
var btn = $("<button>" + textBtn + "</button>");
$(btn).attr("data-search", textBtn)
$(btn).appendTo("#buttons")
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>
Also, I haven't change your code..just pasted your code on the correct block :)

you are missing selector while getting input val
function ready() {
var family = ["demo1", "demo2", "demo3", "demo4", "demo5", "demo6"];
function btns() {
var btn = $("<button>" + family[i] + "</button>")
$(btn).attr("data-search", family[i])
$(btn).appendTo("#buttons")
}
var submit = $("<button>Submit</button>");
var text = $("<input type='text' name='text'>");
$(text).appendTo("#submit");
$(submit).appendTo("#submit");
for (i = 0; i < family.length; i++) {
btns();
}
$(submit).on("click", function() {
var textBtn = $( "input[name='text']" ).val();
family.push(textBtn);
btns();
})
}
ready();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row">
<div id="buttons"></div>
</div>
<div class="row">
<div class="col-sm-3">
<div id="gif"></div>
</div>
<div class="col-sm-9">
<div id="submit"></div>
</div>
</div>
</div>
</body>

You're referring i in your btns function. The recommended way is to create a scope for any variable. I prefer to use let and const to scope the variables.
You have to move the iteration into the btns function and create another function which is solely responsible to create a button with the text passed as a parameter. And call the create button function from your btns function. And easily you can reuse the create button function even for your click event handler.
The sample code can be found here: https://codesandbox.io/s/pop7vkzpx

Related

How to create elements and delete them with native javascript without using jQuery

In the below link, there is a add more button, i want the add more to create the same input field with a delete button associated with it, but i would like to do it all with native js if possible.
https://codepen.io/aazim-khaki/pen/vYZmMRq
Current JS :
$(function() {
$(".btn-copy").on('click', function() {
var ele = $(this).closest('.example-2').clone(true);
ele.find('input').val('')
if (ele.find('button').length < 2) {
let btn = document.createElement("button");
btn.innerHTML = "Delete";
btn.onclick = (e) => {
e.preventDefault()
ele.remove()
}
ele[0].appendChild(btn);
}
$(this).closest('.example-2').after(ele);
})
})
Delegate
I moved the form tag and gave the button a delete class
window.addEventListener("load", function() {
document.querySelector(".row").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains('delete')) {
tgt.closest('.example-2').remove()
} else if (tgt.classList.contains('btn-copy')) {
const ele = tgt.closest(".example-2").cloneNode(true);
ele.querySelector("input").value = "";
if (ele.querySelectorAll("button").length < 2) {
let btn = document.createElement("button");
btn.innerHTML = "Delete";
btn.classList.add("delete");
ele.appendChild(btn);
}
tgt.closest(".card-body").appendChild(ele)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h5 class="card-title">Add Class</h5>
</div>
<form action="#">
<div class="card-body">
<div class="example-2 form-group row">
<!--<label class="col-form-label col-md-2">Input Addons</label>-->
<div class="col-xs-2">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Class Name</span>
</div>
<input class="form-control" type="text">
<div class="input-group-append">
<button class="btn-copy btn btn-primary" type="button">Add More</button>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-xs-2">
<button class="btn btn-primary" type="button">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Use a container and event delegation so you only use one listener rather than attaching a listener to each remove button.
This is a very simple example but the principles are the same.
// Cache your elements
const container = document.querySelector('#container');
const add = document.querySelector('button');
// Add your container an add button listeners
container.addEventListener('click', handleEvent, false);
add.addEventListener('click', handleAdd(), false);
// If a remove button is clicked, find the
// the closest div wrapper and remove it from
// the container
function handleEvent(e) {
const { id } = e.target.dataset;
const row = e.target.closest('.row');
container.removeChild(row);
}
// `handleAdd` returns a function (closure) that
// is used for the add listener rather than
// maintaining a global variable.
// We initialise the id at this point
function handleAdd(id = 0) {
// And now return the function that will be called
// when the add button is clicked
// For the purposes of this example it simply adds new HTML
// to the container, and then increases the id
return function() {
const html = `<div class="row"><input value="${id}" /><button data-id="${id}">Remove</button></div>`;
container.insertAdjacentHTML('beforeend', html);
++id;
}
}
<button>Add</button>
<div id="container"></div>

Add an existing div element with classes (along with its underlying elements) to a div

I need to have a function that would add an existing div with a class (along with its underlying elements) to a particular div using for loop. It looks like this:
<div class="left-col">
<div class="list-row">
<div class="list-row2">
<span>Hello</span>
</div>
</div>
</div>
I need to loop through a function that will produce or duplicate "list-row" twice.
$(function() {
var leftcol = document.getElementsByClassName('left-col');
for (var i = 0; i < 2; i++) {
var listrow = document.querySelector('.list-row');
leftcol.appendChild(listrow[i]);
}
})
It should look like this:
<div class="left-col">
<div class="list-row">
<div class="list-row2">
<span>Hello</span>
</div>
</div>
<div class="list-row">
<div class="list-row2">
<span>Hello</span>
</div>
</div>
<div class="list-row">
<div class="list-row2">
<span>Hello</span>
</div>
</div>
</div>
You can try the following way:
$(function() {
var leftcol = document.querySelector('.left-col');
for (let i = 0; i < 2; i++) {
var listrow = document.querySelector('.list-row').cloneNode();
listrow.textContent = i + 1 + listrow.textContent;
leftcol.appendChild(listrow);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left-col">
<div class="list-row">0</div>
</div>
You could use cloneNode and set the deep property to true. This will clone the node and all of its descendants.
For example:
function cloneNode(copies = 1) {
for (let i = 0; i < copies; i++) {
let leftcol = document.getElementsByClassName('left-col')[0];
let nodeToClone = document.querySelector(".list-row");
let clonedNode = nodeToClone.cloneNode(true);
leftcol.appendChild(clonedNode);
}
}
clone.addEventListener("click", function() {
cloneNode();
});
<button id="clone" type="button">Clone Node</button>
<div class="left-col">
<div class="list-row">Test</div>
</div>
If you wanted to insert more than one copy, you could pass a different value to the cloneNode function.
You can use jQuery's .clone() method to copy the entire content of an element to another element. The boolean argument passed to the clone function determines whether the events associated with the cloned element has to be copied or not. true indicates all the events associated with that div has to be copied.
$(function() {
$('.list-row').each(function(){
$(".left-col").append($(this).clone(true));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="left-col">
<div class="list-row"><h1>This is original row</h1></div>
</div>
$(function() {
var leftcol = document.getElementsByClassName('left-col');
var listrow = document.querySelector('.list-row');
for (var i = 0; i < 2; i++) {
leftcol.appendChild(listrow.clone(true));
}
})

insert content into div from textarea Javascript

I am building a chat and i need to append content from the textarea to an inner div upon clicking send
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
the button and textarea code is
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Javascript
var sendButton= document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv= document.getElementById('inner');
var message=textArea.value;
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=meMessage;
});
var meMessage= '<div class="outgoing" id="outgoing">'+
'<div class="me" id="me"></div></div>';
What i am trying to do is show the text value of the text area to the inner div called 'me' when i click send
and also get the value of the textarea to save it to a database. How can i achieve this
First of all you shouldn't create html elements manually since they would be XSS vulnerable and read about escaping mechanics to prevent malicious code being injected.
Try using document.createElement('div'); method to create div with valid innerText.
later use method:
innerDiv.appendChild(createdElement);
To append element.
You could create builder to build html elements you need and you have to htmlEncode text that will be inside of div element.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
UPDATE: Extended snippet code. Removed Ids since they shouldn't be used there to create multiple message elements with same Id. Changed anchor to button.
You need to get the value of the textarea on click of the link
var sendButton = document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
innerDiv.innerHTML = `<div class="outgoing" id="outgoing">${textArea.value}
<div class="me" id="me"></div></div>`;
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn">Send</a>
You can use this. Youe message variable is not receiving the textarea value
var sendButton= document.getElementById('send-btn');
var innerDiv= document.getElementById('inner');
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=innerDiv.innerHTML+'<div class="outgoing" id="outgoing">'+document.getElementById('input').value+
'<div class="me" id="me"></div></div>';
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Maybe be replacing your js with that :
document.getElementById('send-btn').addEventListener('click',
function(){
var userInput = document.getElementById('input').value;
if(userInput) { document.getElementById('me').innerHTML += '<br>' + userInput; }
}
);
That should let you go a step forward... And good luck for saving to DB.
innerDiv.append(message)
instead of
innerDiv.innerHTML=message

Pass Selected Data from one page to other page in html

I am using form to pass the data from one page to other page.If i click the apply button will go to other page, i want to display the corresponding title of the career(i.e Java Developer) in the next page.I tried to achieve this with the help of javascript.
career.html:
<form action="job portal.html" method="get" target="_blank">
<div class="section-header text-center wow zoomIn">
<h2>Current Oppournities</h2>
</div><br /><br />
<div class="row">
<div class="col-lg-6">
<div class="box wow fadeInLeft">
<h4 class="title" id="career-title" name="career-title"><i class="fa fa-java"></i> <b>Java Developer</b></h4>
<hr />
<div class="carrer-opt">
<h5 name="test">Software Developer</h5>
<p>
Should have join immediate joiner .
</p>
</div>
<div class="col-lg-3 cta-btn-container">
<input type="submit" id="apply" value="Apply Now" onClick="testJS()" />
</div>
</div>
</div>
</form>
js:
<script src="js/main.js"></script>
<script>
function testJS() {
var b = document.getElementById('career-title').value,
url = 'job portal.html?career-title=' + encodeURIComponent(b);
document.location.href = url;
}
</script>
job portal.html:
<h1 id="here" style="color:black"></h1>
js:
<script>
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.career-title;
}
</script>
How to acheive this.Anyone please help.
You need to use HTML5 local storage for these kind of problems.
here is solution for your problem.
<script>
function testJS() {
var b = document.getElementById('career-title').value;
var titleText = localStorage.setItem('title', b);
var url = 'job portal.html';
document.location.href = url;
}
</script>
after setting title value get value by referencing id 'title' in your prtal.html script and set value for the element.
<script>
window.onload = function () {
var valueText = localStorage.getItem('title');
document.getElementById('here').innerHTML = valueText;
}
</script>

JS search using keyup event on input tag

I have few div elements with different text content and one input tag.
<input id="search" type="text"/>
<div class="list>
<div id="el"> red </div>
<div id="el"> blue </div>
<div id="el"> red green </div>
</div>
I'd like to get something like this:
if div's textContent is equal to input.value this div is displayed. Else, it's hidden.
Example:
input.value = "red"
/* "red" and "red green" are displayed, "blue" is hidden */
My JS code:
var search = document.getElementById("search");
var el = document.getElementById("el");
search.addEventListener("keyup", function(){
if(search.value == el.textContent){
el.style.display = "block"}
else{
el.style.display = "none"}})
<input id="search" type="text"/>
<div class="list">
<div id="el"> red </div>
<div id="el"> blue </div>
<div id="el"> red green </div>
</div>
You don't want to assign the same id to multiple items. Instead use class.
See below for a working solution:
var search = document.getElementById("search");
var els = document.querySelectorAll(".el");
search.addEventListener("keyup", function() {
Array.prototype.forEach.call(els, function(el) {
if (el.textContent.trim().indexOf(search.value) > -1)
el.style.display = 'block';
else el.style.display = 'none';
});
});
<input id="search" type="text" />
<div class="list">
<div class="el">red</div>
<div class="el">blue</div>
<div class="el">red green</div>
</div>
Here's the solution for regardless of where the input is located, as long as it is space delimited (just in case):
var search = document.getElementById("search");
var els = document.querySelectorAll(".el");
search.addEventListener("keyup", function() {
Array.prototype.forEach.call(els, function(el) {
var values = search.value.split(' ');
var display = true;
for (var i = 0; i < values.length; i++) {
if(el.textContent.trim().indexOf(values[i]) === -1)
display = false;
}
el.style.display = display ? 'block' : 'none';
});
});
<input id="search" type="text" />
<div class="list">
<div class="el">red</div>
<div class="el">blue</div>
<div class="el">red green</div>
</div>

Categories