JQuery, Create multiple html Element with ascending IDs? - javascript

Here is what is needed to do:
<input type="text" id="main" placeholder="Put URL Here">
Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:
<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->
Here is what I got So far (only using HTML)
<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image

This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.
let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
main = document.querySelector('#main'),
addButton = document.querySelector('[data-url-saver]'),
resetButton = document.querySelector('[data-url-reset]');
addButton.addEventListener('click', () => saveURL())
resetButton.addEventListener('click', () => reset())
})
const saveURL = () => {
let u = main.value;
urls.push(u);
let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
document.querySelector('form').insertAdjacentHTML('beforeend', h);
main.value = "";
let de = document.querySelector('#debug');
de.innerHTML = urls.join(", ");
if (urls.length >= limit) {
addButton.setAttribute('disabled', 'disabled');
main.setAttribute('disabled', 'disabled');
main.setAttribute('placeholder', 'Maximum URLs accepted')
}
}
const reset = () => {
urls = [];
document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
addButton.removeAttribute('disabled');
main.removeAttribute('disabled');
document.querySelector('#debug').innerHTML = "";
}
<form>
<input type="text" id="main" placeholder="Put URL Here">
<button data-url-saver type='button'>enter</button>
<button data-url-reset type='button'>reset</button>
</form>
<div id='debug'></div>

Create a div for hidden urls like
<div id="urls"></div>
try in jquery
var counter = 1;
$('#main').keypress(function (e) {
if(e.which== 13){ // enter key code
var url = $('#main').val();
$('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
$('#main').val(''); //clearing the input
counter++;
}
});

If you want to add ascending URL and if you have the link, then you can use the function below.
function addImage(){
var link = document.querySelector('#main').value;
var all_links = document.getElementById('all_urls');
if (link.length > 0){
code = `
<input type="hidden" id="url_${all_links.children.length}" value="${link}"/>
`
all_links.innerHTML += code;
console.log(document.getElementById('all_urls'))
}
}
<figure class="mb-4">
<input type="text" id="main" placeholder="Put URL Here">
<div id="all_urls">
<!--All the links are added here-->
</div>
<button id="addimage" onclick="addImage()">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>

In jQuery
// Cache some elements
const div = $('div');
const main = $('#main');
$('button').click(() => {
// Grab the value
const val = main.val();
// Create the id based on the current
// number of inputs
const id = div.find('input').length + 1;
// Append the new input
div.append(`<input readonly id="url_${id}" value="${val}" />`);
// Reset the main input
main.val('');
});
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
And the equivalent in vanilla JS:
// Cache some elements
const div = document.querySelector('div');
const main = document.querySelector('#main');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false)
function handleClick() {
// Create the id based on the current
// number of inputs
const id = div.querySelectorAll('input').length + 1;
const html = `<input readonly id="url_${id}" value="${main.value}" />`;
// Append the new input
div.insertAdjacentHTML('beforeend', html);
// Reset the main input
main.value = '';
};
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>

Related

Trying to check for empty value in input

I have an input box that changes another paragraph in my site with JavaScript. It works flawlessly, except for the fact that when I enter nothing in the input, it blanks out the paragraph.
I don't want this to happen. I've tried almost every piece of code I've found online to fix this issue but nothing has worked.
<div class="tasklist">
<p id="task1" style="color:#d3d3a3">You don't have any tasks.</p>
</div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
element.innerHTML = (value);
document.getElementById("task1").style.color = "white";
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();" onclick="changeColor()">+ Add</button>
<div id="tasklist">
<p id="msg" style="color:red">You don't have any tasks.</p>
</div>
<br>
<script>
const element = document.getElementById("msg");
element.style.display = "none";
function add() {
let value = document.getElementById("task").value;
if (value && value.trim() != "") {
document.getElementById("task").value = "";
element.style.display = "none";
const taskContainer = document.getElementById('tasklist');
const task = document.createElement('p');
task.textContent = value;
taskContainer.append(task)
} else {
element.style.display = "block";
}
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="add();">+ Add</button>
First of all add value checker - it will prevent from setting innerHTML as "".
Secondly i think You want to add element with another task, not removing older ones.
use .append() to add at the end of parent or prepend() to add at the begginning of parrent.
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function changeColor(){console.log("color")};
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.append(
Object.assign(
document.createElement("p"),
{textContent:value}
)
);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();changeColor()" >+ Add</button>
if You rather want to replace Your first child then
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.replaceChild(Object.assign(document.createElement("p"),{textContent:value}),element.firstChild);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue()" >+ Add</button>

how can i make Local Storage get 2 different value?

i've tried to make an simple app, its only user input and show the output, and now i tried to make local Storage. can anyone help me plis
this is my code
html
<aside class="input">
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
</aside>
JavaScript
localStorage = "itsStorage";
function addVal() {
const takeName = document.getElementById("name").value;
const takeTittle = document.getElementById("title").value;
const wrapIt = wrapper(takeName,takeTittle);
const list = document.getElementById("list");
localStorage.setItem(takeName, takeTittle);
}
function wrapper(itsName, itsTittle) {
const name = document.createElement("h2");
name.innerText = itsName;
const tittle = document.createElement("p");
tittle.innerText = itsTittle;
const div = document.createElement("div");
div.classList.add("list");
div.append(name, tittle);
const outList = document.querySelector(".list-output");
outList.append(div);
localStorage.getItem(name, tittle);
}
Something more like this
Use stringify to store an array and parse to get it back
I could not test it since Stacksnippets do not allow localStorage
Also I did not code a delete button
If you want one, you need to delegate
There were several other issues I tried to fix, study the code
window.addEventListener("load", function() {
const outList = document.getElementById("container");
const list = localStorage.getItem("list");
list = list ? JSON.parse(list) || []; // if there is a list already
list.forEach(({ name, title }) => wrapper(name, title)); // show
document.getElementById("form").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const name = document.getElementById("name").value;
const title = document.getElementById("title").value;
const wrapper = wrapper(name, title);
list.push({ name, title })
localStorage.setItem("list", JSON.stringify(list));
});
function wrapper(name, title) {
const header = document.createElement("h2");
header.textContent = name;
const p = document.createElement("p");
p.textContentt = title;
const div = document.createElement("div");
div.classList.add("list");
div.append(header)
div.append(p)
outList.append(div);
}
})
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
<div id="container"></div>

How can I create an ol with a li element so that if I create a text node, it can be adding with ordered numbers on the same line in JS

How can I make this code work well with the list printing the result on the same line.
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
mainBody.innerHTML = '<li></li>'
const text = document.getElementById("toDo").value;
const myText = document.createTextNode(text);
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Few things:
You overwrite the contents of the previous list when you do mainBody.innerHTML = '<li></li>'.
It is not semantically correct to add a text node to an ordered list. Instead, create a li element and append the text node to the li.
Try this instead:
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button onclick="submitText()">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
const text = document.getElementById("toDo").value;
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(text));
mainBody.appendChild(myText);
}
</script>
</body>
</html>
Added few things:
remove the value of input when button is clicked
check if length of input is greeter then 1
event listener when enter key is pressed
<html>
<body>
<div>
<input id="toDo" type="text" placeholder="Add an item!" required>
<button id="btn">Submit</button>
</div>
<div><ol align="center" id="probody"></ol></div>
<script>
const mainBody = document.querySelector('#probody');
function submitText() {
var input = document.getElementById("toDo")
if(input.value.length < 1 || input.value.replaceAll(" ", "") < 1) return; // check if the input value length is greeter then 1 character
const myText = document.createElement("li");
myText.appendChild(document.createTextNode(input.value));
mainBody.appendChild(myText);
input.value = ''; // clear the value input
}
document.getElementById("btn").addEventListener("click", submitText); // save the input value when button is clicked
document.getElementById("toDo").addEventListener('keypress', function (e) {
if (e.key === 'Enter') submitText();
}); // save the input value when enter key is pressed
</script>
</body>
</html>
Change
mainBody.innerHTML = '<li></li>'
to
mainBody.innerHTML += '<li></li>'

how to show user input in the body when a button is clicked

I'm trying to display a user input on a separate div, but only have it appear when a button is clicked. I think i have it set up but I'm just not sure how to display the input. can someone help me with how it can be done?
<script>
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function(){
console.log("Call has been set");
userinput.style.display = "block";
</script>
<input id="callerIDInput" type="text" value="" >
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Set the input value to the innerHTML of the div
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
callButt.addEventListener("click", function() {
console.log("Call has been set");
userinput.innerHTML = document.getElementById('callerIDInput').value
})
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt'>CALL</button>
Use innerHTML of the DIV to set the value.
HTML
<input id="callerIDInput" type="text" value="">
<div id="userinput"> </div>
<button id='callButt' onclick="Display()">CALL</button>
Javascript
function Display()
{
var callButt = document.getElementById("callButt");
var userinput = document.getElementById("userinput");
var callerIDInput = document.getElementById("callerIDInput");
console.log("Call has been set");
userinput.style.display = "block";
userinput.innerHTML = callerIDInput.value;
}

JavaScript - display keys and values of an array

I'm playing with a module object and trying to create a sort of blog (it's not going to be used in real life - just me learning stuff).
When a user fills a form and provides a tag, it checks whether the tag exists in an associative array, if not, it adds it with the value = 1. If the tag already exists, it adds +1 to the value. Now I want to display on a side how many entries for each tag there are, eg:
cooking(3)
sport(1)
It seems to partially work as when I add another tag, it displays in but keeps increasing the count of ALL the categories/tags:
cooking(1)
sport(1)
then
cooking(2)
sport(2)
...not just the one the user has just added.
var myArticles = (function () {
var s, articles;
return {
settings: {
articleList: "articles", // div with generated articles
articleClass: "article", // class of an article
articleIndex: 0,
sidebar: document.getElementById("sidebar"),
tagList: {},
// cats: Object.keys(this.settings.tagList)
},
init: function() {
// kick things off
s = this.settings;
articles = document.getElementById(this.settings.articleList);
this.createArticle();
},
createArticle: function() {
var div = document.createElement("div");
var getTag = document.getElementById("tag").value;
var getTitle = document.getElementById("title").value;
// Add classes
div.classList.add(this.settings.articleClass, getTag);
// Add title / content
var title = document.createElement("h2");
var textNode = document.createTextNode(getTitle);
title.appendChild(textNode);
div.appendChild(title);
// Add category
div.innerHTML += "Article" + this.settings.articleIndex;
articles.appendChild(div);
this.settings.articleIndex +=1;
this.updateCategories(getTag);
},
updateCategories: function(tag) {
// Create header
this.settings.sidebar.innerHTML = "<h3>Categories</h3>";
// Create keys and count them
if (tag in this.settings.tagList) {
this.settings.tagList[tag] += 1;
} else {
this.settings.tagList[tag] = 1;
}
var cats = Object.keys(this.settings.tagList);
// Create an unordered list, assign a class to it and append to div="sidebar"
var ul = document.createElement('ul');
ul.classList.add("ul-bare");
this.settings.sidebar.appendChild(ul);
// iterate over the array and append each element as li
for (var i=0; i<cats.length; i++){
var li=document.createElement('li');
ul.appendChild(li);
li.innerHTML=cats[i] + "(" + this.settings.tagList[tag] + ")";
}
}
};
}());
And HTML:
<body>
<div id="container">
<h1>My articles</h1>
<div id="genArticle" class="left">
<form id="addArt" method="post">
<div>
<label for="title">Title</label>
<input type="text" id="title" class="forma" placeholder="Title" required />
</div>
<div>
<label for="tag">Tag</label>
<input type="text" id="tag" class="forma" placeholder="Tag" required />
</div>
<div>
<label for="art">Article</label>
<textarea id="art" class="forma" required /></textarea>
</div>
<input type="button" onclick="myArticles.init()" value="Add Art">
<input type="reset" value="Reset Form">
<input type="range" size="2" name="satisfaction" min="1" max="5" value="3">
</form>
<div id="articles"></div>
</div> <!-- end of genArticle -->
<aside id="sidebar" class="right">
</aside>
</div> <!-- end of container -->
<script src="js/script.js"></script>
</body>
I think this line is wrong
li.innerHTML=cats[i] + "(" + this.settings.tagList[tag] + ")";
It is this.settings.tagList[cats[i]]
Not this.settings.tagList[tag]

Categories

Resources