****UPDATE****
I was able to have below issue work with the help of #JasonB.
In addition, I also have another 3 textareas on the same form that will only show when its checkbox is clicked. How will I add that on my current script? I tried grouping it the same way as TextBoxesGroup but just giving another id but when I hit submit, even if I didn't clicked the checkbox, values inside are being submitted. Thank you so much in advance. I'm really new to programming and I'm trying to learn the basics.
HERE'S MY CODE for the checkbox
<textarea id="text" >NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text1">NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text2">NAME-
ADDRESS-
ETC-</textarea>
<input type="checkbox" id="myCheck" onclick="myFunction()">DETAILS
<input type="checkbox" id="myCheck1" onclick="myFunction1()">DETAILS
<input type="checkbox" id="myCheck2" onclick="myFunction2()">OTHERS
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
function myFunction1() {
var checkBox1 = document.getElementById("myCheck1");
var text1 = document.getElementById("text1");
if (checkBox1.checked == true){
text1.style.display = "block";
} else {
text1.style.display = "none";
}
}
function myFunction2() {
var checkBox2 = document.getElementById("myCheck2");
var text2 = document.getElementById("text2");
if (checkBox2.checked == true){
text2.style.display = "block";
} else {
text2.style.display = "none";
}
}
</script>
PREVIOUS QUESTION
I have a form with multiple textareas. I'm not familiar with any databases so instead of using one, I prefer using or saving the values/inputs of my textarea to another textarea on submit. I was able to make it work but with those textareas being added dynamically, I only get the first textarea.
here's my script
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 15) {
alert("Only 15 textboxes allowed");
return false;
}
$('<div/>',{'id':'TextBoxDiv' + counter}).html(
$('<textarea/>',{'id':'myTextArea' + counter ,'class':'myTextArea'}).html( 'STEP ' + counter + ' : ' )
)
.appendTo( '#TextBoxesGroup' )
$("#myTextArea" + counter).each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
$(document).ready(function() {
$("#btn-primary").click(function() {
e=1;
var text55 = $('#textarea55').val();
var text56 = $('#textarea56').val();
var text57 = $('#textarea57').val();
var text58 = $('#textarea58').val();
var text59 = $('#textarea59').val();
var text60 = $('#textarea60').val();
var text61 = $('#textarea61').val();
var text62 = $('#textarea62').val();
var myTextArea = $('#myTextArea'+e).val();
$('#inputTextToSave').val( $('#inputTextToSave').val()+text55+'\n'+text56+'\n'+text57+'\n'+'TROUBLESHOOTING NOTES'+'\n'+myTextArea+'\n'+text58+'\n'+text59+'\n'+text60+'\n'+text61+'\n'+text62+'\n');
e++;
});
here's my html
<textarea id="textarea55" name="caller"></textarea><br>
<textarea id="textarea56" name="auth"></textarea><br>
<textarea id="textarea57" name="issue"></textarea><br>
<label>TROUBLESHOOTING NOTES:</label><br>
<body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv"></div></div>
<input type='button' value='ADD TS STEPS' id='addButton' class="bubbly-button">
<input type='button' value='REMOVE TS' id='removeButton' class="bubbly-button"><br><\body>
<textarea id="textarea58" name="acct"></textarea><br>
<textarea id="textarea59" name="tid"></textarea><br
<textarea id="textarea60" name="resolution"></textarea><br>
<textarea id="textarea61" name="case"></textarea><br>
<textarea id="textarea62" rows="1" disabled>YANA</textarea>
<input type='button' value='SUBMIT' id='btn-primary' class="bubbly-button"><br>
my css
div {
padding: 1px;
}
textarea {
outline: none;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
}
.myTextArea {
width: 535px;
min-height: 14px;
overflow-y: hidden;
font-size: 14px;
border: 3px solid orange;
background-color:white;color:mediumvioletred;
display: block;
}
body{
font-size: 14px;
font-family: 'tempus sans ITC', 'Arial';
color: mediumvioletred;
text-align: center;
background-color: pink;
}
Your dynamically created textareas are all in #TextBoxesGroup.
To select them all at the time of submission, you can call $('#TextBoxesGroup textarea'). To append their contents into a string with '\n' characters separating them you can use jQuery's .map function to get the text of each element in an array wrapped in a jQuery object, .get to get the underlying array, and .join to concatenate the strings with '\n' as the glue.
var contents = $('#TextBoxesGroup textarea')
.map(function() {
return $(this).text();
})
.get()
.join('\n');
console.log( contents );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="TextBoxesGroup">
<div><textarea>One</textarea></div>
<div><textarea>Two</textarea></div>
<div><textarea>Three</textarea></div>
</div>
Related
I'm trying to make the checkbox behave with the Enter key (when tabbed into) the same way it usually does with the space bar or when clicked. I cooked up a case where the checkbox is indeed being checked, but it then doesn't act like it should, i.e. I want it to display a previously hidden text and disappear itself. How can I achieve this? Adding something like document.getElementById("myCheck").click() doesn't work, though.
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
e.target.checked = !e.target.checked;
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
All you need to do is trigger the click event, that will check the box. If you manually set checked and then trigger click it will undo the manual setting.
document.addEventListener('keydown', (e) => {
if( e.key === "Enter" && e.target.classList.contains('myCheck')){
//e.target.checked = !e.target.checked;
e.target.click()
}
})
function myFunction() {
var form = document.getElementById("form");
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked === true){
form.style.display = "none";
text.style.display = "block";
} else {
form.style.display = "inline-block";
text.style.display = "none";
}
}
* {
margin: 10px;
padding: 0;
font-size: 50px;
}
input {
width: 30px;
height: 30px;
}
p {
color: red;
text-transform: uppercase;
}
<form class="form" id="form" style="display:inline-block">
<input type="checkbox" class="myCheck" id="myCheck" onclick="myFunction()">
<label for="myCheck">Checkbox</label>
</form>
<p id="text" style="display: none;">checkbox is checked</p>
I am trying to change the display property of some text using JS, upon button click.
I have confirmed that the function is firing and running correctly using debugger, but for some reason, I can't grab the specific element I need to change, and assign it to a variable. I also have jquery set up on the page.
I have tried using the console, and document.getElementById('warning-textID') returns the correct element, but when I try to set it to a variable in console, it returns undefined. Am I missing something super obvious here?
Here is the HTML, function and css.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
});
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if(enteredValue == validParam){
console.log('do the thing')
if(cookieCreated == false && enteredValue == validParam){
warning.innerText = "Please enable cookies";
warning.style.display = "";
return;
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "";
enteredValue.value = "";
return;
}
}
.warning-text {
color: red; text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper" >
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I fixed some mistakes and it worked.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if (enteredValue === validParam) {
console.log('do the thing')
if (cookieCreated == false && enteredValue === validParam) {
warning.innerText = "Please enable cookies";
warning.style.display = "block";
return;
}
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "block";
enteredValue.value = "";
return;
}
}
});
.warning-text {
color: red;
text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper">
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I'm writing an <input type="number"> with - and + button for an ecommerce cart.
The structure of each group is:
1x <button class="minus" data-prod="prod_id_int">
1x <input type="number" id="prod_id_int">
1x <button class="plus" data-prod="prod_id_int">
What I'm trying to do now is disabling the button - if the value of the input type number is < 1.
To achieve it, based on my script, I have to disable not the general <button class="minus"> but the specific <button class="minus" data-prod="prod_id_int">.
I tried this
$(buttonClass).data('prod', dataProd).prop('disabled', true);
and it actually prevents the quantity from being < 1 BUT it doesn't really add the property disabled to the button. I'm not sure, then, that it's the right way. Can someone explain me how to achieve it?
Here the working snippet
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = parseInt(inputToChangeValue) - parseInt(1);
if (newValue < 1) {
$(buttonClass).data('prod', dataProd).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 1.5%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="62">
<button class="plus" data-prod="90">+</button>
Here is solution.
$('.'+buttonClass).data('prod', dataProd).prop('disabled', true);
All you need is to concatenate . symbol to your class.
buttonClass returns only the className, such as minus and you need jquery selector, like this: $('.minus')
Also, I recommend you to use this: var newValue = --inputToChangeValue; for a simply way to decrement value, instead var newValue = parseInt(inputToChangeValue) - parseInt(1);
$(document).ready(function() {
$('button').on('click', function() {
var buttonClass = $(this).attr('class');
//console.log(buttonClass);
var buttonID = $(this).attr('id');
//console.log(buttonID);
var dataProd = $(this).data('prod');
var inputToChange = $('#' + dataProd);
var inputToChangeValue = $('#' + dataProd).val();
if (buttonClass == 'minus') {
var newValue = --inputToChangeValue;
if (newValue < 1) {
$('.'+buttonClass).filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', true);
//$(buttonClass).data('prod="' + dataProd + '"').prop('disabled', true);
//$(buttonClass + '.[data-prod="' + dataProd + '"]').attr(disabled=disabled); //.prop('disabled', true)
//alert('NOPE');
} else {
$('#' + dataProd).val(newValue);
//console.log(inputToChangeValue);
}
} else if (buttonClass == 'plus') {
var newValue = parseInt(inputToChangeValue) + parseInt(1);
$('.minus').filter(function() {
return $(this).data("prod") == dataProd
}).prop('disabled', false);
if (newValue > 99) {
alert('NOPPPPEE');
} else {
$('#' + dataProd).val(newValue);
console.log(inputToChangeValue);
}
}
});
});
.plus,
.minus {
width: 10%;
height: auto;
background-color: #EF1B1F;
border-radius: 50%;
text-align: center;
display: inline-block;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="minus" data-prod="23">-</button>
<input type="number" class="qta" id="23" value="5">
<button class="plus" data-prod="23">+</button>
<br>
<button class="minus" data-prod="90">-</button>
<input type="number" class="qta" id="90" value="12">
<button class="plus" data-prod="90">+</button>
I'm doing a little noob project and making a simple "to-do list" and I'm stuck on something that seems so simple! I'm trying to pass the main up top from #myInput and pass it to the next down and so on. Right now, if you enter something then click add, it creates a blank new line at first for some reason then if you type something else and click add, what you typed before shows up on the next line. It will keep doing that for as long as you type something different in the input, but if you keep hitting add a couple times with the same thing in the input, nothing shows up. Then change the input again to something different and click add and all that will show up lol, but still no current line outputs from what you typed...going nuts. Any suggestions on the proper way to do this? I left a JSfiddle link to see exactly what is happening down below.
<div>
<form id="addThings" type="text">
<input type="text" id="myInput" placeholder="add to your to-do list" size="50" maxlength="40" autocomplete="off" autofocus>
<input type="button" id="addButton" value="add">
</form>
</div>
Also, when you click the button and it creates a new line down below it shifts everything around a bit..ideas on what needs to be changed in the css? Trying to get it a little smoother. Thanks!
$(function() {
var i = 2;
$('#addButton').click(function(e) {
var input = $('#myInput').val();
console.log(input);
var id = "newLine" + i;
var line = '<input type=\"text\" id=\"' + id + '\" size=\"50\" disabled><input type=\"checkbox\" >';
$('form').append(line);
var newId = "#" + id;
$('#myInput').change(function() {
$(newId).val(input);
});
i += 1;
});
});
JSFiddle
Try this. Providing a value to the input field before you append it works well.In your case there is an issue with javascript closure. To solve it just define the input variable outside of the click function
$(function() {
var i = 2;
$('#addButton').click(function(e) {
var input = $('#myInput').val();
console.log(input);
var id = "newLine" + i;
var line = '<input type=\"text\" id=\"' + id + '\" value=\"'+input+'\" size=\"50\" disabled><input type=\"checkbox\" >';
console.log(line);
$('form').append(line);
i += 1;
});
});
JSFIDDLE
Try assigning the input value to the value attribute of your new input when you create the new line:
$(function() {
var i = 2;
$('#addButton').click(function(e) {
var input = $('#myInput').val();
var id = "newLine" + i;
var line = '<input type=\"text\" id=\"' + id + '\" size=\"50\" value="' + input + '" disabled><input type=\"checkbox\">';
$('form').append(line);
var newId = "#" + id;
/*$('#myInput').change(function() {
$(newId).val(input);
});*/
i += 1;
});
});
body {
background-color: white;
}
div {
width: 750px;
margin: 0 auto;
margin-top: 200px;
margin-bottom: 0;
padding: 0;
}
form {
margin: 0 auto;
display: inline-block;
margin-bottom: 0px;
}
input {
padding: 10px 18px;
float: bottom;
}
input[type=text] {
border-left: white;
border-right: white;
border-top: white;
font-size: 20px;
i height: 21px;
text-align: center;
outline: none;
float: right;
background-color: white;
}
input[type=button] {
display: inline-block;
height: 25px border: 0;
margin: 0 auto;
font-size: 20px;
float: right;
}
input[type=checkbox] {
vertical-align: top;
width: 10%;
margin: 15px auto;
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
<div>
<form id="addThings" type="text">
<input type="text" id="myInput" placeholder="add to your to-do list" size="50" maxlength="40" autocomplete="off" autofocus>
<input type="button" id="addButton" value="add">
</form>
</div>
</body>
It's a closure/scope issue. Your variable input is inside the click function. Therefore it is not going to be in the scope of the change function.
Move the declaration of inputoutside of the click function.
Create a wrapper function.
That way all the variables needed are in the scope of addButtonScopeFunc and there only.
Those variables aren't needed in the global scope window. nor in the scope of the '#addButton' event function.
$(function() {
var addButtonScopeFunc = function (input, inputValChangeEl) {
var i = 2,
id = "newLine" + i,
newId = "#" + id,
line = '<input type=\"text\" id=\"' + id + '\" size=\"50\" disabled><input type=\"checkbox\" >';
console.log(input);
console.log(line);
$('form').append(line);
$(inputValChangeEl).change(function() {
$(newId).val(input);
});
i += 1;
};
$('#addButton').click(function(e) {
addButtonScopeFunc($('#myInput').val(), '#myInput');
});
});
To give an other example, just for showing up things.
You could "outscope" the $(inputValChangeEl).change(...) event function outside of addButtonScopeFunc in its own wrapper function handling over the input value as parameter.
$(function() {
var addButtonScopeFunc = function (input, inputValChangeEl) {
/* ... */
$('form').append(line);
changeInputVal(inputValChangeEl, newId, input);
i += 1;
},
changeInputVal = function (el, id, input) {
$(el).change(function() {
$(id).val(input);
});
};
$('#addButton').click(function(e) {
addButtonScopeFunc($('#myInput').val(), '#myInput');
});
});
Further reading: Javascript Scopes well explained
I made a way to add and remove fields using the input[type"number"]. I use jquery to do this but the way I did is not perfect. If there's a value in the field, the value will get erase if the number value is change because of using .remove(). Is there a better way to doing this?
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
<script>
$('#num').bind('keyup mouseup', function () {
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
</script>
My Fiddle
Try something like this. Instead of removing all of the inputs every time, this just removes the ones on the end, or adds more to the end.
The main difference between this one and yours is that I added var totNum = 0; to keep track of the current number of input there are. I then used that to determine how many to add/remove.
var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
var num = $(this).val();
if (num != "")
{
if (totNum == 0)
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
for (var i = num; i < totNum; i++)
{
$('.dynamicInput .row:last-child').remove();
}
for (var i = totNum; i < num; i++)
{
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
totNum = num;
if (totNum == 0)
{
$('.dynamicInput h4').remove();
$('.dynamicInput .row').remove();
}
}
});
input[type="number"] {
width: 200px;
height: 30px;
font-family: Arial, sans-serif;
font-size: 20px;
}
.row {
display: block;
margin-bottom: 15px;
}
body {
width: 100%;
padding: 40px;
}
input[type="text"] {
width: 100%;
}
.col1,
.col2 {
width: 45%;
display: inline-block;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
It's easier and less likely to fail using a data structure as a skeleton upon which you can build the view. Note that this technique requires an extra computation in order to save user inputs, this is the reason why I've added the "change" event.
In the following code snippet, I've made two panels side by side. The left one is a list of inputs, very close to yours, easy to adapt to your needs, while the right one allows to see the evolution of the "data" array according to user actions.
Both panels rely on the "data" array, in other words, as soon as new items are added to or removed from "data", or a single item is updated, both panels are fully rebuilt. Note that the "change" event takes advantage of event delegation in order to deal with newly added inputs.
Finally, the "update" functions update the entire data source or a single item of the data source when the corresponding input changes, while the "render" functions draw on the data source to keep the panels in sync with the data. By the way, the right panel is rendered once at starting.
$(function () {
var data = []; // data source
var $num = $('#num'); // input for number of rows
var $left = $('#left'); // left panel
var $right = $('#right'); // right panel
// render the right panel at starting
renderRightPanel();
// when the number of rows changes:
// - rebuild the left panel entirely
// - keep the data list up to date
// - print the array to the right panel
$num.on('keyup mouseup', function () {
renderLeftPanel($(this).val());
updateList();
renderRightPanel();
});
// when a value changes:
// - keep the data item up to date
// - print the array to the right panel
$left.on('change', 'input', function () {
var i = $left.find('input').index(this);
updateItem(i, $(this).val());
renderRightPanel();
});
// updates the data list
function updateList () {
data = $left.find('input').map(function () {
return $(this).val();
}).get();
}
// updates a single data item
function updateItem (index, value) {
data[index] = value;
}
// refreshes the DOM of the right panel
function renderRightPanel () {
$right.html('<pre>data = ' + (
JSON.stringify(data, 0, 4)
) + '</pre>');
}
// refreshes the DOM of the left panel
function renderLeftPanel (nLines) {
var i;
var html = '';
if (nLines > 0) {
html = '<h4>Heading</h4>';
for (i = 0; i < nLines; i++) {
html += '<div><input value="' + (data[i] || '') + '" /></div>';
}
}
$left.html(html);
}
});
body * {
padding: 0;
margin: 0;
}
h4, input {
margin-bottom: .5em;
}
#panels {
border: 1px solid black;
}
#panels > div {
display: table-cell;
padding: 1em;
}
#right {
border-left: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
<div id="left"></div
><div id="right"></div>
</div>
Disable and hide extra elements instead of removing them. That will prevent them from getting posted, and also retain the previous value of all values that have been entered. See fiddle
One last point, if you don't want to retain values of hidden elements, change .hide() to .hide().val("")
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput">
<h4>Please fill in the name and email of each extra attendees</h4>
</div>
</body>
<style>
.col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
.row { padding: 5px; }
</style>
<script>
for (var i = 0; i < 20; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
$('#num').bind('keyup mouseup', function () {
var num = parseInt($(this).val());
$('.dynamicInput .row')
.slice(num)
.hide()
.attr('disabled','disabled');
if ( num > 0) {
$('.dynamicInput .row')
.slice(0,num).show()
.removeAttr('disabled');
$('.dynamicInput h4').show();
} else {
$('.dynamicInput h4').hide();
}
}).trigger('keyup');
</script>
Off-hand, you could cache the values within javascript to resist losing them between #num changes. e.g.
(function($){
var $num = $('#num'),
$dynamic = $('.dynamicInput');
cache = {};
$dynamic.on('change', 'input', function(e){
cache[$(this).prop('name')] = $(this).val();
});
$num.on('change keyup mouseup', function(e){
$dynamic.empty();
var val = parseInt($(this).val(), 10);
if (!isNaN(val) && val > 0){
$('<h4>')
.text('Please fill in the name and email of each extra attendees')
.appendTo($dynamic);
for (var i = 0; i < val; i++){
var nameName = 'attendeesName' + i,
emailName = 'attendeesEmail' + i;
var $row = $('<div>',{'class':'row'}),
$col1 = $('<div>',{'class':'col1'}).appendTo($row),
$col2 = $('<div>',{'class':'col2'}).appendTo($row);
$('<input>',{
'type': 'text',
'name': nameName,
'placeholder': 'Name',
'required': 'true'
}).val(cache[nameName] || '').appendTo($col1);
$('<input>',{
'type': 'email',
'name': emailName,
'placeholder': 'Email',
'required': 'true'
}).val(cache[emailName] || '').appendTo($col2);
$row.appendTo($dynamic);
}
}
});
})(jQuery);
input[type="number"] {
width:200px;
height:30px;
font-family:Arial, sans-serif;
font-size:20px;
}
.row {
display:block;
margin-bottom:15px;
}
body{
width:100%;
padding:40px;
}
input[type="text"]{
width:100%;
}
.col1, .col2{
width:45%;
display:inline-block;
margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
Here is an attempt to improve the accepted answer:
$(function () {
var $num = $('#num');
var $panel = $('#panel');
var h4 = '<h4>Heading</h4>';
var row = '<div><input /></div>';
$num.on('mouseup keyup', function () {
var n, $inputs;
var value = $(this).val();
if (value <= 0) {
$panel.empty();
}
else {
$inputs = $panel.find('input');
// get the number of inputs already added
n = $inputs.size();
// add your heading if there is no input
if (n === 0) {
$panel.append(h4);
}
// the user wants less inputs
if (value < n) {
$inputs.slice(value).remove();
}
// the user wants more inputs
else if (value > n) {
$panel.append(
// a little trick, see below
new Array(value - n + 1).join(row)
);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>
A word on the "array join trick":
var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"
var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"
var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"
This is what exactly you are looking for,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#num").keyup(function(){
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
});
</script>
</head>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
</html>