trying to create a dynamic button system to add/remove inputs on clicks. I have the addButton working but not the deleteButton. What am I missing?
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
The problem is, that $(this) inside the delete button handler refers to the minus button. That minus button is not inside each of the items (It's at the top. and doesn't have a parent div), so you need to reference the element you want to delete another way. In my case below, I'm selecting the last <div> in $(wrapper):
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
$(wrapper).find('div:last').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Also you can do it with pure JS using child Nodes. :D
Sometimes pure JS is beater than JQ
Explanation:
remove is a new function. It's a shortcut, making it simpler to remove an element without having to look for the parent node. It's unfortunately not available on old versions of Internet Explorer so, unless you don't want to support this browser, you'll have to use removeChild.
$(document).ready(function() {
var maxFields = 20;
var addButton = $('#plusOne');
var deleteButton = $('#minusOne');
var wrapper = $('#userNumbers');
var fieldInput = '<div><input type="text" name="persons" id="persons"/></div>';
var x = 1;
$(addButton).click(function () {
if (x < maxFields) {
x++;
$(wrapper).append(fieldInput);
}
});
$(deleteButton).click(function(e) {
e.preventDefault();
var myNode = document.getElementById("userNumbers");
i=myNode.childNodes.length - 1;
if(i>=0){
myNode.removeChild(myNode.childNodes[i]);
x--;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="plusOne">+</button>
<button type="button" id="minusOne">-</button>
<div id="userNumbers">
<p>
<input type="text" id="person" name="person">
</p>
</div>
Try below solution, I care about the back end also because you have to send the data to back end developer so you have to give the array name for input fields such as name="person[]". anyway you can try this solution also.
$(document).ready(function(){
var static_html = '<input type="text" name="person[]" class="input_fields" />';
$("#plus").click(function(){
if($(".input_fields").length < 20 )
$("#dynamic_field_container").append(static_html);
});
$("#minus").click(function(){
if($(".input_fields").length > 1 )
$(".input_fields:last").remove();
else
alert("This is default field so u can't delete");
});
});
.input_fields{
display:block;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="fa fa-plus fa-4x" id="plus"> </span>
<span class="fa fa-minus fa-4x" id="minus"> </span>
<div id="dynamic_field_container">
<input type="text" name="person[]" class="input_fields" />
</div>
Related
Html code
<div class="cont">
<div class="row">
<p>anything</p>
<input type="button" id="1" class="Done" name="Go" value="done">
</div>
<div class="row">
<p>anything</p>
<input type="button" id="2" class="Done" name="Go" value="done">
</div>
<div class="row">
<p>anything</p>
<input type="button" id="3" class="Done" name="Go" value="done">
</div>
</div>
I have 3 of them[buttons]
javascript
var remove=document.getElementsByClassName("Done")
for(var i=0;i<remove.length;i++){
var button=remove[i]
button.addEventListener('click',function(event){
var bclick = event.target
bclick.parentElement.remove()
});
}
I tried that, it's work for the first time but when I reload I miss changes.
I think you can use localstorage to track your removed parentElement. Simply check your localstorage whether your parentElement is removed or not, if it is removed already just hide your row class's elements. It will show nothing once button is clicked. Hope it will help.
var remove = document.getElementsByClassName("Done");
for (var i = 0; i < remove.length; i++) {
var button = remove[i];
if (button) {
if (window.localStorage.getItem(remove[i].id) == 'true') {
document.getElementById(remove[i].id).parentNode.style.display = 'none';
}
}
}
for (var i = 0; i < remove.length; i++) {
var button = remove[i];
if (button) {
button.addEventListener('click', (event) => {
var bclick = event.target;
window.localStorage.setItem(bclick.id, 'true');
bclick.parentElement.remove();
});
}
}
I am working on a web store which offers 2 pre-assigned options (buy two for XX and buy 3 for XY). I also added a normal - 0 + system whith which the customer can select a different number of products.
I wrote a little code which works fine for +- or 2,3 alone, but if i wanna decrease a number added by 2,3 buttons, it doesn't go from 3 to 2 but to 0 or -1.
So, i want to be able to select pre-defined option 2 or 3 but i also want it to be editable by +- buttons.
Any suggestions?
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="0"></input>
<button class="plus" onclick="buttonClicDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
i++;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
var i = 0;
function buttonClickDOWN() {
i--;
document.getElementById('gumb2').value = i;
if (i <= 0) {
i = 0;
display(i);
}
}
</script>
As I already mention in the comment, you have a typo in buttonClicDOWN .......missing k. You directly increment/decrement the value of the element. Please see the modified functions:
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I'd have this added as a comment, but was not able to for missing rep. So an answer:
In simple terms: you are not updating your global variable i when pressing the 2 or 3 button, so when you in/decrease i and assign it to the value property, you do override the old value.
I would recommend to drop the i (global) variable and just to work with the value property, e.g.
function buttonClickDOWN() {
var elm = document.getElementById('gumb2');
if (elm.value > 0)
elm.value--;
else
elm.value = 0;
}
P.S.: as you are using a text type input, you might also want to consider non-numbers the user might have entered.
Why not simply use input type="number"?
<button class="gumb_shop2" onclick="gumb2.value=2">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="gumb2.value=3">3 for 8,99 €</button>
<input type="number" id="gumb2" value="1" step="1" min="1" />
<input type="button" id="order" value="ORDER NOW" />
Here's a simple example that that meets your specs:
<button onclick="setAbs(event)" data-val="2">2 for 10,99 €</button>
<button onclick="setAbs(event)" data-val="3">3 for 8,99 €</button><br/><br/>
<button onclick="down()">-</button>
<input size="2" id="counter" value="0" />
<button onclick="up()">+</button><br/><br/>
<input type="submit" value="Submit" />
<script>
let counter = document.getElementById("counter");
function setAbs(event){
counter.value = event.target.dataset.val;
}
function up(){
counter.value = parseInt(counter.value) + 1;
}
function down(){
if(counter.value > 0){
counter.value = parseInt(counter.value) - 1;
}
}
</script>
this is the answer i was looking for.
Thank you #Mamun for quick response.
<button class="gumb_shop2" onclick="spremembax()">2 for 10,99 €</button>
<button class="gumb_shop3" onclick="spremembay()">3 for 8,99 €</button>
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
I would want to have two or more fields in a form to be dynamically added and deleted as per requirement. Say for, a person can have more than 1 phone numbers and more than 1 email address. The idea is to let the user add more than one phone number and email address if they have
This down below is what I did (only a rough example)
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container2");
var add_button = $(".add_form_field_1");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="text[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
//I repeated the javascript for the first field which was this
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
<div class="container2">
<button class="add_form_field_1">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[]">
</div>
</div>
And the JsFiddle.
I am not a javascript coder hence do not know if this is how you do it or is there a better way.
P.S. I asked the same question an hour ago and had to rephrase it as it was causing confusion.
You can simplyfy so much your code, check this:
$(document).ready(function() {
$("button.add_form_field").click(function(e) {
e.preventDefault();
var name = $(this).closest(".container").find("input:first").attr("class")
var numInputs = $(this).closest(".container").find("input").size()
if (numInputs < 10) {
numInputs++;
if (name=="mytext"){
$(this).closest(".container").append('<div><input type="text" name="mytext[' + numInputs + ']"/>Delete</div>');
}
if (name=="text"){
$(this).closest(".container").append('<div><input type="text" name="text[' + numInputs + ']"/>Delete</div>');
}
} else alert('You Reached the limits')
});
$(document).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[1]" class="mytext">
</div>
</div>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[1]" class="text">
</div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Here is a working example, Hope this will helps you.
This may help you Mecom
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function removeUserDetail(index)
{
var rows=jQuery("#user_info tr").length;
jQuery("#user_info tr:nth-child("+(index+1)+")").remove();
if(index==(rows-1))
{
jQuery("#user_info tr:nth-child("+(index)+")").children().eq(4).append('<a class="mc_plus_button" id="plus_1" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a>');
}
jQuery("#user_info tr").each(function(i,e){
if(i>1)
{
jQuery(this).children().eq(4).children().eq(0).attr("onclick","removeUserDetail("+i+");");
}
});
}
function addUserDetail() {
var row_count1 = jQuery("#user_info tr").length;
var row_count = 0;
jQuery(".tr_clone").each(function(index, value) {
var rowid = jQuery(this).data('rowid');
if (rowid > row_count) {
row_count = rowid;
}
});
row_count = row_count + 1;
jQuery("#user_info tr").eq(row_count1 - 1).find(".mc_plus_button").remove();
var html = '<tr class="tr_clone" data-rowid="' + row_count + '"><td>' + row_count + '</td>';
html += '<td style="text-align: center"><input type="text" name="user_info[name][]" id="name_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[email][]" id="email_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[contact][]" id="contact_'+row_count+'" aria-invalid="false" /></td>';
html += '<td><a class="mc_minus_button" id="minus_' + row_count + '" href="javascript:void();" onclick="removeUserDetail(' + row_count + ');" title="remove"><strong>–</strong></a><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td></tr>';
jQuery("#user_info").append(html);
}
</script>
<table id="user_info">
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<tr class="tr_clone" data-rowid="1">
<td align="center">1</td>
<td style="text-align: center">
<input type="text" name="user_info[name][]" id="name_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[email][]" id="email_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[contact][]" id="contact_1" aria-invalid="false" />
</td>
<td><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td>
</tr>
</table>
I want to make a JavaScript function, which, after pressing a button, takes the list of checkbox elements with their content, checks all the checkboxes, creates a div element with these checkboxes and writes the result to the HTML form.
Here is my code:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
$("formInput").find('.chk').prop("checked", true);
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
}
Here is the HTML Div element with the list of checkbox elements. They also appear dynamically. Initially, Div is empty.
<div id = "selectedList" class = "col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br><br>
</div>
And this is the HTML form, where I want my result to appear:
<form id="formInput">
</form>
The problem here is that it checks all the checkboxes in my list, but in the resulting HTML form they appear unchecked again. What is wrong with it? Thank you
Besides replacing prop() to attr() as Rik Lewis correctly recommended you can alternately put the line
$("formInput").find('.chk').prop("checked", true);
at the bottom of the function and add the # character in front the selector id like this:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id", "selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML + '<br>' + myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectedList" class="col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br>
<br>
<ul>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<ul>
</div>
<form id="formInput">
</form>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
container.append($(html));
}
</script>
Ok here is what I was trying to do... Create a delete button along with edit by using DOM while creating a paragraph. But delete button always seems to be deleting first paragraph instead of deleting the corresponding paragraph.. here's my code:
Javascript:
function writePara()
{
var comment = document.getElementById("usrinput").value;
var newParagraph = document.createElement('p');
newParagraph.textContent = comment;
document.getElementById("updateDiv").appendChild(newParagraph);
var button = document.createElement("button");
var Btext=document.createTextNode("EDIT");
button.appendChild(Btext);
document.getElementById("updateDiv").appendChild(button);
button.onclick =
(
function()
{
var edit = prompt("Type to edit", "");
newParagraph.innerHTML = edit;
}
);
var button2 = document.createElement("button");
var Btext2=document.createTextNode("DELETE");
button2.appendChild(Btext2);
document.getElementById("updateDiv").appendChild(button2);
button2.onclick =
(
function ()
{
var items = document.querySelectorAll("#updateDiv p");
if (items.length)
{
var child = items[0];
child.parentNode.removeChild(child);
}
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);
addBr();
}
And the HTML:
<body onload="radio()">
<div id="paraButton" align="left">
<form><h3>Enter your Paragraph content here:</h3>
<textarea cols="20" rows="10" id="usrinput">Enter your texts here...</textarea>
</form>
<form id="one"><input type="button" value="Apply" onclick="writePara()"/></form>
<div id="updateDiv" name ="update"><h1>Space for Paragraph</h1> </div>
</div>
<div id="radioButton">
<h3>Type your radio button here:</h3>
<input type="text" name="option" id="option" value="Example 1" />
</br></br>
<button id="AddButton">Add</button>
<button id="RemoveButton">Remove</button>
</br></br></br></br></br></br></br></br>
<div id="updateDivRadio"><h1>Space for Radio Button</h1></div>
</div>
</body>
P.S: the radio() function is working fine this is just a segment that I'm having problem with.
Ok I got it working with the help of others so decided to share here...
Changing button2.onclick to this works.
button2.onclick =
(
function ()
{
newParagraph.parentNode.removeChild(newParagraph);
button.parentNode.removeChild(button);
button2.parentNode.removeChild(button2);
}
);