As a newcomer to jQuery, I am facing a challenge in my current project where I need to implement a list of input fields with certain conditions:
- Whenever text is entered into the first input field, another input field should be dynamically added
- If the characters are deleted and the input field becomes empty, it should be removed
- All the values entered should be combined into a single string at the end
- If possible, the values should be stored in an array (optional)
Due to my limited knowledge of jQuery, I have managed to achieve the first condition but I am unsure if my solution is optimal.
http://jsfiddle.net/kubydpvr/5/
$(document).ready(() => {
let count = 0;
let arr = [createInput(0)];
$(".Fields").append(arr);
function addListField() {
$("#id_" + count).one("input", addListField);
$("#id_" + count).attr({
type: "text"
});
arr.push(createInput(count + 1, "hidden"));
$("#id_" + count).after(createInput(count + 1, "hidden"));
count++;
}
function createInput(id, type = "text") {
return (
"<input type=" + type + ' value = "" id = id_' + id + " ></input>"
);
}
addListField();
});
body {
font-size: 17px;
font-family: "Courier New", Courier, monospace;
background: whitesmoke;
line-height: 1.5em;
}
header {
background: rgb(1, 60, 14);
color: whitesmoke;
padding: 20px;
text-align: center;
border-bottom: 4px rgb(26, 0, 62) solid;
margin-bottom: 10px;
}
.container {
margin: auto;
padding: 10px;
width: 200px;
}
.Fields {
display: flex;
flex-direction: column;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<header>
<h1>I Learn jQuery.</h1>
<div class="container">
<div class="Fields"></div>
</div>