Button is working before ajax call in bootstrap Modal.
But After Ajax call click event is not working.
function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
$.ajax({
type: "POST",
url: "/add_appointment_planner",
data: { contract_id: contract_id,job_id : job_id, planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
success: function(data){
if(data['status']=='success')
{
show_notification(data['status'],data['message']);
$("#apt_status_table").load(location.href + " #apt_status_table");
$(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");
}
}
});
}
I Have tried below solutions ,
Solution-1 :-
$(document).on('click', '.appointment_edit_button', function(){
alert("success");
});
Solution-2 :-
$(document).delegate('click', '.appointment_edit_button', function(){
alert("success");
});
I tried with unbind() also. It also not working.
When I put script directly in Console. Then it's working. So may be it's due to bootstrap modal.
So, I want to enable button click event after ajax call in bootstrap modal.
EDIT :-
HTML Code :-
<tbody>
<tr>
<td>
<div class="agenda-date">
<div class="dayofmonth color_font_date">2017-06-01</div>
<div class="dayofweek">
thursday </div>
</div>
</td>
<td>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
1,43)">am </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="8" name="" class="number_planner"></a>
<input type="number" value="9" name="" class="max_limit" disabled="">
<input type="hidden" value="am" name="" class="timeslot_max_limit" disabled="">
</div>
<div class="row margin_two_planner">
<button type="button" class="btn btn-sm btn-primary" onclick="book_appointment_timeslot(19,"2017-06-01",
2,43)">pm </button>
<a data-toggle="modal" href="#add_apt_status" class=""><input type="number" value="6" name="" class="number_planner"></a>
<input type="number" value="5" name="" class="max_limit" disabled="">
<input type="hidden" value="pm" name="" class="timeslot_max_limit" disabled="">
</div>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap appointment_note" required="required" rows="3" name="appointment_note" cols="50" aria-required="true" disabled=""> asdsad </textarea>
</td>
<td style="width: 20%;">
<textarea id="" class="form-control initial_cap holiday_note" required="required" rows="3" name="holiday_note" cols="50" aria-required="true" disabled=""> asasdsaddsad </textarea>
</td>
<td>
<div class="text-right">
<input type="hidden" class="planner_date" name="" value="2017-06-01">
<input type="hidden" class="contract_id" name="" value="43">
<button type="button" id="" class="btn btn-primary appointment_edit_button">edit </button>
<button type="button" id="" onclick="planner_note_edit(10,event)" class="btn btn-md btn-primary appointment_update_button" style="display:none"> update </button>
<button type="button" id="" class="btn btn-md btn-cancel appointment_cancel_button" style="display:none">cancel </button>
</div>
</td>
</tr>
</tbody>
Through this appointment_edit_button class I'm doing this process.
$(".appointment_edit_button").on("click",function(event) {
$(this).closest('tr').find(".appointment_note").prop("disabled", false);
$(this).closest('tr').find(".holiday_note").prop("disabled", false);
$(this).closest('tr').find(".max_limit").prop("disabled", false);
$(this).next('button').show();
$(this).next('button').next('button').show();
$(this).hide();
});
I looks like.
I am guessing your dom is manipulated by that ajax success callback so the click event registration is removed. Try to bind the click event again in the ajax callback.
function book_appointment_timeslot(job_id,planner_date,time_slot,contract_id){
$.ajax({
type: "POST",
url: "/add_appointment_planner",
data: { contract_id: contract_id,job_id : job_id, planner_date: planner_date, time_slot: time_slot, _token: CSRF_TOKEN },
success: function(data){
if(data['status']=='success')
{
show_notification(data['status'],data['message']);
$("#apt_status_table").load(location.href + " #apt_status_table");
$(".tbl_planner_list_whole").load(location.href + " .tbl_planner_list_whole");
$('.appointment_edit_button').click(function(){alert("success");});
}
}
});
}
After ajax response, your binding to div for specific call (click in your case) is removed as DOM area is loaded. Try to initialize your bindings again in ajax response success.
Related
I am creating a survey app that dynamically adds a dropdown box , and two text boxes.Once an option is selected from the dropdown it populates the selected option . Unforunately the first option works but for the others it simply populates the data I selected in the first.The overall goal is to input it inside a database using php.This is my php script
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
$number = count($_POST["name"]);
$crops = count($_POST["selectedCrop"]);
// echo $number;
// echo $crop;
if ($number > 0) {
for ($i=0; $i<$number; $i++) {
if (trim($_POST["name"][$i] != '')) {
$sql = "INSERT INTO tbl_name(name,crop) VALUES('".mysqli_real_escape_string($connect, $_POST["selectedCrop"][$i])."' ,'".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
mysqli_query($connect, $sql);
}
}
echo "Data Inserted";
} else {
echo "Please Enter Name";
}
The result are as follows The Image with the duplicated resukts
Here is my HTML Code and the Javascript I am using to achieve
<body>
<div class="container">
<div class="page-header">
<h1 class="text-center">SURVEY</h1>
</div>
<div class="container">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<strong>E. FARMING AND AGRIBUSINESS </br>Farming</strong>
</div>
<div class="panel-body">
Which of the value chains did your household produce in September 2016 through rain fed production mechanisms? Or you produce now through rain fed production mechanisms?<i>Select all options applicable – 1, 2 up to last</i>
<br />
<form name="add_name" id="add_name">
<!-- This is the Table That I am adding the widgets dynamically -->
<table class="table table-striped table-bordered" id="dynamic_field">
<thead>
<tr>
<th>Name of Crop Options</th>
<th>Crop Selected</th>
<th>Produced/produce this value chain in 2015/2016?</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="dropdown" name= "crops[]">
<button id="crop" onchange="copyValue()" class="btn dropdown-toggle" type="button" data-toggle="dropdown" >
Name of Crop<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Maize</li>
<li>Beans</li>
<li>Tomatoes</li>
<li>Potatoes</li>
</ul>
</div>
</td>
<td>
<input type="text" name="selectedCrop[]" id="selectedCrop" placeholder="Enter your Name" class="form-control name_list" />
</td>
<td>
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
</td>
<td>
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</td>
<!-- <td><button type="button" name="remove" id="'0'" class="btn btn-danger btn_remove">X</button></td></tr> -->
</tr>
</tbody>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><div class="dropdown" name= "crops[]"><button class="btn dropdown-toggle" type="button" data-toggle="dropdown" >Name of Crop<span class="caret"></span></button><ul class="dropdown-menu"><li>Maize</li> <li>Beans</li><li>Tomatoes</li><li>Potatoes</li></ul></div></td><td><input type="text" name="selectedCrop[]" id="selectedCrop" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"farming_and_agribusiness_1_copy.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
$(function(){
$(".dropdown-menu li a").click(function(){
$("#crop:first-child").text($(this).text());
$("#crop:first-child").val($(this).text());
$("#selectedCrop:first-child").text($(this).text());
$("#selectedCrop:first-child").val($(this).text());
});
});
</script>
<!-- Survey - END -->
</div>
</body>
I want when I click on Clear button, all fields in the form to be cleared.
The ajax request is only replacing the form from the tag <form> to </form>.
When it is clicked on Clear button, the console output is working.
I have the following form:
<div class="col-lg-5 formWrapper">
<form data-th-fragment="layoutForm" id="layoutForm" class="form-horizontal" data-th-object="${layout}" data-th-action="#{/layouts/add}" method="POST" role="form">
<div class="row">
<input id="objectId" data-th-field="*{id}" type="hidden">
<input data-th-if="*{filePath} !=null" data-th-field="*{filePath}" type="text" hidden="hidden">
<label for="layoutName" >Layout name</label>
<input data-th-field="*{name}" id="layoutName" class="form-control" type="text">
</div>
<div class="row">
<div class="col-lg-4">
<label for="status">Status</label>
<select id="status" data-th-field="*{status}"class="form-control">
<option value="1">Active</option>
<option value="0">Blocked</option>
</select>
</div>
<div class="col-lg-6">
<label for="exhibitorName">Exhibitor</label>
<select data-th-field="*{exhibitor}" name="exhibitorName" id="exhibitorName" class="form-control">
<option data-th-each="exhibitor : ${exhibitorsList}" data-th-value="${exhibitor.id}" data-th-text="${exhibitor.exhibitorName}"></option>
</select>
</div>
</div>
<div class="row">
<div class=" col-lg-3">
<input id="clearForm" type="reset" value="Clear" class="form-control btn-lg btn btn-default">
</div>
<div class=" col-lg-3 col-lg-offset-4">
<input id="submitButton" type="submit" value="Add" class="form-control btn-lg btn btn-success">
</div>
</div>
</form>
</div>
The form looks something like this:
The jQuery is as follow:
$(document).ready(function() {
$('.formWrapper').on('click','#clearForm', function (event) {
$(this).closest('form').find("input[type=text]").val("");
console.log("ASD");
});
});
The snipped is how I replace the form:
$("body").on('click','#editLayout', function(event){
var ajax = $.ajax({
url : "/layouts/edit/" + $(this).data("id"),
dataType : "html",
success: function (data) {
$("#layoutForm").replaceWith(data);
$('#submitButton').val('Edit').addClass('btn-warning').removeClass('btn-success');
}
});
});
Try this,
$('#form_id').trigger("reset");
or
$('#form_id')[0].reset();
A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use a script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.
Try to use $('#clearForm').reset(); or $('#clearForm')[0].reset();
This is my code, it appends the input form after the user clicks the "Add more" button.
How can I change the input field to a dropdown menu that queries the data from mysql?
Thank you ^^
My HTML code
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
My javascript
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
Here is my HTML and jquery Ajax Code, i want when first row successfully proceed, One new row created by jquery. However first row properly work and proceed, but when second row created by ajax. it does not work, when i submit, it redirect on same page. Please check my code and let me know why my second row not work properly. how i can handle this situation ?
HTML CODE:
<div id="songsList">
<div class="songRow">
<div class="SongStatus"></div>
<form action="" method="POST" class="songsForm">
<div class="col-sm-3">
<input type="text" name="song_title" class="form-control" placeholder="Song Title">
</div>
<div class="col-sm-2">
<input type="text" name="singer_name" class="form-control" placeholder="Singer Name">
</div>
<div class="col-sm-2">
<input type="text" name="album_name" class="form-control" placeholder="Album Name">
</div>
<div class="col-sm-1">
<input type="text" name="album_year" class="form-control" placeholder="Year">
</div>
<div class="col-sm-3">
<input type="text" name="song_url" class="form-control" placeholder="Song Url http://">
</div>
<input type="hidden" name="songsSubmit" value="yes">
<div class="copySongUrl"><button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button></div>
</form>
</div>
<hr />
</div>
Jquery/Ajax Code:
$(function() {
$('.songsForm').submit(function (event) {
event.preventDefault();
event.returnValue = false;
$.ajax({
type: 'POST',
url: 'post.php',
data: $(this).serialize(),
beforeSend: function() {
$(".copySongUrl :button").remove();
$(".copySongUrl").append('<img src="images/ajax-loader.gif" class="ajaxImage">');
},
success: function(res) {
if (res == 'success') {
$(".ajaxImage").remove();
$('input[name=song_title]').attr("disabled", true);
$('input[name=singer_name]').attr("disabled", true);
$('input[name=album_name]').attr("disabled", true);
$('input[name=album_year]').attr("disabled", true);
$('input[name=song_url]').attr("disabled", true);
$('.copySongUrl').append("<button type='button' id='plain-copy' class='btn btn-info'><i class='glyphicon glyphicon-paperclip'></i> Copy Url</button><script>document.getElementById('plain-copy').addEventListener('click', function() { clipboard.copy('<?php if(isset($_SESSION['uploadedUrl'])) echo $_SESSION['uploadedUrl']; ?>').then(function(){ document.getElementById('plain-copy-result').textContent = 'success'; }, function(err){ document.getElementById('plain-copy-result').textContent = err; });});<\/script>");
// Here Adding New Row, Similar Like Top HTML
$('#songsList').append('<div class="songRow"> <div class="SongStatus"></div> <form action="" method="POST" class="songsForm"><div class="col-sm-3"><input type="text" name="song_title" class="form-control" placeholder="Song Title"></div><div class="col-sm-2"><input type="text" name="singer_name" class="form-control" placeholder="Singer Name"></div><div class="col-sm-2"><input type="text" name="album_name" class="form-control" placeholder="Album Name"></div><div class="col-sm-1"><input type="text" name="album_year" class="form-control" placeholder="Year"></div><div class="col-sm-3"><input type="text" name="song_url" class="form-control" placeholder="Song Url http://"></div><input type="hidden" name="songsSubmit" value="yes"><div class="copySongUrl"><button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button></div> </form></div><hr />');
} else {
$(".ajaxImage").remove();
$(".copySongUrl").append('<button type="submit" class="songUploadButton" class="btn btn-primary"><i class="glyphicon glyphicon-upload"></i> Upload</button>');
$(".SongStatus").append("<div class='alert alert-info'><li class='glyphicon glyphicon-warning-sign'></li> <b>"+ res +"</b></div>");
}
},
error: function () {
$('.SongStatus').html('Failed').slideDown();
}
});
});
});
You should change this:
$('.songsForm').submit(function (event) {
to this:
$('.songsList .songRow').submit('.songsForm',function (event) {
This is called delegated event.
Since your original code is pin pointing an element (could be a set of elements), it attaches the event to the element/s once only, and when further clones are created they dont have the event attached.
Delegated events are basically applied to the parent (element container) and then whenever an identified element is rendered within the parent, the element is immediately attached.
You can read here: Event Delegation
I've a form containing input fields and checkboxes (table crud generating dynamically). See the image below:
Here, In my clients modal dialog form I've implemented small crud for adding/updating/deleting Providers data and showing table below of it on the fly.
Following is my code:
View:
<form name="clientForm" ng-submit="check(id)" ng-controller="ClientsController">
<div class="form-group">
<label for="name">Name</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Name" ng-model="client.name">
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Email" ng-model="client.email">
</div>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-earphone"></i></span>
<input type="text" class="form-control" id="title" placeholder="Enter Phone" ng-model="client.phone">
</div>
</div>
<div class="form-group">
<label for="phone">Providers</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="glyphicon glyphicon-hand-right"></i></span>
<input type="text" class="form-control" id="title" ng-model="provider.provider_name" placeholder="Enter Provider Name">
</div>
<br>
<button type="button" id="addbtn" class="btn btn-sm btn-primary" ng-click="addProvider()">Add Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-info" ng-click="updateProvider(id)">Update Provider</button>
<button type="button" id="editbtn" class="btn btn-sm btn-default" ng-click="clearProvider()">Clear Provider</button>
<br>
<table style="width: 50%; margin-top: 10px;" class="">
<tbody>
<tr ng-repeat="val in providersData">
<td>
<input type="checkbox" name="providersData" ng-model="$parent.client.providersList" value="{{val._id}}"/>
</td>
<td>{{val.provider_name}}</td>
<td>
<a style="color: blue;" href="javascript:void(0);" ng-click="editProvider(val._id)"><i class="glyphicon glyphicon-edit"></i></a>
<a style="color: red;" href="javascript:void(0);" title="Delete" confirmed-click="removeProvider(val._id)" ng-confirm-click="Are you sure you want to remove provider?"><i class="glyphicon glyphicon-trash"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="well well-lg text-center bg-gray">
<button class="btn btn-success" ng-if="id">Save Client</button>
<button class="btn btn-danger" ng-if="id" title="Delete" confirmed-click="remove(client._id)" ng-confirm-click="Are you sure you want to remove?">Delete</button>
<button type="button" class="btn btn-warning" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button class="btn btn-success" ng-if="!id">Add Client</button>
</div>
</form>
Controller:
$scope.showModal = false;
$scope.client = {};
$scope.provider = null;
$scope.addClient = function () {
alert(JSON.stringify($scope.client));
$http.post('/clients', {param: $scope.client}).success(function (response) {
if (response) {
alert("Client added successfully");
$scope.client = "";
refresh();
$scope.closemodal();
}
});
};
Now I want to insert/update selected checkboxes value to db along with Name, Email, and Phone field.
Here I'm facing following issues:
Whenever I'm clicking on any checkbox its checking all checkboxes.
After clicking on Add Client button its showing result of alert(JSON.stringify($scope.client)) like this
{"name":"asdfdsafasdf","email":"sdf","phone":"sadf","providersList":{"id":true}}
In mongodb its showing like this:
I've search a lot tried this and ng-model="$parent.client.providersList.id" but still its not working.
I'm beginner in AngularJS and just started working on it.
Any help would be appreciated.
You should use ng-true-value & ng-false-value over the checkbox(I'm considering default value to be 0). And then use $index of providersData ng-repeat to create an array of client.providersList.
Markup
<input type="checkbox" name="{{'providersData'+$index}}"
ng-model="client.providersList[$index].id" ng-true-value="val._id" ng-false-value="0" />
You are facing this problem because of the value of your ng-model attribute. The value for ng-model attribute must be different for each checkbox. Here, try this:
<input type="checkbox" name="providersData" ng-model="client.providersList{{$index}}" ng-value="val._id" />
Try something like this:
$scope.client = {};
$scope.client.providersList = [];
// Now watch the model for changes
$scope.$watch('client', function(){
// When the checkbox is selected it returns true
if($scope.client.providersList1 == true){
$scope.client.providersList.push({"id": value})
}
// Repeat the if statements for all the checkboxes (or use a for loop)
}, true);