how to add and remove div using jquery - javascript

I'm making a scenario where user will be able to add a new row with "Remove" option by clicking "Add" button. If they click "Remove" button, the entire row will be deleted. I've put script for it. But, it's not working perfectly. Kindly, take a look on my fiddle: http://jsfiddle.net/learner73/gS8u2/
My problem is:
(1) If user click "Add" button, a new row will be added. That's good. But, it's gone below the "Add" button. I want, the new row will be added above the "Add" button, I mean "Add" button should be always at the bottom.
(2) At my code, if user click "Remove" button on the previously created row, the entire row will be deleted. That's good. But, when they click "Remove" button on dynamically created row, nothing will happened!
HTML:
<div class="optionBox">
<div class="block">
<input type="text" /> <span class="remove">Remove Option</span>
</div>
<div class="block">
<input type="text" /> <span class="remove">Remove Option</span>
</div>
<div class="block">
<span class="add">Add Option</span>
</div>
</div>
jQuery:
$('.add').click(function() {
$('.optionBox').append('<input type="text" /><span class="remove">Remove Option</span>');
});
$('.remove').click(function() {
$(this).parent('div').remove();
});

You need to use event delegation on your remove link code:
$('.add').click(function() {
$('.block:last').before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$('.optionBox').on('click','.remove',function() {
$(this).parent().remove();
});
jsFiddle example
Also, you weren't adding a complete div block to match the other code you had. You left out the <div class="block"> and only added the input and span.

Demo http://jsfiddle.net/34Lbu/
API: .before https://api.jquery.com/before/
Hope rest fits your need :)
code
$('.add').click(function () {
$(this).before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
});
$(document).on('click', '.remove', function () {
$(this).parent('div').remove();
});
EDIT http://jsfiddle.net/amdzakir/gS8u2/38/
To check if all the input fields are filled with values.
$('.add').click(function() {
flag = true;
$('input').css('border-color','green');
$('input').each(function(){
if ($.trim($(this).val())===''){
$(this).css('border-color','red');
flag = false;
}
});
if(flag){
$(this).before('<div class="block"><input type="text" /><span class="remove">Remove Option</span></div>');
}
});
$(document).on('click','.remove',function() {
$(this).parent().remove();
});

try this:
$('.remove').click(function() {
$(this).closest('div').remove();
});
$('.add').click(function() {
$('.block:last').after('<input type="text" /><span class="remove">Remove Option</span>');
});

Here is one way -
http://jsfiddle.net/gS8u2/3/
$('.add').click(function () {
$('.block:last').before(' <div class="block"><input type="text" /><span class="remove">Remove Option</span></div>'); // make sure to add the div too
});
$('body').on('click', '.remove', function () { // use event delegation because you're adding to the DOM
$(this).parent('.block').remove();
});

Related

PHP & JQuery Adding Dynamic Inputs

I'm using Jquery in order to add dynamic inputs on my page. I only want to display one input initially, then more can be added by clicking a button.
This works as expected.
I'm then using PHP in order to catch the $_POST values of the inputs and send them to an external script. This also works, however I'm always receiving one extra item in my array, and it's empty.
I think this is because I have a hidden <div> field in my HTML, which is shown when a new input is generated?
My code is below;
HTML
// unnecessary code removed
<div class="after-add-more">
<button class="add-more" type="button" title="Add"></button>
<input name="addmore[]" value="" type="text">
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove"></button>
<input type="text" name="addmore[]" value="">
</div>
</div>
JQUERY
$(document).ready(function() {
//here first get the contents of the div with name class copy-fields and add it to after "after-add-more" div class.
$(".add-more").click(function() {
var html = $(".copy-fields").html();
$(".after-add-more").after(html);
});
//here it will remove the current value of the remove button which has been pressed
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
PHP
<?php
// unnecessary code removed
$field_values_array = $_POST['addmore'];
?>
Without generating an additional input, I enter 1111111 into the input box and submit. A print_r($_POST) produces;
[addmore] => Array
(
[0] => 1111111
[1] =>
)
Any help is appreciated.
You are probably better just getting the parent of the element that was clicked and adding your markup after that. Here is an example:
$(document).ready(function() {
// this function handles the click event
function addField(parent) {
// find your template, in this case its the first .after-add-more
var html = $(".after-add-more").first().clone();
// reset the value of any inputs
$('input', html).val('');
// wire the click handler for the button
$("button", html).click(function() {
addField($(this).parent());
});
// append it to the parent of the parent, addContainer
html.appendTo(parent.parent());
}
// wire the click handler for the add-more button
$(".add-more").click(function() {
addField($(this).parent());
});
// I don't know what the intention of this code is so I'm leaving it alone
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
// unnecessary code removed
<div id="addContainer">
<div class="after-add-more">
<button class="add-more" type="button" title="Add">Add</button>
<input name="addmore[]" value="" type="text">
</div>
</div>
<div class="copy-fields hide">
<div>
<button class="remove" type="button" title="Remove">Remove</button>
<input type="text" name="addmore[]" value="">
</div>
</div>

Removing a parent element on click using jQuery

I am having trouble creating a dynamic form where a user can add and remove a text field. The functionality to add an extra field works fine, but removing the field just cannot seem to work.
My html is:
<div class="formItem" id="members">
<label for="workgroup">Add Members:</label>
<br />
Add another member
<p>
<input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />
</p>
</div>
My JS:
$('#addMember').on('click', function() {
$('<p><input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />Remove</p>').appendTo('#members');
return false;
});
$('#removeMember').on('click', function() {
$(this).parent().remove();
});
You are adding the click listener before actually creating the element, use:
$('#members').on('click', '#removeMember', function() {
$(this).parent().remove();
});
see these examples http://api.jquery.com/on/#entry-examples
try using this
$(document).on('click','#removeMember', function() {
$(this).parent().remove();
});

jquery javascript add/remove button

I have a form, where I dynamically want to add additional inputfields. So when I click the "Add"-button, there should appear a new inputfield but now with both an add and remove button. When I now click the "Add" button next to the new inputfield, there shoud appear another new inputfield et. etc. The same goes fro the remove button. So far, so good... my issue is though, that I cant create a new inputfield after clicking "Add"...
So, my code looks like this:
<div id="fields">
<button class="add">Add</button>
<div class="newField">
<div class="check">
<input type="radio" id="field_1" name="correct" required></input>
</div>
<input type="text" id="input_1" required></input>
</div>
</div>
the CSS:
#fields {
width:350px
}
.check{
float:left
}
.add, .remove {
float:right
}
and most important, the javascript:
var InputsWrapper = $("#fields");
var x = InputsWrapper.length;
var FieldCount=1;
$('.add').click(function(e){
FieldCount++;
$(InputsWrapper).append('<div class="newField"><button class="remove">Remove</button><button class="add">Add</button><div class="check"><input type="radio" id="field_'+ FieldCount +'" name="correct"></div><input type="text" id="input_'+ FieldCount +'" /></div></div>');
x++;
return false;
});
$(document).on("click",".remove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
});
Here is a DEMO fiddle: http://jsfiddle.net/cwprf03o/
Can someone help me out?
Replace line
$('.add').click(function(e){
with
$(document).on("click", ".add", function(e){
The reason for this is that the click() function binds your function(e){} to .add elements that exist at the time the click() function is called.
The on() method works differently. On the click event it will also search for any .add items that exist at the time the click event is raised.
http://jsfiddle.net/1qq40qex/

jquery remove only effect the first span

Refer to my jsfiddle , my jquery only work for the first "X" i click but not the second or third ?
2) how do i disable it when it only left one input ?
Demo
<div class="main-form">
<fieldset id="ingt">
<legend></legend>
<div class="formheader">
<label style="width:170px;"></label>
<label></label>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][0][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][0][ingredient]" />
<span id="remove">X</span>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][1][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][1][ingredient]" />
<span id="remove">X</span>
</div>
<div class="formrow">
<span class="drag"></span>
<input type="text" max-length="30" name="recipe[ingredient][2][amount]" />
<input type="text" id="ingredient" size="60px" name="recipe[ingredient][2][ingredient]" />
<span id="remove">X</span>
</div>
<div id="add"></div>
<button id="addi" type="button" onclick="add_field()">Add </button>
</fieldset>
</div>
$(function () {
$("#remove").click(function () {
$(this).parent().remove();
});
});
ID of an element must be unique, use class instead
<span class="remove">X</span>
then
$(function () {
$(".remove").click(function () {
$(this).parent().remove();
});
});
The ID selector will return only the first element with the said element so your selector $("#remove") will return the first element with the the id remove so the click handler will get added to only that element
Also since you have an add button I'm assuming you will be adding dynamic elements, so use event delegation to handle the new elements
$(function () {
//if you want to make the last item in the list(in terms of position) to non removable
$(".main-form").on('click', '.remove:not(:last)', function () {
$(this).parent().remove();
});
});
Demo: Fiddle
or
$(function () {
$(".main-form").on('click', '.remove', function () {
//if you want to make the last item in the list to non removable
if ($('.remove').length > 1) {
$(this).parent().remove();
}
});
});
Demo: Fiddle
Duplicate IDs. ( IDS need to be unique )
<span id="remove">X</span>
change to
<span class="remove">X</span>
and change the script
$(".remove").click(
Id should be unique. So you can use class instead of it.
Change id='remove' to class='remove'
and try,
$(function () {
$(".remove").click(function () {
$(this).parent().remove();
});});
To restrict last one not clickable, Just try,
$(function () {
$(".remove").click(function () {
if($(".remove").length > 1){
$(this).parent().remove();
}
});});
ID must be unique, I will suggest you to use class instead
$(".remove").click(function () {
$(this).parent().remove();
});
HTML
<span id="remove">X</span>
change to
<span class="remove">X</span>
Fiddle DEMO

How to find nearest div element using jquery selector?

my html:
<td class="result">
<div id="main_title">
<label for="textfield"></label>
<input type="text" name="textfield" id="textfield" value="<?php echo $row['leftpanelmaintitle']; ?>" />
</div>
<div id="edit">EDIT</div>
<div id="update">UPDATE</div>
</td>
my js:
$('#edit').click(function()
{
$('#main_title').show(1000,function(){
$('#update').show();
$('#textfield').focus();
});
})
i want to use common selector in the place of $('#main_title'). that is the address of previous div.
i tried;
$(this).click(function()
{
$(this).prev('div').show(1000,function(){
$('#update1').show();
$('#textfield').focus();
});
})
bt not working.
You should use $('id').children() to get the previous div by writing the id of that present div.
You can do this:
$('#edit').click(function () {
$(this).prev('#main_title').show(1000, function () {
$('#update').show();
$('#textfield').focus();
});
});
Here, $(this).prev('#main_title') will give you the previous div with ID main_title to the currently clicked div with ID edit
UPDATE
You can add a class named edit to the edit button and do it like this:
$('.edit').click(function () {
$(this).prev().show(1000, function () {
$('#update').show();
$('#textfield').focus();
});
});
Demo: Fiddle

Categories

Resources