JSFiddle - React, Tailwind, and code Playground
by Alexey Ukolov
HTML
<form action="#">
<input type="text" class="input-key" value="" placeholder="Enter key">
<input type="text" class="input-val" value="" placeholder="Enter value">
<input type="text" class="input-key-del" placeholder="Delete key">
<button type="button" class="btn-add">Add key and value</button>
<button type="button" class="btn-del">Delete key</button>
<div class="output"></div>
</form>
JavaScript
const obj = {};
const btnAdd = document.querySelector('.btn-add');
const btnDel = document.querySelector('.btn-del');
const output = document.querySelector('.output');
function render() {
let str = '';
for (let key in obj) {
str += `Ключ: ${key}, Значение: ${obj[key]} <br>`
}
output.innerHTML = str;
}
function add(e) {
e.preventDefault();
let inputKey = document.querySelector('.input-key').value;
let inputValue = document.querySelector('.input-val').value;
if (inputKey !== '' && inputValue !== '') {
obj[inputKey] = inputValue;
}
render();
}
btnAdd.addEventListener('click', add);
function remove(e) {
e.preventDefault();
const inputKeyDel = document.querySelector('.input-key-del').value;
if (inputKeyDel in obj) {
delete obj[inputKeyDel];
}
render();
}
btnDel.addEventListener('click', remove);