I would need help to move forward with my code. I want each time the user writes (,) between two words, they should be separated and form two li elements in a list. Right now the whole code works but I would get tips on how to make a comma separated text.
var names = [];
function convert_to_list()
{
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0)
{
return false; //stop the function since the value is empty.
}
names.push(theName);
document.getElementById("converted_list").children[0].innerHTML += "<li>"+names[names.length-1]+"</li>";
}
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input onclick="convert_to_list()"value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</form>
</fieldset>
You could do something like I did in this codepen.
Use the split function to split a string when it encounters a specified character, in your case a comma.
The HTML (pug) would look like this:
form
label
span seperated list
input#js-seperatedList(type="text")
ul.results
And this will be your JavaScript code:
const inputValue = document.querySelector('#js-seperatedList')
const results = document.querySelector('.results');
inputValue.addEventListener('keyup', (e) => {
results.innerHTML = ''
const res = e.target.value.split(",")
for (let i = 0; i < res.length; i += 1) {
const e = document.createElement('li');
e.innerHTML = res[i]
results.appendChild(e)
}
})
Use split() function to separate the words using comma and then create li element and append into final ul element.
const btnEnter = document.getElementById("btnEnter");
btnEnter.addEventListener("click", convert_to_list);
const ulElements = document.getElementById("converted_list").children[0];
function convert_to_list() {
const theName = document.getElementById("enter").value;
if (theName.length <= 0) {
return false;
}
const list = theName.split(",");
const liElements = [];
for (const value of list) {
const li = document.createElement('li');
li.innerHTML = value.trim();
ulElements.appendChild(li);
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input id="btnEnter" value="Konvertera" type="button"/>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
i would recommend using addEventListener which is much simpler than calling functions inside html elements , and to do what you asking the split() method can do that with any string , if there is something you don't understand with this code i am happy to help
document.querySelector('.btnclick').addEventListener('click', function () {
const theName = document.getElementById('enter').value;
if (theName.includes(',')) {
theName.split(',').map(function (e) {
if (e !== '')
return document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${e}</li>`);
});
} else if (theName !== '' || theName.length !== 0) {
document
.querySelector('#converted_list')
.insertAdjacentHTML('afterbegin', `<li>${theName}</li>`);
}
});
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<input class="btnclick" value="Konvertera" type="button" />
<div id="converted_list">
<ul></ul>
</div>
</form>
document.querySelector("form").onclick=(ev,v)=>{
if (ev.target.tagName==="BUTTON") {
ev.preventDefault();
v=ev.target.previousElementSibling.value.trim();
ev.target.nextElementSibling.innerHTML=(v>""?"<li>"+v.replaceAll(",","</li><li>")+"</li>":"");
}
}
<html>
<head></head>
<body>
<form>
<fieldset>
<textarea id="enter" onkeyup=""></textarea>
<button>Konvertera</button>
<div id="converted_list"><ul></ul></div>
</fieldset>
</form>
</body>
</html>
Related
What I am trying to achieve is a dropdown menu whose options the user will create by inputting the text content of the option they want to create. I have achieved this but what I want is that the user can delete an option if. I cant figure out how to do this. Help please. Buttons, input fields, anything is fine, but please use vanilla Javascript.
<!DOCTYPE html>
<html>
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
</div>
<script>
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
</script>
</html>
This is one of the procedures you can follow:
Create a function called deleteOption
Inside function, loop through the selectBoxElem variable and find the selected option. Then Remove the element
Attach the function to a button.
Example:
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
function deleteOption() {
const selectBoxElem = document.getElementById("sel");
for (var i = 0; i < selectBoxElem.length; i++) {
if (selectBoxElem.options[i].value == selectBoxElem.value)
selectBoxElem.remove(i);
}
}
<!DOCTYPE html>
<html>
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
<button id="button" onclick="deleteOption()">
Delete Selected Option
</button>
</div>
</html>
select element has options collection. The collection has remove method. You can use it like so;
const select = document.querySelector('select'),
options = select.options;
options.remove(select.selectedIndex);
Here is a complete solution which I rewrote to use eventListeners
document.getElementById("name").addEventListener("click",function(e) {
const tgt = e.target;
const src = document.getElementById('inputname');
const sel = document.getElementById("sel");
const inputval = src.value;
src.value="";
if (tgt.id==="add") {
if (sel.querySelector("option[value="+inputval+"]")) {
alert("That already exists")
}
else {
sel.options[sel.options.length] = new Option(inputval,inputval)
sel.value = inputval; // focus the new value
}
}
else if (tgt.id==="del") {
if (sel.selectedIndex === 0) return;
if (inputval) sel.value = inputval; // if filled in, we use it
const curOpt = sel.options[sel.selectedIndex]; // in any case remove the selected option
if (curOpt) {
curOpt.remove();
sel.selectedIndex = -1;
}
}
})
<div id="name">
<select id="sel"><option value="">Please select</option></select>
<input type="text" class="auto-save" id="inputname">
<button type="button" id="add">Create Option</button>
<button type="button" id="del">Remove Option</button>
</div>
Here you go with a solution
function newnamefunc() {
const inputval = document.getElementById('inputname').value;
const createname = document.createElement("option");
createname.setAttribute("class", "option")
const namevalue = document.createTextNode(inputval);
createname.appendChild(namevalue);
const element = document.getElementById("sel");
element.appendChild(createname);
}
function deleteOption() {
const element = document.getElementById("sel");
element.remove(element.selectedIndex);
}
<div id="name">
<select id="sel"></select>
<input type="text" class="auto-save" id="inputname">
<button id="button" onclick="newnamefunc();document.getElementById('inputname').value='';">
Create Option
</button>
<button id="button" onclick="deleteOption();">
Delete Option
</button>
</div>
Documentation: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_remove
use this:
function RemoveOption(){
var Element = document.getElementById("sel");
Element.remove(Element.selectedIndex);
}
Create new button in html
<button id="button" onclick="remove(document.getElementById('inputname').value);document.getElementById('inputname').value='';">
Delete Option
</button>
And add js function
function remove(val) {
var selectobject = document.getElementById("sel");
for (var i=0; i<selectobject.length; i++) {
if (selectobject.options[i].value == val)
selectobject.remove(i);
}
}
I'm trying to compare a input value with two paragrapah to check if the input value exists in both paragraph. So, I did this below. But the code is not working well :/. Could someone explain how to do it?
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
jQuery(function ($) {
var a = $('#billing_district').val().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split();
var b = $('.regions').text().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split(", ");
var index = $.grep(b, function (element, index) {
if ($.inArray(element, a) != -1) {
console.log(element);
}
});
});
This works, though you did not specify that the code should look at whole terms between commas. This code outputs true even if two letters occur in all the p's.
But you could add an extra loop to check the splitted strings.
jQuery(function($) {
const $input = $('#billing_district');
const b = $('.regions');
$('#billing_district').on('keyup', function(){
let a = $input.val();
let count = 0
$.each(b, function(i, p) {
console.log($(p).text().replace(/\s/g, ""),a);
if ($(p).text().replace(/\s/g, "").includes(a)) {
count++;
}
});
let valueIsInAllParagraphs = (count == 3);
console.log(valueIsInAllParagraphs);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
I am currently taking Wes Boros JS 30 challenge and for this particular class, we created a list where we add foods we like. As an extra assignment, we are to create a select all function, an unselect all function, and a delete function. I was able to successfully create a select all function where once you click that button, it selects all the items on the current list. My issue is that the delete function I created deletes everything, except for one or two items. Those undeleted items still remain checked, but I have to click on the delete button again in order for it to delete. FYI: I local storage was incorporated in this exercise.
Can somebody help me out and also explain what I was doing wrong?
Here is a jsfiddle of it as well
Here is how I have my HTML set up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<h2>LOCAL TAPAS</h2>
<p></p>
<ul class="plates">
<li>Loading Tapas...</li>
</ul>
<form class="add-items">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+ Add Item">
</form>
<input type="button" onclick="selectAll()" value="Select All"/>
<input type="button" onclick="UnSelectAll()" value="Unselect All"/>
<input type="button" onclick="deleteItem()" value="delete Item"/>
</div>
</body>
</html>
Here is my Javascript:
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = JSON.parse(localStorage.getItem('items')) || [];
//DELETE FUNCTION
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
for(var i = 0; i < boxes.length; i++){
box = boxes[i];
txt = texts[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
//SELECT ALL FUNCTION
function selectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = true;
}
}
//UNSELECT ALL FUNCTION
function UnSelectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = false;
}
}
//ADD ITEM FUNCTIO
function addItem(e){
e.preventDefault()
const text = (this.querySelector('[name=item]')).value;
const item = {
text,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}
//DISPLAY THE HTML FUNCTION
function populateList(plates =[], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input class="chk" type="checkbox" name="item" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label class="txt" name="item" for="item${i}">${plate.text}</label>
</li>
`
}).join('');
}
function toggleDone(e){
if(!e.target.matches('input')) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem)
itemsList.addEventListener('click', toggleDone)
populateList(items, itemsList);
//DELETE ITEM EVENT HANDLER
itemsList.addEventListener('click', deleteItem);
The reason why your delete function wasn't working properly it's because Node.childNodes returns a live NodeList which means when you use removeChild on each element in the collection the other elements gets rearranged and the length of list get's smaller causing you to skip some of them so you should convert your html collection to an array using Array.from
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
arrbox = Array.from(boxes)
arrtext = Array.from(texts)
for(var i = 0; i < arrbox.length; i++){
var box = arrbox[i];
var txt = arrtext[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
Here is working jsfiddle
Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}
I found this fiddle and I am trying to get it to work...I can not figure out why the names are not being added to the list, for some reason Add button is acting like a submit button and I can not tell why...It should add all the numbers to a list so when I click submit, then it should send the numbers in an array..
JavaScript:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("inputNames");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByTagName("inputNames").length;
var newGuy1 = document.createElement("inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
HTML:
<h1>Enter Name</h1>
<div id="mainName">
<h2>name</h2>
<label for="name">Add Names: </label>
<input id="name" type="text">
<button id="addName">Add</button>
<form>
<div id="names">
</div>
<input METHOD="POST" action="text.php" type="submit" value="Submit">
</form>
</div>
I've seen
document.createElement("inputNames");
Shouldn't be
document.createElement("input");
?
Because this /^[0-9]{10}$/; will accept only 10 numbers and only that, try entering 1234567890 and you will see no error.
I'm not sure why your "name" field is restricted to 10 digit numbers, but I've got the thing to work.
http://jsfiddle.net/y8Uju/4/
I think the problem was that you were trying to create an element with the tag name inputNames, but that's not a valid tag. Instead I changed it to create inputs, and set the class to inputNames.