Cant' put number in value of text input using jquery - javascript

I have a list that has several option. I dynamically set an event that whenever a button is clicked, create a table and text input and put the value of list in in there, but I have option that have number value but it didn't set to the value of that input. See my code.
My jquery code:
$("#table_drugs").append("<tr><td>"
+ $("#drugs_list").val() + "<input type='text' name='past_druges_used' value="+$("#drugs_list").val()+">"
+ "</td><td>" + $("#drugs-explain").val()+"<input type='text' name='how_to_use' value="+$("#drugs-explain").val()+">"
+ "</td><td>" + "<button type='button' class='col-sm-7 btn btn-danger pull-right'>delete</button> "
+ "</td></tr>");
And my html:
<div class="col-md-12">
<div id="drugs_list_div" class="form-group">
<div class="col-md-4 col-md-offset-6">
<select id="drugs_list" class="form-control" style="font-family: font-style-3;">
<option>empty</option>
<option>Drugs 1</option>
<option>Drugs 3</option>
<option>Drugs 2</option>
</select>
</div>
</div>
<div id="drugs-explain-div" class="form-group">
<div class="col-md-4 col-md-offset-6">
<input type="text" class="form-control" id="drugs-explain" style="font-family: font-style-1;">
</div>
</div>
</div>
<div class="col-md-12">
<div id="table-drugs-div" class="col-xs-11 list-hide">
<table class="table table-striped" id="table_drugs">
</table>
</div>
</div>

You need to put quotes around your values:
$("#table_drugs").append("<tr><td>"
+ $("#drugs_list").val() + "<input type='text' name='past_druges_used' value='"+$("#drugs_list").val()+"'>"
+ "</td><td>" + $("#drugs-explain").val()+"<input type='text' name='how_to_use' value='"+$("#drugs-explain").val()+"'>"
+ "</td><td>" + "<button type='button' class='col-sm-7 btn btn-danger pull-right'>delete</button> "
+ "</td></tr>");

Related

Div based on selection not working, when new selection line was added

i want to create form when there will be possibility to add/remove additional selection rows, but all of this new selection should have possibility to show DIV depends on selected option.
Everything is working fine for first row which is loaded with page, DIV is showing input form, normal text or another selection (this one not need to show anything in additional DIV) based what we choosed.
But for added rows nothing happens after selection.
Any idea how to fix it or use another solution?
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div style="width:100%;">
Replace:
<form>
<div class="">
<div class="col-lg-10">
<div id="row">
<div class="input-group m-3">
<select class="custom-select custom-select-sm" name="test" id="type"><option>select one</option><option value="id">ID:</option><option value="client">Client:</option><option value="file">File:</option></select> with
<div id="values"></div>
<div class="input-group-prepend" style="margin-left: 20px;">
<button class="btn btn-danger" id="DeleteRow" type="button">
<i class="bi bi-trash"></i>
Delete row
</button>
</div>
</div>
</div>
<div id="newinput"></div>
<br />
<button id="rowAdder" type="button" class="btn btn-dark">
<span class="bi bi-plus-square-dotted">
</span> ADD row
</button>
</div>
</div>
</form>
</div>
$("#rowAdder").click(function () {
newRowAdd =
'<div id="row">' +
'<div class="input-group m-3">' +
'<br /><select class="custom-select custom-select-sm" name="test" id="type"><option>select one</option><option value="id">ID:</option><option value="client">Client:</option><option value="file">File:</option></select>' +
' with ' +
' <div id="values"></div>' +
' <div class="input-group-prepend" style="margin-left: 20px;">' +
' <button class="btn btn-danger"' +
' id="DeleteRow" type="button">' +
' <i class="bi bi-trash"></i>' +
' Delete row'+
' </button> </div>' +
'</div> </div>';
$('#newinput').append(newRowAdd);
});
$("body").on("click", "#DeleteRow", function () {
$(this).parents("#row").remove();
})
Example:
http://jsfiddle.net/3th96bac/
The main problem is that you are having multiple elements with the same Id. Id must be unique.
Second you'r $(".type").change(function() { will not get triggered by the newly added elements.
Demo
$(document).ready(function() {
$(document).on("change", ".type", function() {
var val = $(this).val();
if (val == "id") {
$(this).next(".values").html("<select><option>First option</option><option>Second Option</option></select>");
} else if (val == "client") {
$(this).next(".values").html("<input value='Example input' />");
} else if (val == "file") {
$(this).next(".values").html("normal text");
}
});
});
$("#rowAdder").click(function() {
newRowAdd =
'<div class="row">' +
'<div class="input-group m-3">' +
'<br /><select class="custom-select custom-select-sm type" name="test" id=""><option>select one</option><option value="id">ID:</option><option value="client">Client:</option><option value="file">File:</option></select>' +
' with ' +
' <div class="values"></div>' +
' <div class="input-group-prepend" style="margin-left: 20px;">' +
' <button class="btn btn-danger DeleteRow"' +
' id="" type="button">' +
' <i class="bi bi-trash"></i>' +
' Delete row' +
' </button> </div>' +
'</div> </div>';
$('#newinput').append(newRowAdd);
});
$("body").on("click", ".DeleteRow", function() {
$(this).closest(".row").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div style="width:100%;">
Replace:
<form>
<div class="">
<div class="col-lg-10">
<div class="row">
<div class="input-group m-3">
<select class="custom-select custom-select-sm type" name="test" id="">
<option>select one</option>
<option value="id">ID:</option>
<option value="client">Client:</option>
<option value="file">File:</option>
</select> with
<div class="values"></div>
<div class="input-group-prepend" style="margin-left: 20px;">
<button class="btn btn-danger DeleteRow" id="" type="button">
<i class="bi bi-trash"></i>
Delete row
</button>
</div>
</div>
</div>
<div id="newinput"></div>
<br />
<button id="rowAdder" type="button" class="btn btn-dark">
<span class="bi bi-plus-square-dotted">
</span> ADD row
</button>
</div>
</div>
</form>
</div>
Please check below working link for your question.
http://jsfiddle.net/kairavthakar2016/nkrqahpf/11/
Please modify your HTML and instead of ID please use the class and replace the jQuery with class name in the above mentioned example

By click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table

by click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table. How can I insert the data into table if the user add more experiences from model. On the click of the button the value in the value field should increment too and how can I enter if the user add any number of experiences so how can I enter the data in the table. I am inserting this data in table in row wise fashion in table
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<input type="hidden" name="1experience" id="1experience" value="<?php $i = 1; ?>">
<div class="form-group">
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience['status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience['status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
</div>
<script>
function addexperience(){
var i = $('#1experience').val();
i++;
$('#addexperience').append('<div class="col-md-3"> <label>Status</label> <select class="form-control" name="status'+i+'">'+
'<option value="">Select</option>'+
'<option value="Current">Current</option>'+
'<option value="Past">Past</option> </select> </div>'+
'<div class="col-md-3">'+
'<label>Designation</label>'+
'<input type="text" class="form-control" name="designation'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Duration</label>'+
'<input type="text" class="form-control" name="duration'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Employer</label>'+
'<input type="text" class="form-control" name="employer'+i+'">'+
'</div>'+
'</div>');
$(function () {
$('#1experience').val(i);
});
}
</script>
If you modify the HTML slightly in both the initial page display and within the javascript function so that the newly added items are grouped within a single container(div) and the initial elements are similarly grouped and a name assigned to the immediate ancestor of the initially displayed elements ( here I chose data-id='receiver' ) then this matter of deducing the number of times the elements have been added becomes a matter of counting the child elements within the common parent - querySelectorAll being useful here though no doubt jQuery has a concise method to do this too.
With that said though if you were to use the array syntax form form element names, such as designation[] or duration[] when the form is submitted you will have access to each element as an array in PHP ( or other backend language ) which will also, as a byproduct, reveal that same number of elements. Using the array syntax means you do not need to try to keep track of this number within the client
function addexperience() {
let i=document.querySelectorAll('[data-id="receiver"] > div').length;
$('[data-id="receiver"]').append('<div><div class="col-md-3"> <label>Status</label> <select class="form-control" name="status' + i + '">' +
'<option value="">Select</option>' +
'<option value="Current">Current</option>' +
'<option value="Past">Past</option> </select> </div>' +
'<div class="col-md-3">' +
'<label>Designation</label>' +
'<input type="text" class="form-control" name="designation' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Duration</label>' +
'<input type="text" class="form-control" name="duration' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Employer</label>' +
'<input type="text" class="form-control" name="employer' + i + '">' +
'</div>' +
'</div></div>');
alert(i);
document.querySelector('input[name="duplicates"]').value=i;
fetch( location.href, {method:'post',body:'total='+i})
.then(r=>r.text())
.then(text=>{
alert(text)
})
}
[data-id='receiver']{border:1px solid red;margin:1rem;padding:1rem;}
[data-id='receiver'] > div{margin:1rem;border:1px solid black;padding:0.5rem}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<div data-id='receiver' class="form-group">
<div>
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience[ 'status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience[ 'status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
<!-- additional content inserted here within common parent -->
</div>
</div>
<input type='hidden' name='duplicates' />

Addition On javascript Not working when new row is added

var str ="";
var counter=0;
$(document).ready(function() {
$(".amount, .penalty").change(function() {
var total = 0;
var amount = parseInt($(".amount").val()) || 0;
console.log("amount: "+amount);
var penalty = parseInt($(".penalty").val()) || 0;
console.log("penalty: "+penalty);
total = amount + penalty;
console.log(total);
$("#total").html(total);
});
$(".add").click(function() {
alert();
str +="<div class='form-group row' >"
+"<label class='col-xs-3 col-form-label mr-2'>Reason</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control' id='reason"+counter+"' name='reason'>"
+"</div>"
+"<label class='col-xs-3 col-form-label mr-2'>Amount</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control amount' id='amount"+counter+"' name='amount'>"
+"</div>"
+ "<label class='col-xs-3 col-form-label mr-2'>Penalty</label>"
+"<div class='col-xs-9'>"
+"<input type='text' class='form-control penalty' id='penalty"+counter+"' name='penalty'>"
+"</div>"
+ "<div class='col-xs-9'>"
+ "<button type='button' class='add'>+</button>"
+ "<button type='button' class='remove'>-</button>"
+ "</div>"
+ "</div>";
counter++;
$("#customsAdd").append(str);
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
</body>
</html>
The total "4" is coming only of first row and upto that my program is correct but when I add the new row then the total is not changing and new row is not added on after clicking "+" button.How to bring new row on "+" button press and change in total?The total is not changing after entering data in 2nd row and "+" is not working.
You have to use .on() for the event to work on dynamically created element. This will allow the event to work on the elements those are added to the body at a later time.
Change:
$(".add").click(function() {
To
$(".container").on("click", ".add", function() {
You can use .map() and reduce() to calculate the total. Try the following way:
var str = "";
var counter = 0;
var total = 0;
$(document).ready(function() {
$(".container").on("input", ".amount, .penalty", function() {
var tArr = $(".amount, .penalty").map(function(i,el){
return Number($(this).val());
}).get();
total = tArr.reduce((a,c) => a+c,0);
//console.log(total);
$("#total").html(total);
});
$(".container").on("click", ".add", function() {
str ="<div class='form-group row' >"
+"<label class='col-xs-3 col-form-label mr-2'>Reason</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control' id='reason"+counter+"' name='reason'>"
+"</div>"
+"<label class='col-xs-3 col-form-label mr-2'>Amount</label>"
+"<div class='col-xs-9'>"
+ "<input type='text' class='form-control amount' id='amount"+counter+"' name='amount'>"
+"</div>"
+ "<label class='col-xs-3 col-form-label mr-2'>Penalty</label>"
+"<div class='col-xs-9'>"
+"<input type='text' class='form-control penalty' id='penalty"+counter+"' name='penalty'>"
+"</div>"
+ "<div class='col-xs-9'>"
+ "<button type='button' class='add'>+</button>"
+ "<button type='button' class='remove'>-</button>"
+ "</div>"
+ "</div>";
counter++;
$("#customsAdd").append(str);
});
$(".container").on("click", ".remove", function() {
if($(".form-group.row").length > 1){ // remove only if there is more than one element
$(this).closest('.form-group.row').remove();
$(".amount, .penalty").trigger("input");
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
Mamun is right, you need on.
We can make some other improvements too.
We can use your existing row as a template, so if you change your html, you may not need to change your javascript.
You also have a logic issue with your addition function, it won't currently get all fields.
var str ="";
var counter=0;
$(document).ready(function() {
//Use existing row as a template
var rowTemplate = $("#forCustoms").clone(true);
$(".container").on("change", ".amount, .penalty",function() {
var total = 0;
/*NOTE: Not sure what you want to actuall do here
This will always get the fist values, not values
for all
var amount = parseInt($(".amount").val()) || 0;
console.log("amount: "+amount);
var penalty = parseInt($(".penalty").val()) || 0;
console.log("penalty: "+penalty);
*/
/*To Total all values*/
var amount = 0;
var penalty = 0;
$(".form-group,.row").each(function(){
amount += parseInt($(this).find(".amount").val(),10) || 0;
penalty += parseInt($(this).find(".penalty").val(),10) || 0;
})
total = amount + penalty;
console.log(total);
$("#total").html(total);
});
$(".container").on("click" ,".add",function() {
alert();
//Clone our template
var t2 = rowTemplate.clone(true);
//Make Ids Unique
$(t2).attr("id", "row" + counter);
$(t2).find("[name=reason]").attr("id", "reason" + counter);
$(t2).find("[name=amount]").attr("id", "amount" + counter);
$(t2).find("[name=penalty]").attr("id", "penalty" + counter);
counter++;
$("#customsAdd").append(t2);
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<!-- <select class="form-control col-md-6">
<option value="1">Customs</option>
<option value="2">VAT</option>
<option value="3">Excise</option>
<option value="4">Others</option>
</select>-->
<!--div for customs!-->
<div class="form-group row" id="forCustoms">
<label class="col-xs-3 col-form-label mr-2">Reason</label>
<div class="col-xs-9">
<input type="text" class="form-control" id="reason" name="reason">
</div>
<label class="col-xs-3 col-form-label mr-2">Amount</label>
<div class="col-xs-9">
<input type="text" class="form-control amount" id="amount" name="amount">
</div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label>
<div class="col-xs-9">
<input type="text" class="form-control penalty" id="penalty" name="penalty">
</div>
<div class="col-xs-9">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<!--div for customs! ends-->
<div id="customsAdd"></div>
<div class="col-md-12">
Total :
<p id="total"></p>
</div>
</div>
</body>
</html>

How to show text box in html which is declared in JavaScript

I had written JavaScript function to add text boxes with on click function. Here i need to show text boxes wherever i want in the page. The textbox code written in p tag with innerHTML but i need to show text boxes in html.
<div class="col-sm-4 col-md-4">
<div class="row">
<label class="control-label col-sm-12 col-md-10"> </label>
<div class="col-sm-4 col-md-4" id="div">
<div id="wrapper">
<div id="field_div">
<span class="glyphicon glyphicon-plus" onclick="add_field();"></span>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<div class="col-md-12" I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<script>
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("field_div").innerHTML = document.getElementById("field_div").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
</script>
You are adding the text box in incorrect div. Simply specify the id = 'childDiv' in the lower div and get the text box there.
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("childDiv").innerHTML = document.getElementById("childDiv").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
<div class="col-sm-4 col-md-4">
<div class="row">
<label class="control-label col-sm-12 col-md-10"> </label>
<div class="col-sm-4 col-md-4" id="div">
<div id="wrapper">
<div id="field_div">
<span class="glyphicon glyphicon-plus" onclick="add_field();">+</span>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<div id='childDiv' class="col-md-12"> I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-12">Child
</label>
<button onclick="add_field()">Add</button>
<div class="col-md-12" id="field_div"> I need to show text box here instead in javascript </div>
</div>
</div>
</div>
<script>
function add_field() {
var total_text = document.getElementsByClassName("input_text");
total_text = total_text.length + 1;
document.getElementById("field_div").innerHTML = document.getElementById("field_div").innerHTML +
"<p id='input_text" + total_text + "_wrapper'><input type='text' class='input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='text' class='form-control input_text' id='input_text" + total_text + "' placeholder='Enter Text'><input type='button' value='Remove' onclick=remove_field('input_text" + total_text + "');></p>";
}
function remove_field(id) {
document.getElementById(id + "_wrapper").innerHTML = "";
}
</script>

how to use closest with selection div

I have a dynamic form for items. First row items form will appear with (+) and (-) button, next they click (+) button and (-) in the previous row and now I have problem when I want to remove row that has (+) and (-), I need to add (+) button on previous row. I read about closest and find, but I cant use it.
here is my html
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
$('#item_' + index).closest("items").find("#btn_action").append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$('#item_' + index).remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Thanks for your help guys.
What you are looking for is .prev and not .closest.
As correctly pointed out by #Priyal Pithadiya, you will need to add a check before you add element.
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if (shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
Explanation
.closest: It looks in the hierarchy and get to the necessary element. It does not look for previous sibling.
.prev: It looks for previous sibling.
Sample:
var index = 1;
$(document).ready(function() {
addItems(index);
});
function addItems(index) {
$('#btn-add-item').remove();
$('#item_list').append(
"<div class='items' id='item_" + index + "'>" +
"<div class='row'>" +
"<div class='col-md-3'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_qty[]' placeholder='Item qty' data-error='Item qty cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-7'>" +
"<div class='form-group'>" +
"<input type='text' class='form-control' name='item_name[]' placeholder='Item name' data-error='Item name cannot empty' required>" +
"<div class='help-block with-errors'></div>" +
"</div>" +
"</div>" +
"<div class='col-md-2' id='btn_action'>" +
"<button id='btn-remove-item' type='button' class='btn btn-danger' style='margin-right: 5px' onclick='removeItem(" + index + ")'><i class='fa fa-minus'></i></button>" +
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>" +
"</div>" +
"</div>" +
"</div>"
);
index++;
}
function removeItem(index) {
var $item = $('#item_' + index)
var shouldAppendButton = !!$item.find('#btn-add-item').length;
if(shouldAppendButton)
$item
.prev()
.find("#btn_action")
.append(
"<button id='btn-add-item' type='button' class='btn btn-primary' onclick='addItems(" + (index + 1) + ")'><i class='fa fa-plus'></i></button>"
);
$item.remove();
index--;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">Tambah Transaksi</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Transaksi</li>
<li class="active">Tambah Transaksi</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="white-box">
<form action="#" class="form">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nomor Transaksi</label>
<input type="text" class="form-control" name="transaction_number" id="transaction_number" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Nama Pembeli</label>
<input type="text" class="form-control" name="buyer_name" id="buyer_name">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Alamat Pembeli</label>
<textarea type="text" class="form-control" name="buyer_address" id="buyer_address" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Items</label>
</div>
</div>
</div>
<div id="item_list"></div>
</form>
</div>
</div>
<div class="col-md-6 col-xs-12">
<div class="white-box">
</div>
</div>
</div>
Pointers:
IDs must be unique. Having same id in all items div is wrong.
You can also add a delegate instead of adding handlers in every item's markup

Categories

Resources