(JS) Remove an option from select box JUST ONCE after calling function - javascript

I have this code where I want to add text to the select box when calling a function via clicking an input button.
I want the select box to have a default text when the page is loaded and no value is added to the array. And I want this text to vanish but I could still add many values from the input box and make them show on the select box.
So I made the input and select box with the following:
let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []
function adicionar() {
if (isNumero(num.value) && !inLista(num.value, valores)) {
lista.options[0] = null //
valores.push(Number(num.value))
let item = document.createElement('option')
item.text = `Valor ${num.value} adicionado.`
lista.appendChild(item)
} else {
window.alert('Valor inválido ou já existe!')
}
}
<div>
<p>TYpe a number between 1 and 100: <input type="number" name="num1" id="numtxt">
<input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>
<div>
<p>
<select name="sel1" id="seltxt" size="10">
<option>Type a number above!</option>
</select>
</p>
<p><input type="button" value="End" onclick="finalizar()"></p>
</div>
I've tried a lot of commands with boxvar.options[0] = null and boxvar.remove(0)but they all kept removing the first value which I need for the program.
Any sugestions?

let num = document.querySelector('input#numtxt')
let lista = document.querySelector('select#seltxt')
let res = document.querySelector('div#res')
let valores = []
function adicionar() {
if (isNumero(num.value) && !inLista(num.value, valores)) {
if(!valores.length) {
// If there are no values on list, delete whatever is inside of select
lista.innerHTML = ''
}
valores.push(Number(num.value))
let item = document.createElement('option')
item.text = `Valor ${num.value} adicionado.`
lista.appendChild(item)
} else {
window.alert('Valor inválido ou já existe!')
}
}

This is slightly verbose for clarity - if we add a data attribute we can filter on that and remove it if it exists. We can also filter by values and not add if the new one exists (it could be a data attribute if you do not want to set the value.
let lista = document.querySelector('#seltxt');
let res = document.querySelector('#res');
let valores = [];
function adicionar() {
let num = document.querySelector('#numtxt');
let opts = [...lista.options].filter((element, index) => {
return element.dataset.default == "default";
});
console.log(opts);
if (opts.length) {
opts[0].remove();
}
let newValue = Number(num.value);
// now if it already exists, don't add it
let matchOpt = [...lista.options].filter((element, index) => {
return element.value == newValue;
});
// we already have it so jump back out
if (matchOpt.length) {
return;
}
valores.push(newValue);
let item = document.createElement('option');
item.text = `Valor ${num.value} adicionado.`;
item.value = newValue;
lista.appendChild(item);
}
<div>
<p>Type a number between 1 and 100: <input type="number" name="num1" id="numtxt">
<input type="button" value="Adicionar" onclick="adicionar()"></p>
</div>
<div>
<p>
<select name="sel1" id="seltxt" size="10">
<option data-default="default">Type a number above!</option>
</select>
</p>
<p><input type="button" value="End" onclick="finalizar()"></p>
</div>

Related

Increment and update value in the total number after insert new rows dynamically

EDIT: I have updated the code with the answers.
I have a increment function that is working fine. However:
1. I would like to set some limits based on the total number available in one of the span. For example, 10. So the incrementing can't be more than 10. #DONE
Another issue is that I am planning to have multiple rows and before I save I want to make sure if we count the increments in every row it should not be more than 10 as well. If it decrease the total number (span) dynamically would be nice.
I'm adding rows dynamically with the ADD button, how can I add news rows that actually work with the current functions? Mine rows just clone the first one and the increment function is disabled.
document.addEventListener('DOMContentLoaded', async function() {
document.querySelector('#addlocationdest').addEventListener('click', add);
});
function add() {
var x = 1;
var container = document.getElementById('destination');
var detail = document.getElementById('row');
var clone = detail.cloneNode(true);
clone.id = "destination" + x;
x++;
container.appendChild(clone);
}
window.addEventListener("load", () => {
let elTotalQuantity = document.querySelector("#totalqty");
let totalQuantity = parseInt(elTotalQuantity.innerHTML);
function getSumOfRows() {
let sum = 0;
for (let input of document.querySelectorAll("form .row > input.quantity"))
sum += parseInt(input.value);
return sum;
}
for (let row of document.querySelectorAll("form .row")) {
let input = row.querySelector("input");
row.querySelector(".increment").addEventListener("click", () => {
if (getSumOfRows() >= totalQuantity) return;
input.value++;
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
});
row.querySelector(".decrement").addEventListener("click", () => {
if (input.value <= 0) return;
input.value--;
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
});
}
});
<div id="location" class="hide">
<div class="title">Transfer details</div><br>
<div class="line padded-s">Total Quantity: <span>10</span></div>
<br>
<form>
<label>New Total Quantity at this location: <span id="totalqty">10</span></label>
<br>
<div id="destination">
<div id="row" class="row">
<button type="button" class="decrement">-</button>
<input type="text" class="quantity" value="0" readonly/>
<button type="button" class="increment">+</button>
<a>Location: </a>
<input type="text" class="location" value="0" readonly/>
</div>
</div>
</form>
<label>Total being transfer: <p id="total-sum"></p></label>
<br>
<button type="button" id="addlocationdest">ADD</button>
<button type="button" id="removelocationdest">REMOVE</button>
</div>
Prologue
As long as the total quantity is fixed at the beginning of the script-execution, this works. Otherwise, it would be best to save the actual allowed total quantity as an attribute, and observe it using a MutationObserver. That way you can update your max. value in your code dynamically, when the total quantity-attribute changes. You can define custom attributes by naming them "data-*" where "*" is a custom name.
Solution for your problem
You are using the same ID on multiple elements. What you meant were classes, so change id="increment" to class="increment", and the same for decrement.
Since we don't want to input something with the buttons, but add listener to them, I'd say it is better to actually use <button>. In forms, buttons act as type="submit", which we don't want, so we need to change it to type="button".
Since the rows and the total quantity actually belong together, it is wiser to place them together into one <form>-element. However, you can still group the buttons and inputs as a row together using <div>.
Now regarding the in-/decrementing of the row's values and the total quantity:
Save the allowed total quantity in a variable
Add event-listener to the corresponding buttons
If action is valid, change row's value
Update total quantity number to totalQuantity - getSumOfRows()
To add new rows dynamically, we create and setup such an element, and append it to the form. See the appendNewRow()-function below.
Sidenote
I have added the readonly attribute to the input-fields so that you cannot enter numbers via keyboard.
window.addEventListener("load", () => {
let elTotalQuantity = document.querySelector("#totalqty");
let totalQuantity = parseInt(elTotalQuantity.innerHTML);
function getSumOfRows() {
let sum = 0;
for (let input of document.querySelectorAll("form .row > input.quantity"))
sum += parseInt(input.value);
return sum;
}
function updateTotalQuantity() {
elTotalQuantity.innerHTML = totalQuantity - getSumOfRows();
}
function appendNewRow() {
let row = document.createElement("div");
row.classList.add("row");
let child;
// input.quantity
let input = document.createElement("input");
input.classList.add("quantity");
input.value = "0";
input.setAttribute("readonly", "");
input.setAttribute("type", "text");
row.append(input);
// button.increment
child = document.createElement("button");
child.classList.add("increment");
child.innerHTML = "+";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
if (getSumOfRows() >= totalQuantity) return;
input.value++;
updateTotalQuantity();
});
row.append(child);
// button.increment
child = document.createElement("button");
child.classList.add("decrement");
child.innerHTML = "-";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
if (input.value <= 0) return;
input.value--;
updateTotalQuantity();
});
row.append(child);
// button.remove-row
child = document.createElement("button");
child.classList.add("remove-row");
child.innerHTML = "Remove";
child.setAttribute("type", "button");
child.addEventListener("click", () => {
row.remove();
updateTotalQuantity();
});
row.append(child);
document.querySelector("form .rows").append(row);
}
document.querySelector("form .add-row").addEventListener("click", () => appendNewRow());
appendNewRow();
});
<form>
<label>Total Quantity: <span id="totalqty">10</span></label>
<br>
<div class="rows">
</div>
<button type="button" class="add-row">Add new row</button>
</form>
QuerySelector only selects the first occurrence so you haven't really added a listener to the second "row". You should use querySelectorAll but, instead of unique ids, use classes.
<input class="increment" type="button" value="+" />
Now you can use document.querySelectorAll(".increment") to get all elements in an array.
You can traverse in the DOM by using parentElement. By knowing which button you clicked, you can traverse up to the form element and then select the first child - which is an input. A more dynamic way would be to use querySelector to select the input, in case the HTML change in the future. Anyway, that's how you can know which input to manipulate based on where the buttons are in the DOM.
I added two global variables, totalSum and maxSum. maxSum is fetched from your span element (which I assigned an unique id to). totalSum makes sure that all inputs combined doesn't exceed maxSum.
You had some duplicate code, so I refactored it into a new method: changeValue.
In all, I think the code speaks for itself.
Oh, this code doesn't take into account that the user can change the value inside the input. I will leave that for you to figure out with an "oninput" listener on each text input.
var totalSum = 0; // 3
var maxSum = 0
var totalSumElement = null;
document.addEventListener('DOMContentLoaded', async function() {
totalSumElement = document.getElementById('total-sum');
maxSum = document.getElementById('max-sum').innerText;
var incrementElements = document.querySelectorAll('.increment'); // 1
var decrementElements = document.querySelectorAll('.decrement');
addListener('click', incrementElements, incrementValue);
addListener('click', decrementElements, decrementValue);
});
function addListener(type, elementArr, func) {
for (element of elementArr) {
element.addEventListener(type, func);
}
}
function withinRange(newValue) {
var maxReached = newValue > maxSum; // 3
var zeroReached = newValue < 0;
return !maxReached && !zeroReached;
}
function changeValue(event, change) { // 4
if (withinRange(totalSum + change)) {
let parent = event.currentTarget.parentElement; // 2
let input = parent.children[0];
let value = parseInt(input.value) || 0;
if (withinRange(value + change)) {
input.value = value + change;
totalSum = totalSum + change;
}
}
totalSumElement.textContent = `Total: ${totalSum}`;
}
function incrementValue(event) {
changeValue(event, 1);
}
function decrementValue(event) {
changeValue(event, -1);
}
#totalqty {
padding-bottom: 1rem;
}
<div id="totalqty" class="line padded-s">Total Quantity: <span id="max-sum">10</span></div>
<form>
<input type="text" value="0" />
<input class="increment" type="button" value="+" />
<input class="decrement" type="button" value="-" />
</form>
<form>
<input type="text" value="0" />
<input class="increment" type="button" value="+" />
<input class="decrement" type="button" value="-" />
</form>
<p id="total-sum"></p>

append various inputs to display it as a string

Hey I have the following problem, I want to display two text inputs as a list element but I do not know how to append various variables. The code below only shows the first input in the list.
function addLi () {
let x = document.createElement("LI");
let name= document.createTextNode(document.getElementById("name").value);
let city= document.createTextNode(document.getElementById("city").value);
x.appendChild(name)
document.getElementById("list").appendChild(x);
return false;
}
You could do it this way (just an example with a loop):
document.getElementById('add-btn').addEventListener('click', addLi);
function addLi() {
const items = ['name', 'city'];
for (let item of items) {
const li = document.createElement('li');
const value = document.createTextNode(document.getElementById(item).value);
li.appendChild(value);
document.getElementById("list").appendChild(li);
}
}
<input id="name" value="John Doe"> <input id="city" value="Sydney">
<button id="add-btn">Add to list</button>
<ul id="list"></ul>

Disable input field if is already filled Javascript (Sudoku)

I am bulding a Sudoku Solver. All fields of the sudoku can be edited. When the user clicks on "New Sudoku" some of those fields are filled with numbers. At the moment these "filled" fields can still be edited by the user. I want them to be disabled so that the number of the "filled" fields can not be changed.
I am a beginner and grateful for any help :)
My sudoku so far
function createField(event) {
let gridCont;
let fieldCont;
let sudokuBox = document.getElementById("sudokuBox");
gridCont = document.createElement("div");
gridCont.classList.add("grid-cont");
for(row=1; row<=9; row++) {
fieldCont = document.createElement("div") //The 3x3 grid
fieldCont.classList.add("field-cont");
fieldCont.classList.add("indexBig"); //gives index (3x3)
for(col=1; col<=9; col++) {
let dataCell = document.createElement("input")
dataCell.classList.add("sudoku-cell");
dataCell.classList.add("data-cell");
dataCell.classList.add("indexSmall");
fieldCont.appendChild(dataCell);
}
gridCont.appendChild(fieldCont);
}
sudokuBox.appendChild(gridCont);
}
function populateSudoku(JObject){
let fill = document.querySelectorAll(".indexBig");
JObject.sudokuJSON.forEach((bigCellEl, i)=> {
bigCellEl.forEach((cellNumb, j)=> {
if(cellNumb > 0){
fill[i].children[j].value=cellNumb;
//cellNumb.disabled = true; My first idea, but it doesn't work...**
}
});
});
}
You can use the readonly property:
fill[i].children[j].readonly = true;
You could attach event.preventDefault() to onkeydown for all the generated inputs:
const createNew = () => {
//irrelevant
let inputs = document.querySelectorAll("input");
let random = Math.floor(inputs.length * Math.random());
let input = inputs[random]
input.value = Math.round(Math.random() * 10);
//attach prevent default on keydown
input.onkeydown = (event) => event.preventDefault();
}
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<button onclick="createNew()">Click</button>

Delete Child Span after Child Span Delete remaing Child auto rearrange why?

Here is my Javascript code:
function validspan() {
var data = document.querySelector('.keyword-input').value;
var nodes = document.querySelectorAll('.keywords-list span');
var str = Array.prototype.map.call(nodes, function(node) {
return node.textContent;
}).filter(a => !!a).join(",");
var arr = str.split(',');
for (var k = 0; k < arr.length; k++) {
if (data == arr[k]) {
alert("Don't Enter Same Skill");
let list = document.querySelector('.keywords-list');
let array = arr[k].indexOf(data);
list.removeChild(list.childNodes[array]);
return true;
} else {
alert('different values');
return false;
}
}
}
and html code where runtime spans create
<input type="text" class="keyword-input with-border #error('name') is-invalid #enderror" name="skills" placeholder="Add Skills">
<div class="invalid-feedback" style="color: red;font-size: 20px"></div>
<button type="button" class="keyword-input-button ripple-effect" onclick="validspan()"><i class="icon-material-outline-add" ></i></button>
</div>
<div class="keywords-list">
<!-- keywords go here -->
</div>
If value match then delete index but in this my code only 0 index
check and delete 0 idex. my requirment is when same value any index
then delete index
i guess you are looking for something like this?
(() => {
const btnEl = document.querySelector('#add_skill');
const inputEl = document.querySelector('#skills');
const resultsEl = document.querySelector('#keywords-list');
const arr = [];
arr.add = function(val) {
this.push(val);
resultsEl.innerHTML = arr.map(item => `<span>${val}</span>`).join('');
};
btnEl.addEventListener('click', (e) => {
let val = inputEl.value;
if (!val) {
console.error(`A value is required`);
return;
}
if (arr.includes(val)) {
console.error(`Don't Enter Same Skill`);
return;
}
arr.add(val);
});
})();
<input type="text" class="keyword-input with-border #error('name') is-invalid #enderror" id="skills" name="skills" placeholder="Add Skills">
<div class="invalid-feedback" style="color: red;font-size: 20px"></div>
<button type="button" id="add_skill" class="keyword-input-button ripple-effect"><i class="icon-material-outline-add" ></i>Add</button>
</div>
<div class="keywords-list" id="keywords-list">
<!-- keywords go here -->
</div>
in your for loop, you are terminating the execution directly and breaking from it by using the return keyword in both the if statement and the else statement, so basically what your code is doing is just testing the first index (0) and omitting all the other indexes!
you need to remove the return statements and then continue editing your code to handle other cases!
you can understand better about return inside a for loop with the answers in this question : question
hope that helped!

Constructor function didn't save querySelector(x).value

I am working on a small APP for calculating Budgets and i am stuck on a problem i don't understand. I used a constructor for getting the user inputs in a few input fields.
I tried to setup this part in a constructor to learn more about prototyping and constructor functions and to challenge myself. I don't get why the constructor GetInput not holding my input.values
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
// EVENTLISTENER Constructor:
function EventListner(selector, listner, fnt) {
this.selector = selector;
this.listner = listner;
this.fnt = fnt;
document.querySelector(selector).addEventListener(listner, fnt);
};
function GetInput(operator, description, value) {
this.operator = operator;
this.description = description;
this.value = value;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
const clickListener = new EventListner('.add__btn', 'click', () => {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
});
const enterKeyListener = new EventListner('.add__value', 'keypress', (e) => {
if (e.keyCode == 13) {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
// ON ENTER SAVE VALUES IN AN ARRAY
// IF PLUS INTO incomeArr, ON MINUS INTO expenseArr
console.log('enter pressed');
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
}
});
Output is:
GetInput {operator: "inc", description: "", value: ""}
Only works when i:
document.querySelector('.add__value').value;
directly into the console.
Your initial values are empty for the input fields. And your code is executing right away. That's why you are getting empty value for those fields.You can try adding some predefined values for those input field.
Code with predefined value for the input fields :
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
function GetInput(operator, description, value) {
this.operator = operator;
this.description = description;
this.value = value;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" value="mydesc" class="add__description" placeholder="Add description">
<input type="number" value="2" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
Note : You need to add event listener to listen to any change in your input field values. If user type anything then you can proceed to instantiate your constructor function
You are getting this issue because you need to trigger an event to for calculate, and one more thing you have to use something else other then const, because you cannot reinitialize value in constant variables, Current code is execute on loading page, So the values is initialized to that will not change
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
So please change const with var or let, Or you can set default value to description and value

Categories

Resources