How to dynamically choose an option from a dynamically populated dropdown - javascript

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!

Related

Select box change event not appear inside modal bootstrap when reopen

i created select box change event when option in select box is "reschedule" inside bootstrap modal.
first time pop up modal change event is working. but when modal is closed and reopened change event is not running when select "reschedule" in select box.
how to solve this problem
this is script for change event select box
const date = document.getElementById('date');
$('#selector').on('change', function() {
var divClass = $(this).val();
$(".op").hide();
$("." + divClass).slideDown('medium');
const value = document.getElementById('selector').value;
date.required = (value == "Reschedule");
});
.op {
display: none;
}
<div class="row" style="margin-left:4px;">
<div class="col-md-12">
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="user_uid">Action</label>
<div class="col-sm-10">
<select name="agree" class="form-control" id="selector" required>
<option value="" disabled selected>Select Action..</option>
<option value="Accepted">Accept</option>
<option value="Reschedule">Reschedule</option>
<option value="Rejected">Reject</option>
</select>
</div>
</div>
</div>
</div>
<div class="row op Reschedule" style="margin-left:4px;">
<div class="col-md-12">
<div class="form-group row">
<label class="col-sm-2 col-form-label " for="user_uid">Reschedule Datetime</label>
<div class="col-sm-10">
<input class="form-control" id="date" name="date" type="datetime-local" min="<?php echo date(" Y-m-d "); ?>T00:00">
</div>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
i use another file to save the contents of the modal and open using javascript to send variabel using GET.
this is script for modal javascript
<a data-toggle="modal" data-target="#viewdata" data-id="' . $row['id_cdd'] . '" class="viewda dropdown-item" aria-label="Left Align" style="cursor:pointer" data-backdrop="static" data-keyboard="false" title="View"> View </a>
<div id="viewdata" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Candidate Detail</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<input type="hidden" class="form-control" id="idview" name="idview"></input>
<div class="modal-body body-view">
</div>
</div>
</div>
</div>
<script>
$(document).on("click", ".viewda", function() {
var myBookId = $(this).data('id');
var myBook2 = $(this).data('session');
$(".body-view #idview").val(myBookId);
$.ajax({
url: "cdd_inc_modal.php?view=" + myBookId+"&session="+myBook2,
cache: false,
success: function(result) {
$(".body-view").html("");
$(".body-view").html(result);
}
});
});
</script>

Get Textbox value from bootstrap modal dynamically

I have a table that will retrieve all the users information along with a button that will open a popup modal to edit the user details. The Modal will display the user data correctly , but when I try to save the changes that the user has entered on a button click, the value of the textboxes will be the first row of the table bot the one that the user entered. How can I get the value of the textbox that is currently displayed on the modal popup.
My View:
<div class="form-group" align="center">
<table id="AllUsersTable2" class="display" style="width:100%;">
<tr>
<th>id</th>
<th>FullName</th>
<th>username</th>
<th>MobileNumber</th>
<th>Email</th>
<th>IsActiveText</th>
<th>RoleName</th>
<th>Edit</th>
</tr>
#foreach (var user in Model.UserTable)
{
<tr>
<td>#user.NationalID</td>
<td>#user.FullName</td>
<td>#user.username</td>
<td>#user.MobileNumber</td>
<td>#user.Email</td>
<td>#user.IsActiveText</td>
<td>#user.RoleName</td>
<td><button class="btn btn-primary" id="" data-toggle="modal" data-target="##user.NationalID">عرض</button></td>
</tr>
//PopUp Starts HERE
<div class="modal fade" id="#user.NationalID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
#using (Html.BeginForm(Html.BeginForm(null, null, FormMethod.Post, new { #id = "UpdateUserForm" })))
{
<div class="modal-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="NationalID" class="control-label">رقم الهوية</label>
<input type="text" id="UpdateuNationalID" name="NationalID" value="#user.NationalID" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="FullName" class="control-label">الإسم</label>
<input type="text" id="UpdateFullName" name="FullName" value="#user.FullName" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="username" class="control-label">اسم المستخدم</label>
<input type="text" id="Updateusername" name="username" value="#user.username" class="control-label" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="MobileNumber" class="control-label">رقم الهاتف</label>
<input type="text" id="UpdateMobileNumber" name="MobileNumber" value="#user.MobileNumber" class="control-label" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Email" class="control-label">البريد الإلكتروني</label>
<input type="text" id="UpdateEmail" name="Email" value="#user.Email" class="control-label">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="IsActive" class="control-label">حالة المستدم</label>
<select name="IsActive" id="UpdateIsActive">
<option value="">...</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="RoleId" class="control-label">البريد الإلكتروني</label>
<select name="RoleId" id="UpdateRoleId">
<option value="">...</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
</div>
</div>
</div>
</div>
}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn">تعديل المستخدم </button>
</div>
</div>
</div>
</div>
//PopUp END HERE
}
</table>
</div>
My Click Event:
$('body').on('click', '.UpdateUserBtn', function (e) {
var NationalID = $("#UpdateuNationalID").val();
console.log(NationalID);
var username = $('#Updateusername').val();
var FullName = $('#UpdateFullName').val();
var MobileNumber = $('#UpdateMobileNumber').val();
var Email = $('#UpdateEmail').val();
var RoleId = $('#UpdateRoleId').val();
var IsActive = $('#UpdateIsActive').val();
$.post("#Url.Action("UpdateUser", "Home")", { NationalID: NationalID, username: username, FullName: FullName, MobileNumber: MobileNumber, Email: Email, RoleId: RoleId, IsActive: IsActive }, function (data) {
if (data.Result == 1) {
//closePopup();
$.notify(
"تم الحفظ بنجاح",
{
globalPosition: 'top center',
className: 'success'
}
);
}
else {
console.log(data);
$.notify(
"حدث خطأ أثناء الحفظ ",
{
globalPosition: 'top center',
className: 'danger'
}
);
// console.log(data);
}
});
});
The problem here for example the value of $("#UpdateuNationalID").val(); will be always the value of first row of the table not the value that is displayed on the popup..
The problem as said by #Carsten Løvbo Andersenis is that you are using the same Id when generating the HTML, so your jQuery var NationalID = $("#UpdateuNationalID").val(); will take the first value that he find.
To solve this, you need to assign a different Id in every loop, for example you can do ad follow if we suppose that NationalID is unique :
<input type="text" id='UpdateuNationalID #user.NationalID' name="NationalID" value="#user.NationalID" class="control-label" required>
EDIT:
You have to create a function for example SaveMe instead to wait for the event click, and you need to send a value on click in your modal:
<button type="button" id="UpdateUserBtn" class="btn btn-primary UpdateUserBtn" onclick="SaveMe(#user.NationalID)">تعديل المستخدم </button>
and your event listner first line $('body').on('click', '.UpdateUserBtn', function (e) {
change it to be a function:
function SaveMe(myId) {
var str1 = 'UpdateuNationalID ' + myId;
var NationalID = document.getElementById(str1).innerHTML;
// or
var NationalID = document.getElementById(str1).value;
// then
console.log(NationalID);

JavaScript - Taking user input and using in calculation to validate value

I have a modal that allows users to 'refuel' by filling out a form where they can input the amount of fuel to add, however the maximum fuel amount is 180 litres, so if the existing fuel is 170 litres (the existing fuel value will be retrieved from a database), and the user tries to add 20 litres, it should produce an error. I've got some code already, but it's not producing the error. If anyone could point out the issue it would be greatly appreciated.
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
JSFiddle Demo
The problem is here:
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
Your div has id="fuel" and so does the input. Remove the id from the div or make it unique. Also, there is no name attribute for div elements, you should remove that as well.

Form inside bootstrap modal not updating values in mysql

I have a table in my page which displays data about a certain request.
When I click the 'Add Cedula Number', which is a button, it shows a bootstrap modal. And inside it, has a form.
The value in the ID which is 14 is the ID of that row and it came from this code:
<td class=" ">
<button class="btn btn-primary btn-xs" id="<?php echo $data['idPerson'];?>" data-toggle="modal" data-target="#myModal"> Add Cedula Number </button>
</td>
Now, in order to pass the value in the modal, I used this code:
<script>
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').html(' <div class="form-group"><label class="col-sm-3 control-label">ID</label><div class="col-sm-9"><input type="text" value = ' + e.relatedTarget.id +' class="form-control" id="person_id" name="person_id" readonly="readonly"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Date</label><div class="col-sm-9"><input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Cedula Number</label><div class="col-sm-9"><input type="number" class="form-control" id="cedula_number" name="cedula_number"/></div></div>' );
})
</script>
This is my modal code:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<form id="addCedula" action="paid_cedula.php" class="form-horizontal calender" name = "addCedula" enctype="multipart/form-data" method="post" role="form">
<div class="modal-body"></div>
<div class="modal-footer" style="margin:0;">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button id="send" type="submit" class="btn btn-success" name="addCedula">Save Record</button>
</div>
</form>
</div>
</div>
</div>
And my php code is this:
<?php
include 'config.php';
if(isset($_POST['addCedula'])){
$id = $_POST['person_id'];
$date = $_POST['cedula_date'];
$number = $_POST['cedula_number'];
$sql = mysqli_query($conn, "UPDATE person SET dateOfCedulaPayment='$date' AND cedulaNumber='$number' WHERE idPerson='$id';");
mysqli_close($conn);
}
?>
I've been trying to look for the error for hours now. I really can't seem to find where. The value doesn't update in the database. Where did I go wrong? Your help will be much appreciated. Thank you.
#Fred's answer solved the problem (error in Update Query), Here is my 2 cent
This script is overkill to pass the data to modal.
<script>
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').html(' <div class="form-group"><label class="col-sm-3 control-label">ID</label><div class="col-sm-9"><input type="text" value = ' + e.relatedTarget.id +' class="form-control" id="person_id" name="person_id" readonly="readonly"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Date</label><div class="col-sm-9"><input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date"></div></div> <div class="form-group"> <label class="col-sm-3 control-label">Cedula Number</label><div class="col-sm-9"><input type="number" class="form-control" id="cedula_number" name="cedula_number"/></div></div>' );
})
All you need is change id="<?php echo $data['idPerson'];?>" to data-id="<?php echo $data['idPerson'];?>" and following 3 to 4 lines of script do the same job.
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
alert(id);
$("#person_id").val(id);
});
});
Modal HTML
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<form id="addCedula" action="paid_cedula.php" class="form-horizontal calender" name = "addCedula" enctype="multipart/form-data" method="post" role="form">
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">ID</label>
<div class="col-sm-9">
<input type="text" value = "" class="form-control" id="person_id" name="person_id" readonly="readonly">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Date</label>
<div class="col-sm-9">
<input type="date" readonly="readonly" class="form-control" id="cedula_date" value="<?php echo date("Y-m-d");?>" name="cedula_date">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Cedula Number</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="cedula_number" name="cedula_number"/>
</div>
</div>
</div>
<div class="modal-footer" style="margin:0;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="send" type="submit" class="btn btn-success" name="addCedula">Save Record</button>
</div>
</form>
</div>
</div>
</div>
Your query is incorrect. That isn't how UPDATE works. You need to use a comma and not the AND logical operator http://dev.mysql.com/doc/en/logical-operators.html
UPDATE person SET dateOfCedulaPayment='$date', cedulaNumber='$number' WHERE idPerson='$id';
Reference:
http://dev.mysql.com/doc/en/update.html
Checking for errors on your query would have triggered a syntax error:
http://php.net/manual/en/mysqli.error.php
Sidenote: To see if your query (UPDATE) was truly successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
In not doing so, you may get a false positive.
Nota:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.

Modal Dialog Validation ASP.NET/bootstrap

I've been trying to validate some control in a modal dialog for days now, and despite all the examples and other posts here on SO I can't seem to get it working...
In my webpage I have a button that opens a modal dialog. That modal dialog has three required input boxes: one for text and two for positive numeric values. I want to validate the inputs when the user clicks save using the fancy bootstrap feedback scheme like these examples:
http://formvalidation.io/examples/modal/
http://1000hz.github.io/bootstrap-validator/
If the input is valid then I'll take the values and process accordingly. I haven't gotten this far though. The modal does open currently.
I know these examples use forms, but since I'm using a master page, a nested form in my content page isn't allowed. So how can I validate the input and apply the feedback style to the invalid controls when the user clicks save?
<!-- Button to trigger modal -->
<button type="button" id="btnOpenModal" class="btn btn-info" data-toggle="modal" data-target="#myModal">Add</button>
<!-- Bootstrap Modal Dialog -->
<div class="modal fade" id="myModal" data-toggle="validator" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Here is the modal dialog</h4>
</div>
<div id="loginForm" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtWgt" class="col-sm-3 control-label">Weight (LB)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtWeight" name="mdltxtWeight" placeholder="weight in pounds" />
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtLength" class="col-sm-3 control-label">Length (IN)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtLength" name="mdltxtLength" placeholder="length in inches" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
</div>
</div>
</div>
I probably could change the project to not use a master page to make life easier with forms - it's not required (default Web Forms project in VS2015 sets this up automatically).
Just to add...I'm primarily a VB.NET winforms developer so I'm probably missing a lot of fundamentals on ASP.NET and javascript so go easy on me.
Using the Bootstrap Validate plugin, you cannot validate input elements that are outside of a <form></form>. There is no workaround for this limitation.
with a Form id="Form"
<form id="Form">
<div class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
</form>
Fiddle with Form
When form id="Form" changed into a div id="Form" and now the same code cannot be validate by Bootstrap Validate plugin. The plugin does nothing without a <form></form>.
<div id="Form" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" />
<%--<button type="submit" class="btn btn-primary">Save changes</button>--%>
</div>
Fiddle with Div
So as Shehary pointed out the Bootstrap Validate plugin won't work on a modal dialog that is not a form. So to emulate the same effect, I added a span tag to each input to provide the feedback text and use javascript to to the validating and add the feedback styles.
Here is the modal:
<div class="modal fade" id="myModal" data-toggle="validator" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Here is the modal dialog</h4>
</div>
<div id="loginForm" class="modal-body form-horizontal">
<h5>Describe what to do here...</h5>
<div class="form-inline form-group">
<label for="mdltxtId" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" pattern="^.{1,}" title="Item name required" class="form-control" id="mdltxtId" name="mdltxtId" placeholder="item description"/>
<span id="mdlIdHelper" class="help-block h6"></span>
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtWgt" class="col-sm-3 control-label">Weight (LB)</label>
<div class="col-sm-9">
<input type="text" pattern="^[+]?([.]\d+|\d+[.]?\d*)" title="Positive number only" class="form-control" id="mdltxtWeight" name="mdltxtWeight" placeholder="weight in pounds" />
<span id="mdlWgtHelper" class="help-block h6"></span>
</div>
</div>
<div class="form-inline form-group">
<label for="mdltxtArm" class="col-sm-3 control-label">Arm (IN)</label>
<div class="col-sm-9">
<input type="text" pattern="^[0-9]{1,}" title="Positive number only" class="form-control" id="mdltxtArm" name="mdltxtArm" placeholder="arm length in inches" />
<span id="mdlArmHelper" class="help-block h6"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="btnmdlSave2" onclick="CloseModal(); return false;">Save</button>
</div>
</div>
</div>
</div>
And here is the javascript:
function OpenModal() {
//window.alert('opening modal');
ResetModal();
//window.alert('modal was reset');
$('#myModal').modal('show');
//window.alert('modal was opened');
}
function ResetModal() {
//window.alert('beginning modal reset');
var mdlId = $('#mdltxtId');
var mdlWgt = $('#mdltxtWeight');
var mdlArm = $('#mdltxtArm');
// reset the item description input group
mdlId.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlId.val('');
mdlIdHelper.innerHTML = "";
// reset the item weight input group
mdlWgt.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlWgt.val('');
mdlWgtHelper.innerHTML = "";
// reset the arm length input group
mdlArm.closest('.form-group').removeClass('has-error').removeClass('has-success');
mdlArm.val('');
mdlArmHelper.innerHTML = "";
//window.alert('finished modal reset');
}
function ValidateModal() {
var mdlId = $('#mdltxtId');
var mdlWgt = $('#mdltxtWeight');
var mdlArm = $('#mdltxtArm');
var val = true
// Check if the input is valid
if (!mdlId.val()) {
// Add errors highlight
mdlId.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlIdHelper.innerHTML = "You must enter a description";
val = false
} else {
// Add success highlight
mdlId.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlIdHelper.innerHTML = "";
}
// Check if the input is valid
if (!mdlWgt.val() || !$.isNumeric(mdlWgt.val()) || mdlWgt.val() <= 0) {
// Add errors highlight
mdlWgt.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlWgtHelper.innerHTML = "Item weight must be a positive numeric value";
val = false;
} else {
// Add success highlight
mdlWgt.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlWgtHelper.innerHTML = "";
}
// Check if the input is valid
if (!mdlArm.val() || !$.isNumeric(mdlArm.val()) || mdlArm.val() <= 0) {
// Add errors highlight
mdlArm.closest('.form-group').removeClass('has-success').addClass('has-error');
mdlArmHelper.innerHTML = "Arm length must be a positive numeric value";
val = false;
} else {
// Add success highlight
mdlArm.closest('.form-group').removeClass('has-error').addClass('has-success');
mdlArmHelper.innerHTML = "";
}
// return false if there was an error in the modal dialog. A FALSE return value will prevent a postback to the server. Might be redundant since the button onclick also has 'return false'.
return val;
}
I faced the same problem, probably it's too late but here is the code I did. It's useful if you don't care about use ajax and json...
<!-- Modal -->
<div class="modal fade" id="modalOption" tabindex="-1" role="dialog" aria-labelledby="modalOptionLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="modalOptionLabel">Options</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Save", "Option", FormMethod.Post, new { id = "frmTest" }))
{
Html.AntiForgeryToken();
<div class="row">
<div class="col-md-6">
<div class="col-md-6">
#Html.LabelFor(model => model.VALUE1)
#Html.TextBoxFor(model => model.VALUE1, String.Format("{0:#0.00}", Model.VALUE1), new { #class = "form-control input-decimal" })
#Html.ValidationMessageFor(model => model.VALUE1, "", new { #class = "label label-danger" })
</div>
</div>
<div class="col-md-6">
<div class="col-md-6">
#Html.LabelFor(model => model.VALUE2)
#Html.TextBoxFor(model => model.VALUE2, String.Format("{0:#0.00}", Model.VALUE2), new { #class = "form-control input-decimal" })
#Html.ValidationMessageFor(model => model.VALUE2, "", new { #class = "label label-danger" })
</div>
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary btn-sm crud-save" id="SaveOption" data-target="#modalOption" data-container="#divOptionGrid" form="frmTest">Save</button>
</div>
</div>
</div>
</div>
<script>
$(document).off('click', '.crud-save').on('click', '.crud-save', function (event) {
var formName = $(this).attr("form");
var form = $("#" + formName)
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
var isValid = $(form).validate().form();
if (!isValid) {
event.preventDefault();
return false;
}
var formInfo = form.serialize();
//here goes your ajax implementation
$.ajax({
type: form.attr('method'),
dataType: "json",//response by using json
url: form.attr('action'),
data: formInfo,
success: function (customJson) //just return a JsonResult from the controller if the process is successful
{
if(customJson.isDone){
alert("Done");
$("#modalOption").modal('hide');
}
else{
alert(customJson.errorMessage);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
}
});
</script>

Categories