I am trying to create a button that creates an input field every time I click on it. Currently when I click it it creates only only one input field, how can I make so that every time I click it I get an input field?
Here is my html:
<div id="new-input-container"> </div>
<p class="add-new-shareholders-p"><i class="fa fa-plus-circle fa-lg" #click="createNewInputFields"/>
and my function:
createNewInputFields() {
var container = document.getElementById('new-input-container')
container.innerHTML = "<input type='text'/>";
}
Using document.createElement, you can create new input HTMLElement and using container.appendChild function, you can add that new element to the div selector as follows.
function createNewInputFields() {
var container = document.getElementById('new-input-container');
const newElem = document.createElement("input");
newElem.setAttribute("type", "text");
container.appendChild(newElem);
}
<div id="new-input-container"> </div>
<button onclick="createNewInputFields()">Add New</button>
Depending on your logic, you can try one of these solutions :
First logic : Create inputs by a number
<template>
<div id="app">
<input type="text" v-for="i in numberOfInputs" :key="i" />
<br />
<button #click="addInput">Add input</button>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
numberOfInputs: 0,
}),
methods: {
addInput: function () {
this.numberOfInputs++;
},
},
};
</script>
Second logic: Create inputs by values
<template>
<div id="app">
<input
type="text"
v-for="(value, i) in values"
:key="i"
v-model="values[i]"
/>
<br />
<button #click="addInput">Add input</button>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
values: [],
}),
methods: {
addInput: function () {
let value = "";
this.values.push(value);
},
},
};
</script>
Your function will work fine, the only change that you need to make is, instead of setting value using innerHTML property, you can use the insertAdjacentHTML( ) function.
The reason your code only adds the input field once is because what innerHTML is doing here is just overwrite existing HTML each time you set a value using the assignment operator (=). That is because, innerHTML property just gets the innerHTML from the element like it is a string. One option is to concatinate the new input html to the existing innerHTML, the other is to use insertAdjacentHTML( ) function.
insertAdjacentHTML( ) will add adjacent html each time, takes in 2 parameters, first one is the place you want to insert which can be which can be one of ('beforebegin' 'beforeend' 'afterbegin' 'afterend'), in your case the best would be 'beforeend'. The second parameter is the HTML you want to add.
document.querySelector('.btn').addEventListener('click', createNewInputFields);
function createNewInputFields() {
const container = document.getElementById('new-input-container');
const inputHtml = "<input type='text'/>";
container.insertAdjacentHTML('beforeend', inputHtml);
}
<div id="new-input-container"></div>
<p class="add-new-shareholders-p">
<button class='btn'> create field</button>
</p>
I just fixed the bugs in your code.
To add a new item, you must use +=.
If you use only = the first time you will add an item.
But with each subsequent click, the item will be rewritten
The problem with this option is that when you add new fields, the content of the already created ones will be removed!
function createNewInputFields() {
var container = document.getElementById('new-input-container')
container.innerHTML += "<input type='text'/>";
}
<div id="new-input-container"> </div>
<p class="add-new-shareholders-p"><i class="fa fa-plus-circle fa-lg" onclick="createNewInputFields()">Click Me</i></p>
The correct way to add a new field while keeping the idea of your code and saving information in already created fields is:
function createNewInputFields() {
var container = document.getElementById('new-input-container');
var x = document.createElement("input");
x.setAttribute('type', 'text');
container.appendChild(x);
}
<div id="new-input-container"> </div>
<p class="add-new-shareholders-p"><i class="fa fa-plus-circle fa-lg" onclick="createNewInputFields()">Click Me</i></p>
Related
Hello everyone I can't do an exercise in html and javascript. How can I read from an input search multiple inputs and print them dynamically? for example if I write as input in the search bar "mark" I want to print "mark". If I then write "helen" in the search bar, I want to print: "mark", "helen", if I then write "gessy", I want to print "mark", "helen", "gessy" and so on.
page.html
<div class="container-fluid" >
<form class="d-flex" role="search">
<input class="form-control me-2" id="form-control me-2" type="search" placeholder="Search" aria-label="Search"> //here I write the inputs
<button class="btn btn-outline-success" type="button" onclick="send_tocontainer()">Search</button> //when i click the button i see all input value write from users
</form></div>
<div id="container-dx" >
<p id="text"></p>
</div>
script.js
function send_tocontainer(){
let element=document.getElementById("form-control me-2").value;
let newnode= document.createElement("p");
const textnode= newnode.createTextNode(element)
newnode.appendChild(textnode);
document.getElementById("testo").innerHTML=element
}
You could use an array to save the entries coming from your input. Then display them on the page by looping over that array and creating a tag to hold each entry and append it to your pages <p> element.
The benefit of saving the data to an array/object means you could also reference that data later.
See the snippit for an example.
const btn = document.querySelector('.btn')
const search = document.querySelector('form .me-2')
const textEl = document.getElementById('text')
const searchValues = []
const searchResults = (e) => {
// push the values into an array
searchValues.push(search.value)
// iterate over the array
searchValues.forEach((val, i) => {
// create a span tag to hold the display text from the array
let span = document.createElement('span')
// style the span so it is block element
span.style.display = 'block'
// is this the last iteration through, which would be the last entry into the form by user
// yes, then set the last value in the array to the textContent of our newly created span tag
i === searchValues.length - 1 ? span.textContent = searchValues[searchValues.length-1] : null
// append the text element
textEl.appendChild(span)
})
}
// event listener for button
btn.addEventListener('click', searchResults)
<div class="container-fluid">
<form class="d-flex" role="search">
<input class="form-control me-2" id="form-control me-2" type="search" placeholder="Search" aria-label="Search"> //here I write the inputs
<button class="btn btn-outline-success" type="button">Search</button> //when i click the button i see all input value write from users
</form>
</div>
<div id="container-dx">
<p id="text"></p>
</div>
Or you could just display the entries directly on the page without saving the input to some kind of array/object/etc...
See the snippit for an example.
const btn = document.querySelector('.btn')
const search = document.querySelector('form .me-2')
const textEl = document.getElementById('text')
const searchResults = (e) => {
let span = document.createElement('span')
span.style.display = 'block'
span.textContent = search.value
textEl.appendChild(span)
}
btn.addEventListener('click', searchResults)
<div class="container-fluid">
<form class="d-flex" role="search">
<input class="form-control me-2" id="form-control me-2" type="search" placeholder="Search" aria-label="Search"> //here I write the inputs
<button class="btn btn-outline-success" type="button">Search</button> //when i click the button i see all input value write from users
</form>
</div>
<div id="container-dx">
<p id="text"></p>
</div>
There are multiple ways you can complete this exercise. I've decided to use the local storage. It's important save the previous search state as it is required to be used on the next function call.
Rather than using element variable I'm using oldElement and newElement hoping they may self explain.
send_tocontainer = () => {
let newElement = document.getElementById("form-control me-2").value;
if (!localStorage.getItem('data')) {
localStorage.setItem('data', '[]');
}
let oldElement = JSON.parse(localStorage.getItem('data'));
oldElement.push(newElement);
localStorage.setItem('data', JSON.stringify(oldElement));
let serchContent = document.createElement("p");
serchContent.innerText = oldElement.toString();
document.body.appendChild(serchContent);
// let newnode = document.createElement("p");
// const textnode = newnode.createTextNode(element);
// newnode.appendChild(textnode);
// document.getElementById("testo").innerHTML = element
}
notice I have commented out the createTextNode as the function aren't defined in the question.
Here in local storage an array is created as data and new values are stored in to it. I also took liberty of creating a paragraph element to display your search results.
I've hosted this code here try to play around with it
https://stackblitz.com/edit/js-eamamp?file=index.html,index.js
This is the div
<div class="col-lg-4 pre-scrollable" id="all-menus-div">
<h3 class="text-center">Tum menu listesi</h3>
<div class="list-group" id="all-menus-checkboxes" th:each="menu : ${allMenusList}">
<input th:id="${menu.id}" th:text="${menu.item}" th:value="${menu.item}" type="checkbox"/>
</div>
<button class="btn btn-success" disabled id="add-menus-to-role-btn" type="submit">Ekle</button>
</div>
<button class="btn btn-success" id="update-menus-for-role-btn" type="submit">Rolu guncelle</button>
</div>
it gets from model object.
This is the function of it for onchange:
$('#all-menus-checkboxes').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
it calls this function when I click the first checkbox only. And i can see only the log at this time. So, only button disabled becomes false only when i click the first one.
When i click others, nothing happens, no logs.
But when i click for example second one, then click first one, it shows 2 of them are selected.
Why is that?
Simple allMenuslist:
[MenuDTO{id=1, href='/check-deposit-money', menuName='Kontrol-Onay Ekranları', roles=[RoleDTO{id=1, name='ADMIN'}], iconName='null', item='Cüzdana Para Yükleme - Kontrol', className='null'}]
onchange event must to bind on the <input>.
bind event must to after <input> appended.
But your <input> like by dynamic generation, recommend use 'event delegation':
add class to <input>.
<input class="all-menus-checkboxes" />
use event delegation.
<script>
$('#all-menus-div').on('change', '.all-menus-checkboxes', function () { ... }
</script>
try this
$('#all-menus-checkboxes > input[type=checkbox]').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>
I made a filter for my nested inputs, im using javascript to filter a link whenever paste event is fired.
function fixLink(foo){
if (foo.includes('youtube') && (foo.includes('watch')) || foo.includes('vimeo') && !foo.includes('video') ) {
foo = foo.includes('youtube') ? 'https://www.youtube.com/embed/' + foo.slice(foo.indexOf('=') + 1) : foo;
foo = foo.includes('vimeo') ? 'https://player.vimeo.com/video/' + foo.slice(foo.indexOf('com/') + 4) : foo;
}
return foo;
}
input.addEventListener('paste', () => {
setTimeout(() => {
input.text = fixLink(input.value);
input.value = fixLink(input.value);
}, 100)
});
This is my HTML
#Component({
selector: 'video-control',
template: `<div class="form-group p-0 mb-2" [formGroup]="video">
<div class="input-group group-social">
<input [disabled]="onHold" class="form-control" formControlName="url" type="text" (focus)="setUrl($event.target)" placeholder="https://www.youtube.com/watch?v=IWfWqDhx65s">
<button type="button" class="remove-photo-gallery btn btn-sm btn-danger" (click)="removed.emit(index)">
<i class="fas fa-trash"></i>
</button>
</div>
</div>`,
})
It changes input value but when i save the value it comes as if the filter didn't work.
I can only get my filter to work if i add something else to the input like a space.
What I can deduce from your HTML is that you have a FormGroup called video and it has a FormControl called url. These are the edits I think you need to make.
Update your input element to use the Angular (paste) event emitter:
<input [disabled]="onHold" class="form-control" formControlName="url" type="text" (focus)="setUrl($event.target)" (paste)="onPaste($event)" placeholder="https://www.youtube.com/watch?v=IWfWqDhx65s">
Then in your component have the following method:
onPaste(event: ClipboardEvent) {
const clipboardData = event.clipboardData || window.clipboardData;
const fixedLink = this.fixLink(clipboardData.getData('text'));
window.setTimout(() => this.video.get('url').value = fixedLink);
}
You would also need to move this fixLink function to be part of the component as well.
If your hope is to have plain JS update the Angular FormGroup then you're using Angular wrong and I strongly advise against continuing along that path.
Try to use two-way binding to the value of the input element and trigger fixLink function on the paste event to change the property that is bound to the input value.
I am trying to create an extention which clicks on an item of the price given by the user. Here is the relevant popup.html:
<input style="display:none" /><input type="text" id="userInput" value='' />
<button id="clickme">Run</button>
When 'clickme' is clicked, it runs this popup.js:
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+ document.getElementById("userInput").value+".00";
alert(price);
$("p:contains("price")").parentNode.click();
});
If you type the desired price in in the form as 48, it returns an alert with the value $48.00.
It then shuold click on the item of that price, however this currently isn't working. Here is the code of the relevant part of the website which I am trying to run my extention on (not my website):
<div class="grid__item wide--one-fifth large--one-quarter medium-down--one-half">
<a href="/collections/1seventeenweek7/products/copy-of-supreme-dazzle-warm- up-top-red" class="grid-link text-center">
<p class="grid-link__title">Supreme Corner Cap Light Blue</p>
<p class="grid-link__meta">
<span class="visually-hidden">Regular price</span>
$48.00
</p>
</a>
</div>
I am trying to get it to search for the p element containing $48.00, and then click on the a element which is the parent element, but this is not currently working. What am I doing wrong? - thanks
Here you go. This will work!
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
alert(price)
for (let i = 0; i < metas.length; i++) {
if (metas[i].innerHTML.includes(price)) metas[i].parentNode.click()
break
}
})
Personally, I'd really like to use something like the following, yet I forgot that getElementsByClassName doesn't return an array, but rather a NodeList object.
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
var match = metas.find((curr) => curr.innerHTML.includes(price))
match.parentNode.click()