I have a Button called "Add New Menu" in my HTML page , onclick i am opening the Modal which contain a form and some <select></select>elements.
like this.
<button class="btn btn-success" onclick="add_menu()"><i class="glyphicon glyphicon-plus"></i> Add New Menu</button>
Here is my Modal.
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Menu Form</h3>
</div>
<div class="modal-body form">
<form id="form" class="form-horizontal" name="form">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Menu Title</label>
<div class="col-md-9">
<input name="menu_title" placeholder="Menu Title" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Parent Menu</label>
<div class="col-md-9">
<select name="parent_id" id="parent_id" class="form-control">
<option value=""> -- Select Parent Menu -- </option>
</select>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
If you have checked i have <select name="parent_id" id="parent_id" class="form-control"> in a form inside modal and having single option.
Now when user click on "Add New Menu" button i am calling the below function which is in Javascript.
function add_menu()
{
AppendMenuTitles();
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Menu'); // Set Title to Bootstrap modal
}
function AppendMenuTitles(){
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('insoadmin/menu/getMenus')?>/",
type: "POST",
dataType: "JSON",
success: function(data)
{
$.each(data.menus, function(i, item) {
//console.log(data[i].expert_name);
$('#parent_id').append($('<option>', {
value: data.menus[i].menu_id,
text : data.menus[i].menu_title,
}));
});
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error getting Menus , Please try again');
}
});
}
here everything works fine, i am getting data through an ajax but the problem is , each time user clicks on the "Add New Menu" button it keep appending the options to my select box, when it should be once only.
I dont want to append each time user clicks on the "Add new Menu" button and ya make sure each time user click on the "Add new button" i need to make an Ajax call for compulsory, then append options to the <select>
Another possibility is to test if the select has already the element.
Add element only if it does not exist in the select:
$.each(data.menus, function(i, item) {
if ($('#parent_id option[value="' + data.menus[i].menu_id + '"]').length == 0) {
$('#parent_id').append($('<option>', {
value: data.menus[i].menu_id,
text: data.menus[i].menu_title,
}));
}
});
success: function(data){
$('#parent_id').html('')
$.each(data.menus, function(i, item) {
//console.log(data[i].expert_name);
$('#parent_id').append($('<option>', {
value: data.menus[i].menu_id,
text : data.menus[i].menu_title,
}));
});
},
Put $('#parent_id').html(''), this will remove your older html
You should make the #parent_id empty before you append the code to it.
SO use this.
$('#parent_id').html('')
if you have any predefined values in the select box.add some class to the predefined options.
<select name="parent_id" id="parent_id" class="form-control">
<option class="predefined" value=""> -- Select Parent Menu -- </option>
and remove the rest of the options using jQuery.
$('#parent_id option:not(".predefined")').remove();
Related
My code is getting the data from PHP, then generating modals according to the number of items I have in the db. I have tried several solution of SO, how to get button ids according to the button clicked but don't find any solution.
When I click the any button generated, it sends only the first item of the modal form instead of the item clicked. I think the problem is the buttons not having unique id's. How to ensure that they have unique id's. Below is the code:
<div id="feedback">
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#feedback-modal-<?php echo $item['payment_id']; ?>">Add Payment</button>
</div>
<div id="feedback-modal-<?php echo $item['payment_id']; ?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Add Payment</h3>
</div>
<div class="modal-body">
<form class="feedback" name="feedback" method="POST">
<strong>Full Name</strong>
<br>
<input type="text" name="fullName" id="fullName" class="input-xlarge" value="<?php echo $item['full_name'] ?? 'Unknown';?>">
<br><br>
<strong>Subtotal</strong>
<br>
<input type="text" name="subtotal" id="subtotal" class="input-xlarge" value="<?php echo $item['subtotal'] ?? '0';?>">
<br><br>
<strong>Payment Method</strong>
<br>
<select name="paymentMethod" id="paymentMethod">
<option value="Cash1">Cash1</option>
<option value="Cash2">Cash2</option>
<option value="Cash3">Cash3</option>
</select>
<br><br>
<strong>Received by</strong>
<br>
<input type="text" name="receivedBy" id="receivedBy" class="input-xlarge" value="<?php echo $item['received_by'] ?? 'Unknown';?>">
</form>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="payment-btn" name="payment-btn">Send</button>
Close
</div>
</div>
</div>
</div>
The problem is that the button for sending the data have the same id, and ajax only accepts one id as shown below:
$(document).ready(function () {
$("button#payment-btn").click(function () {
$.ajax({
type: "POST",
url: "admin-server.php",
// url: "../Database/Payment.php",
data: 'contactFrmSubmit=1&fullName=' + $('#fullName').val() + '&subtotal=' + $('#subtotal').val() + '&paymentMethod=' + $('#paymentMethod').val() + '&receivedBy=' + $('#receivedBy').val(),
success: function (message) {
$("#feedback").html(message)
$("#feedback-modal").modal('hide');
},
error: function () {
alert("Error");
}
});
});
});
How can I have different id's?
I'm creating a company directory where you can create, read, update and delete entries about employees, departments, and locations. When updating a specific employee, accessed by a button on their employee's row:
You get a modal:
The code for this modal is:
<div class="modal fade" id="update_employee" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header update_header">
<h5 class="modal-title" id="exampleModalLongTitle">Update Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="updatingEmployee_problem" class="alert alert-danger alert-dismissible fade show" role="alert" style="display:none;">
<p id="description_of_update_problem"></p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div id="update_this_id" hidden></div>
<div class="form-group">
<label for="name">First Name</label>
<input class="form-control" id="update_fname">
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input class="form-control" id="update_lname">
</div>
<div class="form-group">
<label for="job_title">Job Title</label>
<input class="form-control" id="update_job_title">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="update_email">
</div>
<div class="form-group">
<label for="department">Department</label>
<div class="row ml-1">
<select data-width="450px" title="Select department" class="selectpicker" id="departmentSearch4" onchange='possibleLocations("#departmentSearch4", "dependentLocation2")'></select>
</div>
</div>
<div class="form-group">
<label for="location">Location</label>
<div class="row ml-1">
<select data-width="450px" title="Select location" id="dependentLocation2" class="selectpicker"></select>
</div>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault" onclick="certainDecision('updateTheEmployee')">
<label class="form-check-label" for="flexCheckDefault">
I am happy with the information provided.
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button onclick="updateEmployee()" class="btn btn-primary" id="updateTheEmployee" disabled>Update</button>
</div>
</form>
</div>
</div>
</div>
Departments can have multiple locations. Therefore, my location dropdowns are dynamically populated depending on which department is chosen.
The code for this is:
function possibleLocations(department, id) {
$.ajax({
type: 'POST',
url: 'libs/php/locationOptions.php',
data: {
department: $(department + ' option:selected').text()
},
success: function (result) {
while (document.getElementById(id).firstChild) {
document.getElementById(id).removeChild(document.getElementById(id).lastChild);
}
for (let i = 0; i < result.length; i++) {
var node = document.createElement("OPTION");
var textnode = document.createTextNode(result[i].name);
node.value = result[i].id;
node.appendChild(textnode);
document.getElementById(id).appendChild(node);
}
$('#' + id).selectpicker('refresh');
}
})
}
I fill in this modal, by executing this code when clicking on the row's edit button:
function update_this(ele) {
var row = ele.closest('tr');
var data = row.children;
var id = data[0].childNodes[0].data;
$('#update_this_id').text(id);
document.getElementById('update_fname').setAttribute('value', data[1].childNodes[0].data);
document.getElementById('update_lname').setAttribute('value', data[2].childNodes[0].data);
document.getElementById('update_job_title').setAttribute('value', data[3].childNodes[0].data);
document.getElementById('update_email').setAttribute('value', data[4].childNodes[0].data);
$('#departmentSearch4').val(data[5].childNodes[0].data).trigger('change');
$('#dependentLocation2').selectpicker('val', data[7].childNodes[0].data); << TRYING TO SELECT THE EMPLOYEE LOCATION FROM THE DYNAMIC LOCATION DROPDOWN
$('#update_employee').modal('show');
}
As departments can have multiple locations, I would like to automatically select the employee's location from the dynamic dropdown which is populated from the employee's department so that it looks 'filled out'. Any ideas on how I can achieve this?
I figured out one solution!
I can use a setTimeout so that the dropdown list has time to populate before I select the employee's location. I did it with the following code:
function update_this(ele) {
var row = ele.closest('tr');
var data = row.children;
var id = data[0].childNodes[0].data;
$('#update_this_id').text(id);
document.getElementById('update_fname').setAttribute('value', data[1].childNodes[0].data);
document.getElementById('update_lname').setAttribute('value', data[2].childNodes[0].data);
document.getElementById('update_job_title').setAttribute('value', data[3].childNodes[0].data);
document.getElementById('update_email').setAttribute('value', data[4].childNodes[0].data);
$('#departmentSearch4').val(data[5].childNodes[0].data).trigger('change');
setTimeout(function () { $('#dependentLocation2').selectpicker('val', data[7].childNodes[0].data) }, 1);
$('#update_employee').modal('show');
}
I would still love anyone else's ideas though of how to solve it!
I have a modal, e.g the modal is in modal.html, the method i wrote in a javascript file modal.js. when I am trying to submit data through modal, it is not working properly. the code is below. please help me someone.
/modal.html
<div class="col-md-12 text-right">
<button type="button" data-toggle="modal" data-target="#myModal">Update User Information</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Enter User Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="myFormSubmit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
/modal.js
$(function() {
$('#myFormSubmit').click(function () {
$.post("/api/adduserInfo/v1",
{
user_name : $("#user_name").val(),
email : $("#email_id").val(),
address : $("#address").val()
});
});
});
You can use something like this (you will have to get the parametres via post on the server side):
<!-- FORM -->
<form id="idform">
<!-- FORM INPUTS -->
<input class="btn btn-large btn-primary" value="Submit" type="submit">
</form>
<script>
// Variable to hold request
var request;
$("#idform").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$.ajax({
url: '/api/adduserInfo/v1',
type: 'post',
data: serializedData,
beforeSend: function () {
$("#divtoaddresult").html("Processing, please wait...");
},
success: function (response) {
$("#divtoaddresult").html(response);
}
});
});
</script>
i'm using the function eventClick on fullcalendarand i have the following problem, whenever i click at an event a modal is opening and i can edit this specific event, and when i click on save (with another onclick function) there is a confirm that is firing as many times as the modal has been opened previously.
let me explain it with my piece of code..
eventClick: function (calEvent, jsEvent, view) {
$('#myModalEditEvent').modal('show');
$("#deleteEventfromEditModal").click(function () {
if (!confirm("are you sure?")) {
return 0;
}
else {
var classID = calEvent.id;
var deleteRequest = {
classID: classID,
};
var dataString = JSON.stringify(deleteRequest); // parsing the request above.
$.ajax({ // starting an ajax func
})
};
});
}
this is my html code:
<div class="modal fade" id="myModalEditEvent" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="EditEventHeader"></h4>
</div>
<div class="modal-body">
<div class="form-group">
<select id="ClassesDDLEdit" class="form-control"></select>
</div>
<div class="form-group">
<select id="GuidesDDLEdit" class="form-control"></select>
</div>
<div class="input-group bootstrap-timepicker timepicker">
<input id="classStartTimeEdit" type="text" class="form-control input-small" placeholder="Start time">
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
</div><br />
<div class="input-group bootstrap-timepicker timepicker">
<input id="classEndTimeEdit" type="text" class="form-control input-small" placeholder="start time">
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
</div><br />
<div class="modal-footer">
<button type="button" id="AddEventAfetEditing" class="btn btn-info center-block" data-toggle="modal" data-target="#myModalEditEvent">Save</button><br />
<button type="button" id="deleteEventfromEditModal" class="btn btn-danger glyphicon glyphicon-trash center-block" data-toggle="modal" data-target="#myModalEditEvent"></button>
</div>
</div>
</div>
</div>
</div>
what can i do to prevent it from happening?
thanks all the help!
Change your following line
$("#deleteEventfromEditModal").click(function () {
as follow
$("#deleteEventfromEditModal").unbind( "click" ).click(function () {
Because on every click you are binding a click event. Therefore you need to unbind it every time
You should do this
$("#deleteEventfromEditModal").click(function () {
...
});
outside the eventClick, and do it in the page load for exemple.
$(document).ready(function(e){...})
I have this code for show confirm delete message before send form data:
JS:
$('input[name="S1"]').on('click', function (e) {
var $form = $(this).closest('form');
var checked = $("input:checked").length;
var action = $('select[name="todo"]');
if (action.val() === "delete" && checked) {
e.preventDefault();
$('#confirm').modal({
backdrop: 'static',
keyboard: false
})
.one('click', '#delete', function (e) {
$form.trigger('submit');
});
}
});
HTML Code:
<div class="panel-body">
<form method="POST" role="form" action="#">
<div class="row margin-bt-15">
<div class="col-md-6 col-sm-6 col-xs-12">
<select name="todo" class="contentgroup">
<option value="">choose</option>
<option value="delete">delete</option>
<option value="mark">mark</option>
<option value="unmark">unmark</option>
</select>
<input type="hidden" name="csrf_token" value="MTQzNjU3MDc3NjZPNXFKUmZWVlJWcE9ZNnd4VUZFbmRiSzMzSTZwMzRD">
<input type="submit" value="ok" class="btn btn-primary btn-sm" name="S1" />
</div>
</div>
</div>
<input type="checkbox" name="selected[]" class="check" value="4" />
</form>
</div>
<div id="confirm" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">delete</h4>
</div>
<div class="modal-body text-center">
<i class="fa fa-exclamation-triangle text-danger fa-lg flashitmap"></i>
<label>message</label>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger btn-sm" id="delete"><i class="fa fa-trash"></i>delete</button>
<button type="button" data-dismiss="modal" class="btn btn-sm">back</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now in PHP file i check $_POST using isset like this :
if ($_POST['todo'] && isset($_POST['S1']) && $_SERVER['REQUEST_METHOD'] == 'POST'){
echo 'true';
} else {
echo 'false';
always in result I see: false and my php code not detect isset($_POST['S1']) for my input name. how do can fix this ?
NOTE: when i remove bootstrap delete confirm, my form worked true and detect input name isset($_POST['S1']). I think my problem with bootstrap confirm code.
DEMO: http://jsfiddle.net/530j1hmp/2/
Apart form the things mentionned in the comments, there are several other to consider revision in your code.
$_POST['todo'] can be an empty string if the user has not selected an item, because there is value="". In PHP and other languages an empty string evaluates to false. Do you want it like this ?
if you have data in the $_POST array, then there it's a good bet your $_SERVER['REQUEST_METHOD'] equals 'POST'
To the main point: isset($_POST['S1']) will always be false. The element with name S1 is an input with type submit, and as such, it will be submitted ONLY if it is the submitter, ie only if it has been clicked. But with e.preventDefault(), you prevent that action, and the form is submitted through $form.trigger('submit');.
If you really need it, a solution could be to use a hidden field (type="hidden").
For more about which elements get submitted or not, you have the main rule on w3's site. Two other well known elements aren't submitted : radio button and checkbox if they have checkedness == false.