I'm working on a small project in ASP.NET MVC, and in one part I need help of javascript.
Acctually there is modal with three inputs, old password, new and confirm new password,
and in case all fields are empty I need to prevent user from closing modal, I tried to solve it like this:
function comparePasswords(currentPassword) {
//Here I will loop throught all of my three inputs to check are they empty
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty.');
$('#ChangePassword').modal({
backdrop: 'static',
keyboard: false // I need to prevent user from clicking ESC or something
})
}
}
But I get following error (check the image):
EDIT:
FULL CODE:
<div class="form-group">
<label for="UserPassword">Pw:</label>
#Html.TextBoxFor(model => model.PasswordHash, new { #class = "form-control custom-input", data_toggle = "modal", data_target = "#ChangePassword", ariaDescribedby = "basic-addon1" })
</div>
#*Modal for ChangePassword which is opening when user clicks on control above ^*#
<div id="ChangePassword" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating password</h4>
</div>
<div class="modal-body" id="allInputs">
#*Modal Old Password*#
<div class="form-group">
<label for="UserPassword">Old password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="Eldin123" name="oldPassword" id="OldPassword" data-toggle="modal">
</div>
#*Modal New Password*#
<div class="form-group">
<label for="UserPassword">New password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="newPassword" id="NewPassword" data-toggle="modal">
</div>
#*Modal Repeat New Password*#
<div class="form-group">
<label for="UserPassword">Confirm new password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="confirmPassword" id="ConfirmNewPassword" data-toggle="modal">
</div>
#*Modal - submit*#
<div class="confirm-login">
<button type="button" class="btn custom-btn-big" onclick="comparePasswords();">NEXT</button>
</div>
</div>
</div>
</div>
</div>#*end of Modal for ChangePassword*#
#*Confirm button*#
<div class="confirm-login">
<button class="btn custom-btn-big" data-target="#">SAVE ALL CHANGES</button>
</div>
</div>
</div>
</div> #*End of User / Administration*#
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
function fieldInvalid() {
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
console.log(formInvalid);
}
});
}
function passwordsInvalid() {
var invalidPassword = true;
var oldPw = $("#OldPassword").val();
var newPw = $("#NewPassword").val();
var confirmNewPw = $("#ConfirmNewPassword").val();
if (oldPw != newPw) {
alert('Postojeći password nije ispravan.');
}
else if (oldPw != confirmNewPw) {
alert('Password koji ste unijeli se ne slaže.');
}
else {
invalidPassword = false;
}
return invalidPassword;
}
var comparePasswords = function () {
if (fieldInvalid()) {
alert('One or more fields is empty.');
}
else {
if (!passwordsInvalid()) {
$("#ChangePassword").modal('hide');
}
}
}
</script>
}
So when someone clicks on password input, modal will be opened, and from that modal after informations are there user should click on button "NEXT" and there is event onclick which is calling comparePasswords method.
You are missing bootstrap library file.
Order of the file should be
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Same Problem (missing bootstrap.js) http://jsfiddle.net/1aeur58f/676/
Problem resolved (by adding bootstrap.js) http://jsfiddle.net/1aeur58f/677/
Hope this will help you.
Related
This is sort of an add-on to my previous question:
Modal Pop-Up Not Closing Properly After Form Submission
I'm trying to reuse the modal pop-up functionality for another pop-up on the same page. This time I am using it to upload a file. This is the javascript in question:
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
})
I inadvertently misspelled "relative" on the submit button of this form:
#model Models.AttachmentModel
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success realative" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
With the word "relative" misspelled, the file information is being sent to the action in the controller(see below). My guess is the Javscript isn't catching the click action ($('body').on('click', '.relative', function (e)). When I spell "relative" correctly the file information is NULL:
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{ //do something
}
What needs to change with the Javascript (or my form/controller) to get the file information? In both cases the collection information is being passed. Is there a way to get the file information added to the collection?
--------- More Info based on #Rena answer
Let me expand some more on the original code and how this works. I have a page that has a modal section that will be populated with different partial views depending upon what I want displayed in the modal. On the Main page it has the following Javascript section:
<script>
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
})
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
I took what was provided by #Rena and inserted it into this section, but found that the Modal wouldn't close (although the data from the form in the partial view was now getting passed). I tried changing the .realative to another value on both the partial view and the javascript, but it made no difference. I then tried what #mj313 suggested in the preceding posts by changing the provided script like this to redirect to /Issue/Edit but that didn't work either.:
}).done((response, textStatus, xhr) => {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
So while I can now pass data I can't close the Modal.
UPDATE
Here is a slimmed down version of the Edit page where all of this starts
#model MYAPP.ViewModels.IssueViewModel
#{
ViewData["Title"] = "Issue Detail Page";
}
<script type="text/javascript">
$(document).ready(function () {
$("#UploadSection").load("/Attachment/GetAttachments/" + #Model.IssueData.issueId);
});
$(function () {
//Some code
});
function onSelectChange(element) {
//Some code
}
</script>
<div asp-validation-summary="All" class="text-danger"></div>
<hr />
<div class="row">
<div>
<form asp-action="Edit">
<input type="hidden" asp-for="IssueData.issueId" />
#*Some Code*#
#*Placeholder for Modal Pop-up*#
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
#*This table contains the first control that generates a modal which contains the _CreateEdit.cshtml*#
<table width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<div class="form-group">
<label asp-for="IssueData.issueStatus" class="control-label">Current Issue Status</label>
-
#if (#Model.IssueData.StatusList[0].UpdatedByName != "")
{
<text>Updated by: </text> #Model.IssueData.StatusList[0].UpdatedByName <text> - </text>#Model.IssueData.StatusList[0].StatusDate.Value.ToShortDateString()
}
else
{
<text>Created by: </text> #Model.IssueData.StatusList[0].EnteredByName <text> - </text>#Model.IssueData.StatusList[0].StatusDate.Value.ToShortDateString()
}
</div>
</td>
<td style="background-color: midnightblue; padding-right:5px">
#if (#Model.IssueData.StatusList[0].StatusDate != DateTime.Today)
{
Add New Status
}
else
{
<a href="#Url.Action("CreateEdit", new { controller = "Issue", issueid = Model.IssueData.issueId, addedit = "edit" })"
class="modal-link btn btn-success">Edit Current Status</a>
}
</td>
</tr>
</table>
<br />
#*This table contains the second control that generates a modal which contains the _UploadFile.cshtml*#
<table id="upload" width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<label class="control-label">Upload Attachments</label>
</td>
<td style="background-color: midnightblue; padding-right:5px">
<a href="#Url.Action("FileUpload", new { controller = "Attachment", issueid = Model.IssueData.issueId })"
class="modal-link btn btn-success">Upload Files</a>
</td>
</tr>
</table>
#*This section contains a partial view _DisplayFiles.cshtml. The _DisplayFiles.cshtml has controls that generate 2 more modals. The modals contain either the
_DeleteFile.cshtml or _EditFile.cshtml partial views*#
<div id="UploadSection"></div>
#{
await Html.RenderPartialAsync("_DisplayFiles");
}
<div class="form-group">
<input type="submit" value="Save Changes" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
//Using this to scroll the page on the close of the modal/page refresh
$(document).ready(function () {
var JumpTo = '#ViewBag.JumpToDivId';
if (JumpTo != "") {
$(this).scrollTop($('#' + JumpTo).position().top);
}
});
//Using this to Capture the click that opens the modals
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
//Using this to Capture the click that Submits the _EditFile,_DeleteFile,_CreateEdit forms on the modal
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
var issueid = "";
issueid = $('body').find('[name="issueidSaved"]').val();
var jumpto = $('body').find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
if (issueid == "")
{
window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto=" + jumpto;
}
}
});
})
//Using this to Capture the click that Submits the _UploadFile form on the modal
$(function () {
$('body').on('click', '.fileupload', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
var isValid = $(response).find('[name="IsValid"]').val() == 'True';
var issueid = $(response).find('[name="issueidSaved"]').val();
var jumpto = $(response).find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit/?id=" + issueid + "&jumpto="+jumpto;
}
});
})
});
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
}
Here is the code for _UpdateFile.cshtml
#model MYAPP.Models.AttachmentModel
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<input name="issueidSaved" type="hidden" value="#ViewBag.ID" />
<input name="jumpto" type="hidden" value="#ViewBag.JumpToDivId" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success fileupload" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
<!--Modal Body End-->
Here is the code for the file Upload
[HttpPost]
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{
if (file == null)
{
ModelState.AddModelError("aFileData", "Please select a file.");
}
if (collection["aIssueAttachmentDescription"] == "")
{
ModelState.AddModelError("aIssueAttachmentDescription", "Please provide a description for the file.");
}
if (!ModelState.IsValid)
{
return PartialView("_UploadFile");
}
var formFileContent =
await FileHelpers.ProcessFormFile<BufferedSingleFileUploadDb>(
file, ModelState, _permittedExtensions,
_fileSizeLimit);
var thefile = new AttachmentModel
{
aFileData = formFileContent,
aFileName = file.FileName,
aIssueAttachmentDescription = collection["aIssueAttachmentDescription"],
aFileSize = file.Length,
aFileType=file.ContentType,
issueId = collection["issueId"]
};
string result = _adoSqlService.InsertFile(thefile);
ViewBag.ID = collection["issueId"];
ViewBag.JumpToDivId = "upload";
return PartialView("_UploadFile");
}
You can see in the code above that I add in model errors if the file is not selected or the description is not filled in. These are not being shown.
I can live with the collection returning the entire Edit forms data, but ideally it should only return the fields on the _UploadFile.cshtml form (aIssueAttachmentDescription, issueId)
Anything you can provide that fixes the display of the model errors as well as a way to simplify my code would be greatly appreciated.
With the word "relative" misspelled, the file information is being sent to the action in the controller(see below). My guess is the Javscript isn't catching the click action ($('body').on('click', '.relative', function (e)). When I spell "relative" correctly the file information is NULL
The <input type="submit"> defines a submit button which submits all form values to a form-handler.So although you misspelled the word,it also could submit to the action successfully by default.
For how to use ajax to pass form data with file,you could follow:
#model Mvc3_0.Controllers.HomeController.AttachmentModel
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<!--Modal Body Start-->
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Attachment">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success realative" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$('body').on('click', '.realative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
}).done((response, textStatus, xhr) => {
$("#exampleModal").modal('hide'); //update here...
});
})
});
</script>
}
Update1:
.done((response, textStatus, xhr) => {
$("#exampleModal").modal('hide'); //update here...
});
Update2:
By using your code,I find that you add the modal html in a form which is in the main page.This will cause the form in modal which is in _UploadFile.cshtml could not generate well in my project.Here is the whole working demo:
Main Page:
#model AttachmentModel
<div class="row">
<div>
//change here.....
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
<form asp-action="Edit">
<br />
#*This table contains the second control that generates a modal which contains the _UploadFile.cshtml*#
<table id="upload" width="100%">
<tr>
<td width="90%" style="padding:5px 5px 0px 5px;background-color:midnightblue;color:white">
<label class="control-label">Upload Attachments</label>
</td>
<td style="background-color: midnightblue; padding-right:5px">
<a href="#Url.Action("FileUpload", new { controller = "Attachment", issueid = "1" })"
class="modal-link btn btn-success">Upload Files</a>
</td>
</tr>
</table>
<div class="form-group">
<input type="submit" value="Save Changes" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Js in Main Page:
#section Scripts
{
<script type="text/javascript">
$(function () {
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.fileupload', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var fdata = new FormData();
$('input[name="file"]').each(function (a, b) {
var fileInput = $('input[name="file"]')[a];
if (fileInput.files.length > 0) {
var file = fileInput.files[0];
fdata.append("file", file);
}
});
$("form input[type='text']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$("form input[type='hidden']").each(function (x, y) {
fdata.append($(y).attr("name"), $(y).val());
});
$.ajax({
url: actionUrl,
method: "POST",
contentType: false,
processData: false,
data: fdata
})
.done((response, textStatus, xhr) => {
var isValid = $(response).find('[name="IsValid"]').val() == 'True';
var issueid = $(response).find('[name="issueidSaved"]').val();
var jumpto = $(response).find('[name="jumpto"]').val();
if (isValid) {
$('body').find('#modal-container').modal('hide');
}
});
})
})
</script>
}
_UploadFile.cshtml:
#model AttachmentModel
<div class="modal-content">
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<input name="issueidSaved" type="hidden" value="#ViewBag.ID" />
<input name="jumpto" type="hidden" value="#ViewBag.JumpToDivId" />
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" method="post" enctype="multipart/form-data" asp-controller="Home">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
<span asp-validation-for="#Model.aFileData" class="text-danger"></span>
</div>
<div>
<p>Enter a file description</p>
<input id="attachment" asp-for="#Model.aIssueAttachmentDescription" class="form-control" />
<span asp-validation-for="#Model.aIssueAttachmentDescription" class="text-danger"></span>
<input id="issueid" type="hidden" asp-for="#Model.issueId" class="form-control" value="#ViewBag.id" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
#*<button type="submit" class="btn btn-success fileuploadmodal" data-save="modal">Upload</button>*#
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success fileupload" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
Controller:
[HttpPost]
public async Task<IActionResult> FileUpload(IFormFile file, IFormCollection collection)
{
var thefile = new AttachmentModel
{
aFileData = "asdad",
aIssueAttachmentDescription = collection["aIssueAttachmentDescription"],
issueId = collection["issueId"]
};
ViewBag.ID = collection["issueId"];
ViewBag.JumpToDivId = "upload";
return PartialView("_UploadFile");
}
Result:
**Hi, a newbie here on Stack overflow. Uhm my submit button does not read the java script file i created and goes straight to the php file instead of validating the input fields first on the java script file. I'm not quite sure what's wrong i've been stuck here for hour.
I created the files separately. And i put the link to my javascript file at the end of my html file.
Here is my html code:
<!-- Add Student Modal-->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<form class="form-horizontal" id="submitUserForm" action="action/createUser.php" method="POST">
<div class="modal-header">
<div class="div-action pull pull-right" >
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div> <!-- /div-action -->
<h4 class="modal-title"> Add User</h4>
</div>
<div class="modal-body" style="max-height:650px; overflow:auto;">
<div id="add-user-messages"></div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="full_name" name="full_name" placeholder="Full Name" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="new_password" name="new_password" placeholder="Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="confirm_password" name="confirm_password" placeholder="Confirm Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<select class="form-control" name="level" id="level">
<option value="">~~Level~~</option>
<option value="Admin">Admin</option>
<option value="User">User</option>
</select>
</div>
</div> <!-- /form-group-->
</div> <!-- /modal-body -->
<div class="modal-footer">
<button type="submit" id="createUserBtn" name="createUserBtn" data-loading-text="Loading..." class="btn btn-success"><i class="fa fa-check"></i> Save</button>
<button type="reset" class="btn btn-danger" onClick="resetUserForm()"><i class="fa fa-eraser"></i> Reset Form</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
My Javascript Code:
$("#addUserModalBtn").unbind('click').bind('click', function() {
$("#submitUserForm")[0].reset();
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#submitUserForm").unbind('submit').bind('submit', function() {
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
var full_name = $("#full_name").val();
var username = $("#username").val();
var level = $("#level").val();
var new_password = $("#new_password").val();
var confirm_password = $("#confirm_password").val();
const pasteBox = document.getElementById("#confirm_password");
pasteBox.onpaste = e => {
e.preventDefault();
return false;
};
if(full_name == "") {
$("#full_name").after('<p class="text-danger">Full name field is required.</p>');
$('#full_name').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#full_name").find('.text-danger').remove();
// success out for form
$("#full_name").closest('.form-group').addClass('has-success');
} // /else
if(username == "") {
$("#username").after('<p class="text-danger">Username field is required.</p>');
$('#username').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#username").find('.text-danger').remove();
// success out for form
$("#username").closest('.form-group').addClass('has-success');
} // /else
if(level == "") {
$("#level").after('<p class="text-danger">Please select user level.</p>');
$('#level').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#level").find('.text-danger').remove();
// success out for form
$("#level").closest('.form-group').addClass('has-success');
} // /else
if(new_password == "") {
$("#new_password").after('<p class="text-danger">Password field is required.</p>');
$('#new_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#new_password").find('.text-danger').remove();
// success out for form
$("#new_password").closest('.form-group').addClass('has-success');
} // /else
if(confirm_password == "") {
$("#confirm_password").after('<p class="text-danger">Confirm password field is required.</p>');
$('#confirm_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#confirm_password").find('.text-danger').remove();
// success out for form
$("#confirm_password").closest('.form-group').addClass('has-success');
} // /else
if(full_name && level && username && new_password) {
var form = $(this);
var formData = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response) {
if(response.success == true) {
// submit loading button
$("#createUserBtn").button('reset');
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
setTimeout(function(){window.location = window.location}, 1000);
// shows a successful message after operation
$('#add-user-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
// remove the mesages
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
// reload the manage student table
manageUsersTable.ajax.reload(null, true);
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
} else if(response.success == false) {
// reload the manage member table
manageUsersTable.ajax.reload(null, true);
// reset the form text
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#add-user-messages').html('<div class="alert alert-danger">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-danger").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // if
} // /success function
}); // /ajax function
} // /if validation is ok
return false;
}); // /submit product form
}); // /add product modal btn clicked
And my PHP code:
<?php
require_once 'core.php';
$valid['success'] = array('success' => false, 'messages' => array());
if($_POST) {
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$new_password = md5($_POST['new_password']);
$confirm_password = md5($_POST['confirm_password']);
$level = $_POST['level'];
$status = "0";
if($new_password == $confirm_password) {
$sql = "INSERT INTO `users`(`full_name`, `username`, `password`, `level`, `status`) VALUES ('$full_name','$username','$new_password','$level', $status)";
if($connect->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully added user account.";
}else{
return false;
}
}else{
return false;
}
$connect->close();
echo json_encode($valid);
} // /if $_POST
?>
You can use one of two solutions here:
1 Prevent default
You can prevent the submit button from executing the default event action. Instead of doing this:
$("#submitUserForm").unbind('submit').bind('submit', function() {
Do it like this:
$('#submitUserForm').submit(function (event) {
event.preventDefault();
//the rest of the submittion logic goes here
}
2 Button without the submit type
You actually don't have to create a button with the submit type, to send your form data (as you use $.ajax anyway). You can create a simple button with onClick event just like this:
<button onclick="submitForm()"><i class="fa fa-check"></i> Save</button>
And then the whole function that is under the
$("#submitUserForm").unbind('submit').bind('submit', function() {
can be extracted to the new submitForm method
We are working on a dApp that is giving us problems. The site loads OK and the button to open the subform ("Post My Rental") works. When I fill out the subform and click the 'submit' button, nothing happens. I have confirmed that I am connected to Metamask and Ganache, but no transaction goes through. Checking inspect in Chrome, no errors there. I suspect there is something missing in this code, but I can't find it. If you could help out, we would really appreciate it. Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Rent My Place</title>
<!-- Title will appear as a tab in browser on webpage -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Application -->
<link href="css/app.css" rel="stylesheet">
<!-- stylesheet refers to the look of the page, Font, color-->
</head>
<body>
<div class="container">
<!-- container that contains title panel-->
<div class="jumbotron text-center">
<p style="font-size:80px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:10px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015" >Rent My Place</font></p>
</div>
<div class="col-md-12" id="article-list">
<div class="row">
<div class="col-lg-12">
<!--<p id="account" class="welcome pull-right"></p>
<p id="accountBalance" class="welcome pull-left"></p>-->
</div>
</div>
<div class="row panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-title">
<p style="font-size:24px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:5px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015">Renter's Tip: </font><font color = "#000000">Inspect the property before you send money.</font><br><font color = "#880015">Landlord's Tip: </font><font color = "#000000">Meet prospective tenants in person.</font></p>
<!-- Button that opens second window to a form to fill out-->
<button class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#sellArticle">Post a Rental</button>
</div>
</div>
<!-- when the event button gets click, it will show the list-->
<ul id="events" class="collapse list-group"></ul>
</div>
<div id="articlesRow" class="row">
<!-- ARTICLES with pertinent item information LOAD HERE -->
</div>
</div>
</div>
<!--Result that is displayed after input-->
<div id="articleTemplate" style="display: none;">
<div class="row-lg-12">
<div class="panel panel-default panel-article">
<div class="panel-heading">
<h3 class="panel-title"></h3>
</div>
<div class="panel-body">
<strong>Beds</strong>: <span class="beds"></span><br/>
<strong>Baths</strong>: <span class="baths"></span><br/>
<strong>Address</strong>: <span class="propaddress"></span><br/>
<strong>Rental Price</strong>: <span class="rental_price"></span><br/>
<strong>Description</strong>: <span class="article_description"></span><br/>
<strong>Property is available for showing</strong>: <span class="available"></span><br/>
<strong>Contact Email</strong>: <span class="contact_email"></span><br/>
<!--<strong>Sold by</strong>: <span class="article-seller"></span><br/>-->
</div>
<div class="panel-footer">
<button type="button" class= "btn btn-primary btn-success btn-buy" onclick="App.buyArticle(); return false;">Buy</button>
</div>
</div>
</div>
</div>
<!-- Modal form to sell an article -->
<div class="modal fade" id="sellArticle" 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">Rent Your Place</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<form>
<div class="form-group">
<!--NOTE: For radio buttons to work, 'name' field must match-->
<label for="property_type">Property Type</label>
<input type="radio" name="property" id="property_type" value="house" > House
<input type="radio" name="property" id="property_type" value="apartment" > Apartment
<input type="radio" name="property" id="property_type" value="duplex" > Duplex
</div>
<div class="form-group">
<label for="propaddress">Address</label>
<input type="text" class="form-control" id="propaddress" placeholder="Enter the address">
</div>
<div class="form-group">
<label for="beds">Beds</label>
<input type="radio" name="beds" id="beds" value="0"> Studio
<input type="radio" name="beds" id="beds" value="1"> One
<input type="radio" name="beds" id="beds" value="2"> Two
<input type="radio" name="beds" id="beds" value="3"> Three +
</div>
<div class="form-group">
<label for="baths">Baths</label>
<input type="radio" name="baths" id="baths" value="1"> One
<input type="radio" name="baths" id="baths" value="2"> Two
<input type="radio" name="baths" id="baths" value="3"> Three +
</div>
<div class="form-group">
<label for="rental_price">Rent (in USD)</label>
<input type="text" class="form-control" id="rental_price" placeholder="$" pattern="[0-9]+([\.,][0-9]+)?">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control vresize" id="article_description" placeholder="Describe your property" maxlength="255"></textarea>
</div>
<div class="form-group">
<label for="available"></label>
<input type="checkbox" name="available" value="available" id="available"> Property is available for showing
</div>
<div class="form-group">
<label for="contact_email">Contact Email</label>
<input type="text" class="form-control" id="contact_email" placeholder="Enter your contact email">
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-success" data-dismiss="modal" onclick="App.sellArticle(); return false;">Submit</button>
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="footer" class="container">
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="navbar-inner navbar-content-center text-center">
<p class="text-muted" credit>AXbean - © 2018</a></p>
</div>
</nav>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/OurRentalManualInputDataInitWeb3appMay22.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
</body>
</html>
Here is the app.js that is called:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('OurRentalTestFromClassMay24.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.OurRentalTestFromClassMay24 = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.OurRentalTestFromClassMay24.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
displayArticle: function(id, seller, beds, baths, propaddress, rental_price, description, available, contact_email){
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.beds').text(beds);
articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text(rental_price);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact_email').text(contact_email);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
var _beds = $('#beds').val();
var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact_email = $('#contact_email').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
//if((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
In my website, I am using a simple modal popup with some input controls ( name, email, button).
The purpose of modal popup is:
After filling all mandatory fields, if user press "submit" button they will get one .pdf file.
I launch the modal upon onload.
Here, I am trying to do:
Open the modal popup only once for a user, or
Don't want to show the modal popup to users who previously filled out the form already
Here is the code of my modal popup:
<script type="text/javascript">
$(document).ready(function () {
$("#eBookModal").modal('show');
});
</script>
<div class="modal fade" id="eBookModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="row">
<h4 class="modal-title text-center" style="color:#FFFFFF;">Download eBook</h4>
</div>
</div>
<div class="modal-body">
<form role="form" id="eBookform" class="contact-form"
action="file.pdf">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="FName" autocomplete="off" id="eBook_FName" placeholder="First Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="LName" autocomplete="off" id="eBook_LName" placeholder="Last Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="email" class="form-control form-text" name="email" autocomplete="off" id="eBook_email" placeholder="E-mail" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center" id="eBook_download">
<button type="submit" class="btn main-btn" style="color:#fff !important;">Download Now</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
You have to keep record of the modal displays. To store that info, you can either use a cookie or the localStorage. Based on the stored value, you can decide whether to show the modal or not.
The sample below uses the localStorage as an example:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
Available as a Codepen too.
If you would like to hide the modal just from those who already submitted the form, you should set the flag upon form submit, like so:
$('#eBookform').on('submit', function (event) {
// event.preventDefault();// depending on your use case
localStorage.setItem(key, true);
})
Note: to reset the stored value, just call localStorage.removeItem('hadModal').
If you just to show the modal one time for first time visit and previous code didn't work try this !
$(window).load(function(){
var Modal = document.getElementById('myModal');
var key = 'hadModal',
hadModal = localStorage.getItem(key);
if (!hadModal) {
Modal.style.display = "block";
localStorage.setItem(key, true);
}
});
if (document.cookie.indexOf("ModalShown=true")<0) {
jQuery(document).ready(function() {
setTimeout(function(){
$("#homepageModal").addClass("modal-show")
}, 1000);
});
var date = new Date(),
expires = 'expires=';
date.setDate(date.getDate() + 1);
expires += date.toGMTString();
document.cookie = 'ModalShown=true ;' + expires + '; path=/';
}
How do you get this script to work in Bootstrap 5 without using jQuery?
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
hi all iam using angularjs ngrepeat to bind the datas into table.i have one add new button when i click bootstrap model popup open i fill the input details click submit means data will stored correctly but table couldn't not get the new data but once i reload the page data will show
my controller code
var refresh = function () {
$http.get('/ViewFacility').success(function (response) {
$scope.ViewFacilitys = response;
};
refresh();
My add new code:
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
refresh();
});
};
Html Code
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog" ng-controller="IndexController">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title ">Role Name</h4>
</div>
<div class="modal-body">
<h4>Name</h4>
<input type="text" name="RoleName" class="form-control" ng-model="Role.RoleName">
<span class="error" ng-show="profileform.FirstName.$invalid && profileform.FirstName.$dirty">Please enter a First Name</span>
<h4>Description</h4>
<input type="text" name="Description" class="form-control" ng-model="Role.Description">
<span class="error" ng-show="profileform.LastName.$invalid && profileform.LastName.$dirty">Please enter a Last Name</span>
<h4>IsActive</h4>
<input type="checkbox" name="IsActive" class="form-control checkbox" ng-model="Role.IsActive" style="margin-left:-47%" >
<span class="error" ng-show="profileform.Email.$invalid && profileform.Email.$dirty">Please enter a Email</span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid">Submit</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Clear</button>
</div>
</div>
</div>
</div>
</form>
Just add the new item to the array.
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
$scope.ViewFacilitys.push($scope.Role);
});
};
You don't need to fetch all data each time you create a new item. Refresh must be called just one time.
For pagination you can code a simple function that send the number of page to the server:
$scope.changePage = function (page) {
$scope.get('/ViewFacility?page='+page)
.then(function (response) {
$scope.ViewFacilitys = response.data;
});
}
Try modifying your refresh function like so
var refresh = function () {
$http.get('/ViewFacility').success(function (response) { //assuming this only fetches the newly added one
$scope.ViewFacilitys.push(response);
};