Delete the last item element JQuery - javascript

I'm working on something, basically I have this Add Parameter button which adds 2 new text field namely a parameter name and parameter value. I have a button which is delete parameter. How can I delete the last parameter name and value? The button should delete the last.
Here's my code https://jsfiddle.net/q7fokdbw/
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5" id="paramArea">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="hidden" class="form-control" id="paramCount" name="paramCount" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" id="addParams">Add Parameter</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" id="deleteParams">Detele Parameter</button>
</div>
</div>
<script>
$(function() {
var count = 0;
$( "#addParams" ).click(function() {
$("#paramArea").append('<br /><input type=text class="form-control" name=ParamName'+count+' id=ParamName'+count+' placeholder="Parameter Name" /> ');
$("#paramArea").append('<br /><input type=text class="form-control" name=ParamValue'+count+' id=ParamValue'+count+' placeholder="Parameter Value" />');
count++;
$("#paramCount").val(count);
});
});
</script>

You should rather wrap those two inputs in div and append it to #paramArea. like this:
$("#paramArea").append('
<div class="rowelement"><input type=text class="form-control" name=ParamName'+count+'
id=ParamName'+count+' placeholder="Parameter Name" /><br />
<input type=text class="form-control"
name=ParamValue'+count+' id=ParamValue'+count+'placeholder="Parameter Value" /></div>
');
and on click of delete button, you can get .rowelement and delete last element using :last and .remove()
$("#deleteParams").click(function(){
$(".rowelement:last").remove();
});

Use .remove() with the :last selector
$('#deleteParams').click(function(){
$('[id^=ParamName]:last,[id^=ParamValue]:last').remove();
});
Updated Fiddle

You can do it something like :
$("#deleteParams").on('click', function(){
$("#paramArea").find(':text:last').remove();
});
Demo

Using a container will make this easier.
$(function() {
var count = 0;
$("#addParams").click(function() {
$("#paramArea").append(
'<br /><div class="container"><input type=text class="form-control" name=ParamName' + count + ' id=ParamName' + count + ' placeholder="Parameter Name" /> <br /><input type=text class="form-control" name=ParamValue' + count + ' id=ParamValue' + count + ' placeholder="Parameter Value" /></div>');
count++;
$("#paramCount").val(count);
});
$("#deleteParams").click(function() {
$('.container').last().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5" id="paramArea">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="hidden" class="form-control" id="paramCount" name="paramCount" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" id="addParams">Add Parameter</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" id="deleteParams">Detele Parameter</button>
</div>
</div>

Try this one
$("#deleteParams" ).click(function() {
$("#paramArea").find(".form-control").filter( ":last" ).remove();
});

Related

Saving dynamically added li and ul element to database using an array

I'm trying to build a User interface of an application where user could add ul and li element when clicking on add question, I successfully managed to develop the front end part here's a preview:
but the problem is when saving this to the database which is so overwhelming I'm stuck at this, is there any way to save the data to an array so I can display them with php, any idea is welcomed.
here's the jquery code:
wrapper.on("click", "button", function(e){
e.preventDefault();
var parent = $(this).parent().parent().parent().parent().parent().parent();
var parentID = $(this).attr('element-id');
var elementID = 1000000000000000000*Math.random();
parentIDs.push(elementID);
if($(this).attr('class') == "add_field_button btn btn-success"){
if(parent.find('ul').length){
parent.find('ul').first().append(`
<li>
<div class="panelcb white-box">
<div class="form-horizontal form-material">
<div class="form-group">
<label class="col-md-12">Question</label>
<div class="col-md-12">
<input type="text" placeholder="Your Question" value="testqst" class="question question`+parentID+` form-control form-control-line" parent-question="`+parentID+`" element-question="`+elementID+`"> </div>
</div>
<div class="form-group">
<label class="col-md-12">Response</label>
<div class="col-md-12">
<input type="text" placeholder="Your Response" value="testqst" class="response response`+parentID+` form-control form-control-line" parent-response="`+parentID+`" element-response="`+elementID+`"> </div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<button class="add_field_button btn btn-success" element-id="`+elementID+`">Add Question</button>
</div>
<div class="col-sm-4">
<button class="delete_field_button btn btn-error" >Delete</button>
</div>
</div>
</div>
</div>
</div>
</li>`);
}else{
$(this).closest('li').append(`
<ul><li>
<div class="panelcb white-box">
<div class="form-horizontal form-material">
<div class="form-group">
<label class="col-md-12">Question</label>
<div class="col-md-12">
<input type="text" placeholder="Your Question" value="testqst" class="question question`+parentID+` form-control form-control-line" parent-question="`+parentID+`" element-question="`+elementID+`"> </div>
</div>
<div class="form-group">
<label class="col-md-12">Response</label>
<div class="col-md-12">
<input type="text" placeholder="Your Response" value="testqst" class="response response`+parentID+` form-control form-control-line" parent-response="`+parentID+`" element-response="`+elementID+`"> </div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
<button class="add_field_button btn btn-success" element-id="`+elementID+`">Add Question</button>
</div>
<div class="col-sm-4">
<button class="delete_field_button btn btn-error" >Delete</button>
</div>
</div>
</div>
</div>
</div>
</li></ul>`);
}
}else if($(this).attr('class') == "delete_field_button btn btn-error"){
parent.remove();
}
Thanks is advance.
Well...
If the whole user-interative-area, I'd call a playground, can be put inside a container:
<div id='playground'>
.. all the ul's and li's..
</div>
And if you've got a form or something else:
<form action='/' id='form-playground' method='post'>
<textarea id='playground-container' name='playground' class='hidden'>
</textarea>
<input type='submit' value='Save My Playground'>
</form>
Then on submit you can copy the contents of the the playground to a hidden textarea:
$(document).ready(function () {
$('#form-playground').on('submit', function () {
$('#playground-container').html($('#playground').html());
return true;
});
});
Or perhaps an AJAX post:
$.post( PostUrl, { playground: $('#playground').html() } );

Get the id of button to Remove a input field on click of minus button

I have an option field with by default 2 option. I have a button "Add more Option", this will add a input field (containing minus button to remove) dynamically.
I want to remove the particular input field when user clicks minus button.
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label for="options">Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
</form>
</div>
Here is the script -
$(document).ready(function(){
var optionNo = 2;
$("#moreOptions").click(function(){
optionNo = optionNo + 1;
$("#optionsList").append
('<div class="input-group" id="inputField' + optionNo +'"><input type="text" class="form-control" placeholder="New option field" id="option' + optionNo +'"><i class="input-group-btn"><button class="btn btn-danger" type="button" id="removeBtn' + optionNo +'"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
});
// here i want to write code to remove that input field
});
I tried this -
$(".input-group").click(function(){
const id = this.id;
$("#id").remove();
});
Please suggest. Any other way to do this will also be fine.
Use classes instead of worrying about incrementing ID's. That approach gets too complicated to manage sometimes and it isn't needed at all
Simplified append html with new class remove-btn instead of id on button:
$("#optionsList").append
('<div class="input-group"><input><button class="btn btn-danger remove-btn" type="button"></button></div>');
Delegated event listener for any .remove-btn added to dom in future
$(document).on('click', '.remove-btn', function(){
// "this" is current button event occurs on
$(this).closest('.input-group').remove()
})
Firstly don't use id's in dynamically created elements if you are not going to change it's value and end up with multiple elements with the same ID instead use classes. ie.
class="removeBtn'
Next for dynamically created elements use event bubbling to attach events
$("body").on("click", ".removeBtn", function(){
$(this).closest(".input-group").remove();
});
Because you add on the fly the new button you need to delegate the click event to the document:
$(document).on('click', ".input-group button", function(e) {
$(this).closest('.input-group').remove();
});
This part: ".input-group button" means: listen for click event related to button element inside an input-group
The closest used to get the parent div to be removed.
The snippet:
$(document).ready(function(){
var optionNo = 2;
$("#moreOptions").on('click', function(e) {
optionNo = optionNo + 1;
$("#optionsList").append
('<div class="input-group" id="inputField' + optionNo +
'"><input type="text" class="form-control" placeholder="New option field" id="option' + optionNo +
'"><i class="input-group-btn"><button class="btn btn-danger" type="button" id="removeBtn' + optionNo +
'"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
});
// here i want to write code to remove that input field
$(document).on('click', ".input-group button", function(e) {
$(this).closest('.input-group').remove();
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label>Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
<div class="form-group">
<button type="submit" class="btn btn-lg btn-success" name="button">Submit</button>
</div>
</form>
</div>
Try with the below code. Hope it helps.
var counter = 1;
$(document).on('click', 'button#moreOptions', function(){
$("#optionsList").append
('<div class="input-group" style="padding:5px;"><input type="text" class="form-control" placeholder="New option field '+ counter +'"><i class="input-group-btn"><button class="btn btn-danger btn-minus" type="button"><i class="glyphicon glyphicon-minus"></i></button></i></div>');
counter++;
});
$(document).on('click', 'button.btn-minus', function(){
$(this).parents('div.input-group').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-sm-4 col-sm-offset-4">
<form class="form-horizontal" action="index" method="post">
<div id="optionsList"class="form-group">
<label>Options</label>
<input type="text" class="form-control" id="option1" placeholder="M S Dhoni">
<input type="text" class="form-control" id="option2" placeholder="Virat Kohli">
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-default" id="moreOptions">Add More Options</button>
</div>
</form>
</div>
Add a onclick handler when you generate your button as following :
$("#removeBtn" + optionNo + "").click(function()
{
$("#inputField" + optionNo + "").remove();
});

Appending div inside 'form' not working

I'm try to append 'div' element and its content inside an another 'div' but that's not working inside 'form' tag, outside its working fine ..
<form id="myForm">
<div id ="wrapfields" class="input_fields_wrap">
<div class="col-md-12 form-group">
<button style ="margin-left:1%;"class="btn btn-success"onclick="Addelemt()">+</button>
</div>
<div>
<div class="col-md-6 form-group">
<label class="text-center">Add Items</label>
<input type="text" class="form-control" name="addItem[]" id="email">
</div>
<div class="col-md-2 form-group">
<label>Price</label>
<input type="text" class="form-control" name="addprice[]" id="email">
</div>
<div class="col-md-2 form-group">
<label>Quantity</label>
<input type="text" class="form-control" name="addprice[]" id="email">
</div>
</div>
<div id ="" style="margin-bottom:10px;">
<div class="col-md-2 form-group" style="margin-left:45%;">
<button type ="submit" onsubmit ="return saveInputs()" name ="submit" class="btn btn-default"/>submit</button>
</div>
</div>
</div>
</form>
and the javascript code written so far..
var counter = 0;var increment=0;
function Addelemt()
{
var parentDiv = document.getElementById('wrapfields');
increment++;
var divClass = document.createElement("div");
divClass.setAttribute('id','divId'+increment);
console.log(divClass);
parentDiv.appendChild(divClass);
}
Can anyone tell me that why its not working inside 'form'???
So, the problem is with your html
<button style ="margin-left:1%;" class="btn btn-success" onclick="Addelemt()">+</button>
add type="button" to Add button
<button style ="margin-left:1%; "class="btn btn-success" type="button" onclick="Addelemt()">+</button>
As button inside <form> tag without type attribute is treated like Submit button, hence it refresh the page.

Add required attribute when you add form inputs dynamically

I have a form where dynamically, the user can add/delete form inputs. The problem is that in form-group which is hidden, I can't add the attribute required because in submit event, the submit won't happen.
How can I add the attribute required every time i press + button and delete it when I press - button?
I tried this: $('#barcode').prop('required',true); but isn't right because if I press 2 times the + button, I will have 2 inputs with the same id...
var counter = 0;
$('#form1')
// Add button click handler
.on('click', '.addButton', function() {
counter++;
var $template = $('#addLine'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-index', counter)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="barcode"]').attr('name', 'barcode-' + counter).end()
.find('[name="productsInBox"]').attr('name', 'productsInBox-' + counter).end()
.find('[name="packer"]').attr('name', 'packer-' + counter).end()
.find('[name="count"]').attr('name', 'count-' + counter).end();
$('#barcode').prop('required', true);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-index');
counter--;
// Remove element containing the fields
$('#barcode').prop('required', false);
$row.remove();
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-6">
<form id="form1" method="post" action="actions?do=barcodePaleta_submit" class="form-horizontal" role="form">
<fieldset>
<div class="form-group">
<label for="inputName" class="col-md-1 col-sm-2 control-label">box:</label>
<div class="col-md-3 col-sm-4">
<input type="text" pattern=".{23,23}" class="form-control" name="barcode" required/>
</div>
<label for="inputName" class="col-md-1 col-sm-2 control-label">num:</label>
<div class="col-md-1 col-sm-3">
<input type="number" min="0" class="form-control" name="productsInBox" required/>
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i>
</button>
</div>
</div>
<div id="addLine" class="form-group hide">
<label for="inputName" class="col-md-1 col-sm-2 control-label">box:</label>
<div class="col-md-3 col-sm-4">
<input id="barcode" type="text" pattern=".{23,23}" class="form-control" name="barcode" />
</div>
<label for="inputName" class="col-md-1 col-sm-2 control-label">num:</label>
<div class="col-md-1 col-sm-3">
<input type="number" min="0" class="form-control" name="productsInBox" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="form-group myTop">
<div class="col-lg-10 ">
<button type="submit" name="formAction" value="next" class="btn btn-primary">submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
I miss understood question.try this for + button
if($('#barcode').attr('required') != true){
$('#barcode').attr('required',true);
}
this for - button
if($('#barcode').attr('required')){
$('#barcode').removeAttr('required');
}

cant get textbox value with space - jquery

I have a text box and a button , I writed a script that when clicked on button , create new textbox and Add it to form .
but when I have text Like 32 bit and clicked on button It created a textbox with value like 32 . I get inspect element and result was :
<input type="text" name="Options" class="field-input add-more" value="32" bit="">
my script:
$("#add-more").click(function(e){
e.preventDefault();
var text = $("#more-text");
var newTag = '<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" value='+ text.val() + ' /><span class="btn-sm btn-danger remove-me field-input">x</span></div>';
$("#frm-fields").append(newTag);
text.val("");
});
please see below example .
$("#add-more").click(function(e){
e.preventDefault();
var text = $("#more-text");
var newTag = '<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" value='+ text.val() + ' /><span class="btn-sm btn-danger remove-me field-input">x</span></div>';
$("#frm-fields").append(newTag);
text.val("");
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row " id="div-fields">
<div class="col-lg-12">
<div class="form-horizontal" id="frm-fields-options">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" id="more-text" />
<div class="input-group-addon">
<span class="btn btn-sm btn-success" id="add-more">+</span>
</div>
</div>
</div>
<div id="frm-fields" class="row">
</div>
</div>
</div>
</div>
Use jQuery method .val() to set text by converting HTML string in to a jQuery object.
//Create a jQuery object
var newTag = $('<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" /><span class="btn-sm btn-danger remove-me field-input">x</span></div>');
//Set the text and append to form
$("#frm-fields").append(newTag.find('input').val(text.val()).end());
$("#add-more").click(function(e) {
e.preventDefault();
var text = $("#more-text");
var newTag = $('<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" /><span class="btn-sm btn-danger remove-me field-input">x</span></div>');
$("#frm-fields").append(newTag.find('input').val(text.val()).end());
text.val("");
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row " id="div-fields">
<div class="col-lg-12">
<div class="form-horizontal" id="frm-fields-options">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" id="more-text" />
<div class="input-group-addon">
<span class="btn btn-sm btn-success" id="add-more">+</span>
</div>
</div>
</div>
<div id="frm-fields" class="row">
</div>
</div>
</div>
</div>
You forgot to include the double-quotes:
$("#add-more").click(function(e){
e.preventDefault();
var text = $("#more-text");
$("#frm-fields").append('<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" value="' + text.val().replace(/\"/g, '"') + '" /><span class="btn-sm btn-danger remove-me field-input">x</span></div>');
text.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row " id="div-fields">
<div class="col-lg-12">
<div class="form-horizontal" id="frm-fields-options">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" id="more-text" />
<div class="input-group-addon">
<span class="btn btn-sm btn-success" id="add-more">+</span>
</div>
</div>
</div>
<div id="frm-fields" class="row">
</div>
</div>
</div>
</div>
This line is not balanced .Opening and closing quotes for value attribute is not proper.
'<div class="col-lg-3"><input type="text" name="Options" class="field-input add-more" value='+ text.val() + ' />
Also you need check there is an empty space between quotes is this line
$("#more-text").val(" ");
JS
$("#add-more").click(function(e){
e.preventDefault();
var text = $("#more-text").val();
console.log(text);
var newTag = '<div class="col-lg-3">'+
'<input type="text" name="Options" class="field-input add-more" value="'+text+'"/>'+
'<span class="btn-sm btn-danger remove-me field-input">x</span>'+
'</div>';
$("#frm-fields").append(newTag);
$("#more-text").val(" ");
});
JSFIDDLE
You have to put a "" quotes around your value attribute as the value is space separated:
value="'+ text.val() + '"

Categories

Resources