Appended field Issue - javascript

I am having this problem, that whenever i am trying to get value from dynamic section it is not showing anything
the html part:
<div class="modal fade" id="mcqModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Multiple Choice Question</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="mcq" action="{{ route('poll.mcq') }}" method="post">
<input type="hidden" name="poll_id" value="{{ $poll->id }}">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Question:</label>
<input type="text" class="form-control" id="mcqque" name="question[question]">
</div>
<fieldset>
<legend>Options</legend>
<ul class="addli list-group" id="allLi">
<style>
.addinp{
float:right;
width: 30%;
position: relative;
}
</style>
<button type="button" class="addinp btn btn-success float-right" onclick="newLi(this)"> Add new Field </button>
<li class="list-group-item">
<input type="checkbox" class="correct col-md-2" id="mcqcorrect" >
<input type="hidden" name = "inp correct[]" value="0">
<input type="text" class="col-md-8" name = "answers[]">
</li>
</ul>
<input type="submit" class="form btn btn-primary" value="Save">
</form>
</fieldset>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div
script:
function newLi(event){
var ul = document.getElementById('allLi');
var li = document.createElement('li');
li.className = 'list-group-item';
li.innerHTML = ' <input type="checkbox" class="correct col-md-2" id="mcqcorrect" ><input type="hidden" name = "inp correct[]" value="0"><input type="text" class="col-md-8" name = "answers[]">';
ul.appendChild(li);
}
This newLi is appending the child successfully but
second script:
$('.correct').on('click',function(){
if($(this).is(':checked')){
$('.inp').val(1);
}
else{
$('.inp').val(0);
}
});
on click on the checkbox, I want its input value to be which is working very well for the static HTML part but not for the dynamic part
please help me solve this issue
any help will be highly appreciated
Thanks in advance

When you have dynamic added fields on your page you need to change your code a little bit, because when the page is loaded at first the jquery sees only what's initially there... and if there are new elements added jquery doesn't take them in concern... so with this code you check the whole document if there is any element with that class:
$(document).on('click', '.correct', function () {
if($(this).is(':checked')){
$('.inp').val(1);
} else {
$('.inp').val(0);
}
});

Related

How to dynamically choose an option from a dynamically populated dropdown

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!

How to unhide form on link click?

How can I show my html form when the edit link is clicked?
Anchor tag:
edit
Hidden html form:
<div class="modal fade" id="form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">+ Type Kamar</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" enctype="multipart/form-data" id="form">
<input type="hidden" name="id" value="<?= $utk["id"]; ?>">
<input type="hidden" name="gambarLamaa" value="<?= $utk["gambarr"]; ?>">
<input type="hidden" name="">
<div class="form-group">
<label for="room">Room</label>
<input type="text" class="form-control" id="room" name="room" value="<?= $utk["room"]; ?>">
</div>
<div class="form-group">
<label for="type">Type</label>
<input type="text" class="form-control" id="type" name="type" value="<?= $utk["type"]; ?>">
</div>
<div class="form-group">
<label for="gambarr">picture</label>
<br>
<img src="../img/<?= $utk['gambarr']; ?>" width="700"> <br>
<input type="file" class="form-control" id="gambarr" name="gambarr">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="ubah" class="btn btn-primary">Add</button>
</form>
</div>
</div>
</div>
</div>
I would suggest to not to use aria-hidden="true" to hide your content because if you hide it for now and when you need to again unhide it (setting its value to aria-hidden="false") after clicking on the link it will misbehave inconsistently across browsers.(According to MDN WebDocs)
So instead use display:none to hide your form
<div class="modal fade" id="form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="display:none">
Also set an id for the link
edit
And you will need javascript to unhide it when clicked on the link as.
JS
<script>
document.getElementById('link').onclick = function(){
document.getElementById('from').style.display = "block";
};
</script>
You should change your a href tag to:
edit
Then add a div around your form, id ="show-form", change the css of the div to:
#show-form {
display: none; }
and then add the following javascript:
<script>function show() {
var x = document.getElementById("show-form");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
} </script>

span onClick JQuery change text

I'm trying to get a value from the database: SenderDriver->total_trips.
And all great, but I want to get a specific id so I have to put it into onClick(), then it set the value from the database variable: SenderDriver->total_trips.
This is the code
<span onclick="readd( amounts{{$referral_detail->SenderDriver->total_trips}});"
data-target="#addMoneyModel" data-toggle="modal" id="{{$referral_detail->GetterDriver->id }}">
<a data-original-title="Add Money" data-toggle="tooltip" id="{{ $referral_detail->GetterDriver->id }}" data-placement="top" class="btn text-white btn-sm btn-success menu-icon btn_detail action_btn">
<i class="fa fa-money-bill"></i>
</a>
</span>
Now I want the val to change a specific text when it's clicked using the above code. Btw all this is in .blade.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
function readd(){
$("input:text").val(amounts);
}
</script>
I tried a lot nothing working any help?
The input
<div class="modal fade text-left" id="addMoneyModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel33"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<label class="modal-title text-text-bold-600" id="myModalLabel33">#lang('admin.message200')</label>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ route('merchant.AddMoney') }}" method="post">
#csrf
<div class="modal-body">
<label>#lang('admin.message203'): </label>
<div class="form-group">
<select class="form-control" name="payment_method" id="payment_method" required>
<option value="1">#lang('admin.message201')</option>
<option value="2">#lang('admin.message202')</option>
</select>
</div>
<label>#lang('admin.message204'): </label>
<div class="form-group">
<input type="text" name="receipt_number" value="0"
class="form-control" required>
</div>
<label>#lang('admin.message205'): </label>
<div class="form-group">
<input type="text" id="amount" name="amount"
class="form-control" required>
<input type="hidden" name="add_money_driver_id" id="add_money_driver_id">
</div>
<label>#lang('admin.message206'): </label>
<div class="form-group">
<input class="form-control" id="title1" rows="3" name="description"
value="Refer Gift">
</div>
</div>
<div class="modal-footer">
<input type="reset" class="btn btn-outline-secondary btn-lg" data-dismiss="modal" value="close">
<input type="submit" class="btn btn-outline-primary btn-lg" value="Add">
</div>
</form>
</div>
</div>
</div>
Not 100% sure what you're trying to accomplish, but here are my thoughts anyway.
In your onclick implementation you provide an argument to the function readd, which you're not using/defining in your javascript code at the bottom.
It appears that you try to push the value into the input text field of your bootstrap modal with the id="amount"
Here is the improved JavaScript section:
<script type="text/javascript">
function readd(amount){
$("#amount").val(amounts);
}
</script>
I'm not sure if the bootstrap toggle possibly overrides the onclick event of the span element. If that's the case you need to approach that issue a bit different
<script type="text/javascript">
function readd(amount){
$("#amount").val(amounts);
// Do something with the id
const some_important_id = $(this).attr('data-id');
console.log(some_important_id);
$('#addMoneyModel').modal('show');
}
</script>
and remove the modal stuff from your Span element.
<span onclick="readd( {{$referral_detail->SenderDriver->total_trips}});" data-id="{{$referral_detail->GetterDriver->id }}">

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.

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