JQuery Datetimepicker not working when loaded dynamically - javascript

Im having trouble getting the datetimepicker to load fully in the following:
it adds the elements to the page but clicking on the calendar icon does not function like the first set does.
Im new to web page building be gentle
Here is the jsfiddle: https://jsfiddle.net/gq8a7k14/
The first 2 datetimepickers work fine, when you click the add button, a new set is added but they dont work.
<?php
?>
<html>
<head>
<title>SubmitYourTime</title>
<link href='assets/css/phppot-style.css' type='text/css' rel='stylesheet' />
<link rel='stylesheet' type='text/css'
href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datetimepicker/4.17.42/css/bootstrap-datetimepicker.min.css'>
<style type='text/css'>
.container {
margin-top: 40px;
}
.btn-primary {
width: 100%;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://momentjs.com/downloads/moment.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.42/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type='text/javascript'>
$( document ).ready(function() {
$('#datetimepicker0s').datetimepicker();
$('#datetimepicker0e').datetimepicker();
$('.add').on('click', add);
$('.remove').on('click', remove);
});
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
$("#datetimepicker" + new_chq_no + "s").datetimepicker();
$("#datetimepicker" + new_chq_no + "e").datetimepicker();
var new_input = "<div class='row'> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>Start Time</label> <div class='input-group date' name='dtp" + new_chq_no + "s' id='datetimepicker" + new_chq_no + "s'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'> </span> </span> </div> </div> </div> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>End Time</label> <div class='input-group date' name='dtp" + new_chq_no + "e' id='datetimepicker" + new_chq_no + "e'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'></span> </span> </div> </div> </div> </div>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).remove();
$('#total_chq').val(last_chq_no - 1);
}
}
</script>
</head>
<body>
<div class='container'>
<div class='panel panel-primary'>
<div class='panel-heading'>Enter Your Time</div>
<div class='panel-body'>
<div id='new_chq'>
<div class='row'>
<div class='col-md-6'>
<div class='form-group'>
<label class='control-label'>Start Time</label>
<div class='input-group date' name='dtp0s' id='datetimepicker0s'>
<input type='text' class='form-control' />
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</div>
</div>
</div>
<div class='col-md-6'>
<div class='form-group'>
<label class='control-label'>End Time</label>
<div class='input-group date' name='dtp0e' id='datetimepicker0e'>
<input type='text' class='form-control' />
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</div>
</div>
</div>
</div>
</div>
<input type='hidden' value='1' id='total_chq'>
<button class='add'>Add Time</button>
<br></br>
<input type='submit' class='btn btn-primary' value='Submit'>
</div>
</div>
</body>
</html>

You need to initialize the datepicker() after it is appended to the page, currently when you attempt to initialize it the selector does not find anything.
modified fiddle
original
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
$("#datetimepicker" + new_chq_no + "s").datetimepicker();
$("#datetimepicker" + new_chq_no + "e").datetimepicker();
var new_input = "<div class='row'> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>Start Time</label> <div class='input-group date' name='dtp" + new_chq_no + "s' id='datetimepicker" + new_chq_no + "s'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'> </span> </span> </div> </div> </div> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>End Time</label> <div class='input-group date' name='dtp" + new_chq_no + "e' id='datetimepicker" + new_chq_no + "e'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'></span> </span> </div> </div> </div> </div>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
modified
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<div class='row'> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>Start Time</label> <div class='input-group date' name='dtp" + new_chq_no + "s' id='datetimepicker" + new_chq_no + "s'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'> </span> </span> </div> </div> </div> <div class='col-md-6'> <div class='form-group'> <label class='control-label'>End Time</label> <div class='input-group date' name='dtp" + new_chq_no + "e' id='datetimepicker" + new_chq_no + "e'> <input type='text' class='form-control' /> <span class='input-group-addon'> <span class='glyphicon glyphicon-calendar'></span> </span> </div> </div> </div> </div>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
$("#datetimepicker" + new_chq_no + "s").datetimepicker();
$("#datetimepicker" + new_chq_no + "e").datetimepicker();
}

Related

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

After adding input field in div using jquery form is submitted on enter

I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to add multiple expenses as shown in picture. But after appending the div input field (Cost) on enter the page is submitted. and the chosen css is not working (class is not working).
Please help me i dont understand that why the page is submitted on enter key in input field.
my code is:-
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<jsp:include page="../template.document.head.jsp" />
<script>
$(function() {
$("#expenses").addClass('menu_item_active');
var groupId = $("#id").val();
if (groupId != '') {
$("#heading").text("Edit Expense Details");
} else {
$("#heading").text("Add New Expense");
}
});
$(document).ready(function() {
$("#expense_id").change(function() {
var expense_id = $("#expense_id").val();
populateSubExpenses(expense_id);
});
});
var subgroups;
function populateSubExpenses(expense_id){
var url = "http://" + window.location.host + "/transport/getexpensesbygroup?exp_grp_id="+expense_id;
$.get(url, function(data) {
subgroups = data;
populateSubExp(data, 0);
}, "json");
}
function populateSubExp(data, id){
var selectedDeviceModel = $('#name');
if(id != 0)
selectedDeviceModel = $('#name_' + id);
selectedDeviceModel.empty();
selectedDeviceModel.append(' <option value=""> Select Expense Name</option>');
$.each(data, function(key, value) {
selectedDeviceModel.append('<option value="'+key+'">'+value+'</option>');
selectedDeviceModel.trigger("chosen:updated");
});
}
var row = 1;
function removeStops(row) {
calTotalCost(row);
$("#row"+row).remove();
}
function addExpense(){
var htm = "<div class='row' id='row"+row+"'>"
+ "<div style='width:215px; height: 24px;float:left;padding-right:10px;margin-top: 0px;'>"
+ "<select name='name' id='name_" + row + "' style='height: 24px; margin-top: 10px;width:150px !important' class='chosen-select-width' tabindex='1'>"
+ "<option value='' label='Select Expense Name' />"
+ "</select>"
+ "</div>"
+ "<div style='width:55px; height: 24px;float:left;padding-right:10px;margin-top: 10px;'>"
+ "<input type='text' name='payment' id='payment_" + row + "' class='txt-field number-field' maxlength='6' style='width:50px;' onfocusout='calTotalCost(" + row + ")' onKeyDown='if(event.keyCode==13) calTotalCost(" + row + ")'/>"
+ "</div>"
+ "<div style='width:305px; height: 24px;float:left;margin-top: 10px;'>"
+ "<textarea name='remark' id='remark_" + row + "' class='txt-field' style='width:300px;'></textarea>"
+ "</div>"
+ "<div style='width:50px; height: 24px;float:left;margin-top: 10px;'>"
+ "<input type='button' value='Remove' class='btn-login' style='font-size: 10px; margin-top: 1px; margin-left: 20px;' onclick='removeStops(" + row + ");'/>"
+ "</div>"
+ "</div>";
$("#expenseDiv").append(htm);
populateSubExp(subgroups, row);
row++;
}
function calTotalCost(row) {
var i = 0;
var final_payment = 0;
for(i; i <= row ; i++){
if(i == 0)
payment = $('#payment').val();
else
payment = $('#payment' + '_' + i).val();
if (payment != undefined)
final_payment = parseFloat(final_payment) + parseFloat(payment);
}
$('#final_payment').val(final_payment);
}
</script>
<div class="frm-block-outer" style="width:70%;">
<div class="headinginner">
<h3 id="heading" style="margin: 0px;"></h3>
</div>
<div class="frm-wrapper" style="width: 980px;">
<form:form action="${pageContext.request.contextPath}/transport/addexpense" modelAttribute="expenseSubGroup" id="frmLogin" method="post" commandName="expenseSubGroup">
<div style="float: left;">
<fieldset class="mem-field-set">
<legend>Account Group Details</legend>
<form:input path="id" id="id" type="hidden" class="txt-field" />
<div class="nmem-input-pair mandatory">
<label>Date: <span class="req_field">*</span></label>
<div class="row-field">
<form:input path="expense.expense_date" id="expense_date" class="txt-field date-field-fy"/>
<form:errors path="expense.expense_date" class="field-error"></form:errors>
</div>
</div>
<div class="nmem-input-pair mandatory">
<label>Expense Group:<span class="req_field">*</span></label>
<div class="row-field">
<form:select path="expense.id" id="expense_id" style="height: 24px;width:150px !important" class="chosen-select-width" tabindex="1">
<form:option value="" label="Select Account Name" />
<form:options items="${groupName}"/>
</form:select>
<form:errors path="expense.name" class="field-error"></form:errors>
</div>
</div>
<div class="nmem-input-pair mandatory">
<label>Through:<span class="req_field">*</span></label>
<div class="row-field">
<form:select path="expense.partner_id" style="height: 24px;width:150px !important" id="partner_id" class="chosen-select-width" tabindex="1">
<form:option value="" label="Select" />
<form:options items="${partners}"/>
</form:select>
<form:errors path="expense.partner_id" class="field-error"></form:errors>
</div>
</div>
<fieldset>
<hr>
<div style="margin-left: 100px;" id="expenseDiv">
<div style="float: left;width: 685px;margin-top: 10px;margin-bottom: 10px;">
<div style="float: left; width: 200px; text-align: center;">
<label>Expense</label>
</div>
<div style="float: left; width: 100px; text-align: center;">
<label>Cost</label>
</div>
<div style="float: left; width: 300px; text-align: center;">
<label>Description</label>
</div>
</div>
<div style="width:215px; height: 24px;float:left;padding-right:10px;">
<form:select path="name" style="height: 24px;width:150px !important" class="chosen-select-width" tabindex="1">
<form:option value="" label="Select Expense Name" />
</form:select>
</div>
<div style="width:55px; height: 24px;float:left;padding-right:10px;">
<form:input path="payment" id="payment" class="txt-field number-field" maxlength="6" style="width:50px;" onfocusout="calTotalCost(0)" onKeyDown="if(event.keyCode==13) calTotalCost(0)"/>
</div>
<div style="width:305px; height: 24px;float:left;">
<form:textarea path="remark" class="txt-field" style="width:300px;"></form:textarea>
</div>
<div style="width:50px; height: 24px;float:left;">
<a onclick="addExpense();"><input title="Add" class="jqueryaddrow" type="button" style="font-size: 10px; margin-top: -1px; margin-left: 20px;"></a>
</div>
</div>
</fieldset>
<fieldset>
<hr>
<div class="nmem-input-pair mandatory">
<label>Total Payment:<span class="req_field">*</span></label>
<div class="row-field">
<form:input path="expense.final_payment" id="final_payment" class="txt-field number-field" maxlength="6" style="width:50px;"/>
<form:errors path="expense.final_payment" class="field-error"></form:errors>
</div>
</div>
<div class="nmem-input-pair">
<label>Remark:<span class="req_field"></span></label>
<div class="row-field">
<form:textarea path="expense.remark" class="txt-field"></form:textarea>
</div>
</div>
</fieldset>
</fieldset>
</div>
<div class="mem-input-pair" style="margin-left: 184px;">
<div class="login-btn gapl-110">
<a href="${pageContext.request.contextPath}/transport/expense">
<input type="button" value="Cancel" class="btn-grey" style="width:105px;" />
</a>
</div>
<div class="login-btn">
<input name="updatebtn" id="updatebtn" type="submit" value="Save" class="btn-login" style="width:105px;" />
</div>
</div>
</form:form>
</div>
</div>
<jsp:include page="../template.document.tail.jsp" />
as per html form will trigger submit on hit of enter but if you want to prevent it with jquery you can prevent it by following code
$("#frmLogin").on("submit", function(){
return false;
})

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