Razor Communicate Display of Modal from PageModel's OnPost() Method - javascript

I want to communicate from my Razor PageModel's OnPost() method to display the modal upon validation errors for it. Which basically means changing the modal's css from display none to block. Is there a way for this to be done?
Currently on return Page() the modal is hidden because thats what its css is initially set to, and is normally displayed on the user clicking the button to show it. I marked in my PageModel code where Id like the communication to occur
#page
#{
ViewData["Folder"] = "CourtUser";
<form asp-action="AddorEditUsersOnHearing" method="post" name="AddorEditUsersOnHearingForm" id="AddorEditUsersOnHearing">
<div class="container">
<div class="row">
<div class="col-md-8 mb-4">
<p>Add/Edit Users on <b style="font-style:italic">#Model.HearingName </b></p>
<div class="modal" tabindex="-1" role="dialog" id="AddUserForm">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add User</h5>
<button type="button" onclick="closeAddUserForm()" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="form-group" style="margin-top:5px;padding-left:45px">
<label asp-for="AddUserInput" style="width:100px"></label>
<input asp-for="AddUserInput" class="form-control col-4" id="EmailInputBox" style="display:inline-block" onchange="ValidateEmail()" />
<span style="display:block" asp-validation-for="AddUserInput" class="text-danger"></span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" style="margin:0 auto" asp-page-handler="AddUser" name="AddUserSubmit" value="Yes">Submit</button>
</div>
</div>
</div>
</div>
<input asp-for="HearingId" type="hidden" />
<input asp-for="HearingName" type="hidden" />
<button type="button" class="btn btn-primary" onclick="ShowAddUserForm()">Add User</button>
<button style="float:right" class="btn btn-primary">Remove User(s)</button>
</div>
</div>
</div>
</form>
}
<script type="text/javascript">
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}

You can try to use TempData.Here is a demo:
js:
#section Scripts
{
<script type="text/javascript">
$(function () {
if ("#TempData["Modal"]" == "Display")
{
ShowAddUserForm();
}
});
function ShowAddUserForm() {
document.getElementById("AddUserForm").style.display = "block";
}
function closeAddUserForm() {
document.getElementById("AddUserForm").style.display = "none";
}
</script>
}
handler:
public IActionResult OnPostAddUser()
{
if (ModelState.IsValid)
{
if (AddUserInput == null)
{
ModelState.AddModelError("AddUserInput", "Please enter an email");
UsersonHearingList = HttpContext.Session.GetObjectFromJson<List<UsersModel>>("UsersonHearingList");
//*****This is where I want to communicate to the view to display the modal.*******
TempData["Modal"] = "Display";
return Page();
}
}
else
{
return RedirectToPage("/Shared/Error");
}
}
result:

Related

MVC can't reach inside a tempdata condition

I'm trying to show user a notification with TempData but my code can't reach the script part. Any idea how can I fix this ? In debug I can see that TempData is not null.
<body>
#if (TempData["error"] != null)
{
<div class="modal fade" tabindex="-1" id="modal3"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
#TempData["error"]
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Sign</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</div>
</div>
</div>
}
#if (TempData["error"] != null)
{
//This is the problem. In temporary breakpoint , it skips this part.
#section Scripts{
<script type="text/javascript">
const modal = document.getElementById("modal3")
$(window).on('load', function () {
modal.style.display = "block";
});
function closeModal() {
modal.style.display = "none";
}
</script>
}
}
</body>
I'm trying to show user a notification with TempData but my code can't
reach the script part. Any idea how can I fix this ?
I have checked your shared code snippet and investigated that which seems alright and working as expected. I have set the console and alert both executed as expected. Finally, I tried to bind the '#TempData["error"]' within the modal and got the expected output as you can see below:
Output:
HTML:
I just kept your code as it is. Therefore, just you can replace your code.
Script:
<body>
#if (TempData["error"] != null)
{
<div class="modal fade" tabindex="-1" id="modal3"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
#TempData["error"]
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Sign</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</div>
</div>
</div>
}
#if (TempData["error"] != null)
{
//This is the problem. In temporary breakpoint , it skips this part.
#section Scripts{
<script type="text/javascript">
const modal = document.getElementById("modal3")
$(window).on('load', function () {
console.log(modal);
alert("Debug");
modal.style.display = "block";
$("#modal3").find(".modal-header").html('#TempData["error"]');
$("#modal3").find(".modal-title").html(('#TempData["error"]'));
$("#modal3").modal('show');
});
function closeModal() {
modal.style.display = "none";
}
$("#btnHideModal").click(function () {
$("#modal3").modal('hide');
});
</script>
}
}
</body>
Note: I have directly bind the html('#TempData["error"]') as HTML to your modal-header class and its working. Please have a try, It should work as expected.

How can I make a completely different Modal appear in the View, depending on the response from the Controller?

I have a code on my Asp.Net Core APP which I want to handle exclusively through Modals and with responses from the Controller, which change depending on the values that are sent from the View.
Right now I have the following code, which, what it does is change the message in a div on the Modal, for the response it receives from the controller, with the button that calls said Modal.
General part of the view:
#model AP.ViewModels.UK1
<div class="container">
<div class="card level-3">
<h3>Ac</h3>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<input asp-for="UK2" class="form-control" />
<span asp-validation-for="UK2" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="UK3" class="form-control" />
<span asp-validation-for="UK3" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="UK5" class="btn btn-primary" /> |
<!-- Button to Open the Modal -->
<button id="btnOpenModal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
CALL CONTROLLER / MODAL BUTTON
</button>
</div>
</form>
</div>
</div>
</div>
</div>
Modal Code on the View:
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">CONTROLLER RESPONSE:</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" id="modalcontent">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">CANCEL</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">OK1</button>
</div>
</div>
</div>
</div>
Script which calls Modal and sent the data to the Controller:
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$("#btnOpenModal").click(function () {
var uk = {};
uk.UK2 = $("#UK2").val();
uk.UK3 = $("#UK3").val();
$.ajax({
type: "POST",
url: "/UK1/GetViewContent",
data: uk,
beforeSend: function (request) {
request.setRequestHeader(
"RequestVerificationToken",
$("[name='__RequestVerificationToken']").val());
},
success: function (data) {
$('#modalcontent').html(data);
},
error: function (response) {
$("#myModal").modal('toggle')
}
});
});
$("#myModal").on("click", ".btn-default", function () {
alert("Cancel button click");
});
$("#myModal").on("click", ".btn-danger", function () {
// code
alert("Delete button click");
$('#myModal').modal('hide')
});
});
</script>
Controller Code:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GetViewContent(UK1 uk)
{
if (uk.UK2 == uk.UK3)
{
return Ok("A-CASE 1");
}
if (uk.UK2 >= uk.UK3)
{
return Ok("B-CASE 2");
}
if (uk.UK2 <= uk.UK3)
{
return Ok("C-CASE 3");
}
if (uk.UK2 == null)
{
return Ok("D-CASE 4");
}
if (uk.UK3 == null)
{
return Ok("E-CASE 5");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(UK1 ukk)
{
return View("Home1");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateDos(UK1 ukk)
{
return View("Home2");
}
Now this is what I want to achieve with the code:
I would like my code to have 5 possible Modals, one for each possible response from the Controller, and that each one of these Modals had a different message, as well as different buttons, and my question is, how can I do it? Which are my options?
The first thing that comes to my mind is to have HTML code for 5 different Modals in view, and depending on which the Controller's response is, the code calls a different one of the Modals, the problem is that I don't know how to do that, since I don't know how to read the controller Response as a 'variable' in the script code, or how I should put "Ifs" that depend on the response there in the Script, but I understand that this should go in this part of the code:
success: function (data) {
$('#modalcontent').html(data);
},
error: function (response) {
$("#myModal").modal('toggle')
}
In any case, what I would like for my 5 Modals, is something similar to this:
1)If the answer that is received from the Controller is "A-CASE 1", the Modal should get an "A" message on the div, and just the Cancel button should appear at the botton of the Modal.
2)If the answer that is received from the Controller is "B-CASE 2", the Modal should get an "B" message on the div, and both the Ok and Cancel button should appear at the botton of the Modal, the Ok Button should call me the Controller's Create method.
3)If the answer that is received from the Controller is "C-CASE 3", the Modal should get an "C" message on the div, and both the Ok and Cancel button should appear at the botton of the Modal, the Ok Button should call me the Controller's CreateDos method.
4)If the answer that is received from the Controller is "D-CASE 4", the Modal should get an "D" message on the div, and just the Cancel button should appear at the botton of the Modal.
5)If the answer that is received from the Controller is "E-CASE 5", the Modal should get an "E" message on the div, and just the Cancel button should appear at the botton of the Modal.
Anyway, thanks for reading everything and thanks in advance, all this is simply because I try to learn how to make the Modal Script do different things, and consider different cases, depending on what is the response that is sent from the Controller, since I understand that the complexity of the problem arises that the variables of the Script environment exist at different times than the variables of the View, and I don't know to what extent it is possible to treat the 'response' sent by the controller as a Variable, but I would like to learn how to do it if possible, and I want to understand all this.
Here is a working demo:
UK1:
public class UK1
{
public string UK2 { get; set; }
public string UK3 { get; set; }
}
UK1Controller:
//UK2 and UK3 are string,so that they can be null.When comparing them,we need to change them to int
[HttpPost]
[ValidateAntiForgeryToken]
public string GetViewContent(UK1 uk)
{
if (Convert.ToInt32(uk.UK2) == Convert.ToInt32(uk.UK3))
{
return "A-CASE 1";
}
if (Convert.ToInt32(uk.UK2) >= Convert.ToInt32(uk.UK3))
{
return "B-CASE 2";
}
if (Convert.ToInt32(uk.UK2) <= Convert.ToInt32(uk.UK3))
{
return "C-CASE 3";
}
if (uk.UK2 == null)
{
return "D-CASE 4";
}
if (uk.UK3 == null)
{
return "E-CASE 5";
}
return "";
}
public IActionResult ShowUK1()
{
return View();
}
public IActionResult Create()
{
return Ok();
}
public IActionResult CreateDos()
{
return Ok();
}
ShowUK1 View(I change OK1 button to <a> tag,and add id to Ok1 and Cancel):
<div class="container">
<div class="card level-3">
<h3>Ac</h3>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<input asp-for="UK2" class="form-control" />
<span asp-validation-for="UK2" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="UK3" class="form-control" />
<span asp-validation-for="UK3" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="UK5" class="btn btn-primary" /> |
<!-- Button to Open the Modal -->
<button id="btnOpenModal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
CALL CONTROLLER / MODAL BUTTON
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">CONTROLLER RESPONSE:</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" id="modalcontent">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="cancel" type="button" class="btn btn-danger" data-dismiss="modal">CANCEL</button>
<a id="ok1" class="btn btn-primary" >OK1</a>
</div>
</div>
</div>
</div>
<script>
$(function () {
$("#btnOpenModal").click(function () {
var uk = {};
uk.UK2 = $("#UK2").val();
uk.UK3 = $("#UK3").val();
$.ajax({
type: "POST",
url: "GetViewContent",
data: uk,
beforeSend: function (request) {
request.setRequestHeader(
"RequestVerificationToken",
$("[name='__RequestVerificationToken']").val());
},
success: function (data) {
switch (data) {
case "A-CASE 1":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("A");
break;
case "B-CASE 2":
$("#ok1").removeAttr("hidden");
$("#ok1").attr("href", "Create");
$('#modalcontent').html("B");
break;
case "C-CASE 3":
$("#ok1").removeAttr("hidden");
$("#ok1").attr("href", "CreateDos");
$('#modalcontent').html("C");
break;
case "D-CASE 4":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("D");
break;
case "E-CASE 5":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("E");
break;
default:
break;
}
},
error: function (response) {
$("#myModal").modal('toggle')
}
});
});
});
</script>
result:

Call JavaScript Function Contained on _Layout.cshtml

Please help, new web developer alert!
MVC + JavaScript :)
I have a .cshtml page that has a submit button. When I press that button I want to call a JavaScript function contained on my _Layout.cshtml page.
Unfortunately I get a function not found error.
'ReferenceError: validateCheckBoxesInForm is not defined'
Here is the cshtml page...
#model FrontEnd.Web.Areas.PresentationToPolicy.ViewModels.CaseSummary.InsurersReferralViewModel
#{
ViewBag.Title = "Refer To Insurers";
}
<div>
<form asp-area="PresentationToPolicy" asp-controller="CaseSummary" asp-action="ReferToInsurers" method="POST" id="documentDownload">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</div>
Here a cut down version of my _Layout.cshtml (the script is loaded just after bootstrap etc, at the start of the body)
#inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body style="background-color: #f6f8fa">
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-ui/jquery-ui.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/dist/manifest.js"></script>
<script src="~/js/dist/vendor.js"></script>
<script src="~/js/dist/scripts.js" asp-append-version="true"></script>
</environment>
<div class="container body-content">
#RenderBody()
<hr style="margin-bottom: 2px; padding-bottom: 2px" />
<footer>
<p style="vertical-align: baseline">© 2017 - ABACUS Portfolio Portal</p>
</footer>
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
Oh and the script that contains the function!
function validateCheckBoxesInForm(event, formId, title, message) {
let validated = false;
let form = $(`#${formId}`);
let elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>')
.appendTo('body')
.html(
`<div id="validateModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content" style="border-color: #f00">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">
${title}
</h3>
</div>
<div class="modal-body">
<h4>${message}</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>
</div>
</div>
</div>
</div>`
);
$('#validateModal').modal('show');
}
}
And finally a cut down version of 'View Source'
<body style="background-color: #f6f8fa">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/dist/manifest.js"></script>
<script src="/js/dist/vendor.js"></script>
<script src="/js/dist/scripts.js?v=iHOVZCmLJ7F7ev0DnwzRmkZgp-zu74ZoPGBIra9EaIk"></script>
<div class="container body-content">
<form method="POST" id="documentDownload" action="/PresentationToPolicy/CaseSummary/ReferToInsurers/43cffe87-2d8f-43eb-8ad2-e0b046fc8d20">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
If I press view source and click on the script link I get this...
webpackJsonp([19],{
/***/ 749:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(750);
/***/ }),
/***/ 750:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//Global Functions that will be run of every page
//Called via _Layout.cshtml
function validateCheckBoxesInForm(event, formId, title, message) {
var validated = false;
var form = $('#' + formId);
var elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>').appendTo('body').html('<div id="validateModal" class="modal fade">\n <div class="modal-dialog">\n <div class="modal-content" style="border-color: #f00">\n <div class="modal-header">\n <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\n <h3 class="modal-title">\n ' + title + '\n </h3>\n </div>\n <div class="modal-body">\n <h4>' + message + '</h4>\n </div>\n <div class="modal-footer">\n <button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>\n </div>\n </div>\n </div>\n </div>');
$('#validateModal').modal('show');
}
}....
So I guess my question is how to I call the function contained on the _Layout page from the child cshtml page?
I guess I could use a script section on the page, but this function is shared by multiple places. So I kinda need a central location to keep the code dry.

Linking a modal to an entry field and validating using JavaScript

With the following code I'm trying to validate an entry field in JavaScript. The validation requires only 10 characters. When you authenticate, it is supposed to display a modal with a confirmation message:
function myFunction() {
var con_code, text;
//getting the field
con_code = document.getElementById("con_code").value;
if ($.trim($('con_code').val()).length == 0) {
text = "Authentication code is not valid";
}
//trigger to the modal if it meets the condition
$(document).ready(function() {
$("#con_code").click(function() {
$("#myModal").modal();
});
});
document.getElementById("error_con_code").innerHTML = text;
}
<div class="container">
<h2>Activate Modal with JavaScript</h2>
<!-- Trigger the modal with a button -->
<div class="form-group">
<label>Confirmation Code.</label>
<input type="text" name="con_code" id="con_code" class="form-control" required="required" placeholder="Enter your Confirmation Code" />
<br> //the error code display
<span id="error_con_code" class="text-danger"></span>
<br> //the authenticate button
<button type="button" class="btn btn-success btn-sm" id="con_code" onclick="myFunction()">Authenticate</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button> //the modal
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
However, it is not authenticating the confirm code. How can I fix it?
You have an error at:
if($.trim($('con_code').val()).length ==0){...}.
It should be $('#con_code')
Also you have 2 elements with the same id="con_code".
Please check with the following codes.
I am assuming you want to show the modal when there is 10 chars in the input field. If the rule changes, then please edit at: 'if ($.trim(con_code.val()).length != 10) {}' in the below codes.
$(document).ready(function() {
myFunction();
});
function myFunction() {
$("#con_code_btn").click(function() {
var con_code = $('#con_code');
var error_con_code = $('#error_con_code');
error_con_code.html('');// Remove Previous Error Message(if any);
if ($.trim(con_code.val()).length != 10) {
error_con_code.html("entication code is not valid");
}
else {
$("#myModal").modal();
}
});
}
Also please change the id of the button to "con_code_btn" in the form:
<button type="button" class="btn btn-success btn-sm" id="con_code_btn" onclick="myFunction()">Authenticate</button>

Focus on a textarea after custom text on a bootstrap floating modal form

I am using bootstrap to invoke a simple modal form which contains only a textarea field and couple of buttons. I am setting some custom text (variable length) in the textarea while invoking the modal form. What I want is to focus on the textarea field after the custom text so the user can start typing after that. I have mentioned my implemenation of this below. Can anyone tell how to achieve this?
Here is the Fiddle: http://jsfiddle.net/jLymtdg8/
A bit explanation here as well -
Here is my modal (all bootstrap stuff)-
<div class="modal fade" id="msg" 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">Type a message</h4>
</div>
<div class="modal-body">
<textarea id="Message" class="form-control"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Cancel</button>
<button id="PostModalButton" class="btn btn-primary btn-sm">Post</button>
</div>
</div>
</div>
And here is how it gets invoked -
<div class="pull-right">
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#msg" data-screenname="Type after this">
Post A Message
</button>
</div>
This is how I am prefilling the textarea and setting focus, but this is only setting cursor on first line rather than after screen_name -
$(this).on('shown.bs.modal', '#msg', setFieldAndFocus)
var setFieldAndFocus = function () {
var screen_name = $("button[data-target='#msg']").data("screenname");
$("#Message").val(screen_name + " ");
$("#Message").focus();
};
Sam you can try the following javascript code:-
var screen_name = '',
old_message = '',
new_message = '';
$("#msg").on('shown', function() {
screen_name = $("button[data-target='#msg']").data("screenname"),
old_message = $.trim($('#Message').val()),
new_message = ( old_message.length == 0 ) ? screen_name : old_message;
$("#Message").focus().val(new_message + " ");
});
Let me explain why i have used this code. From the js fiddle link that you have provided what i understand is you are using the bootstrap 2 version, but the code that you are using
$("#msg").on('shown.bs.modal', function(){
...
}
was introduced only in bootstrap 3. so I have changed it to
$("#msg").on('shown', function(){
...
}
and the line
$("#Message").focus().val(new_message + " ");
is used so that you can set the focus after the custom text.I hope this will resolve your issue.
You can take reference of this link : http://jsfiddle.net/3kgbG/433/
It is working for me.
$('.launchConfirm').on('click', function (e) {
$('#confirm')
.modal({ backdrop: 'static', keyboard: false })
.on('')
.one('click', '[data-value]', function (e) {
if($(this).data('value')) {
//alert('confirmed');
} else {
//alert('canceled');
}
});
});
$('#confirm').on('shown', function () {
$('#txtDemo').val($('#txtDemo').val());
$('#txtDemo').focus();
// do something…
})
body,
.modal-open .page-container,
.modal-open .page-container .navbar-fixed-top,
.modal-open .modal-container {
overflow-y: scroll;
}
#media (max-width: 979px) {
.modal-open .page-container .navbar-fixed-top{
overflow-y: visible;
}
}
<div class="page-container">
<div class="container">
<br />
<button class="btn launchConfirm">Launch Confirm</button>
</div>
</div>
<div id="confirm" class="modal hide fade">
<div class="modal-body">
Do you want to continue?
<input id="txtDemo" type="text" value="Jayesh" class="form-control"/>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-primary" data-value="1">Continue</button>
<button type="button" data-dismiss="modal" class="btn" data-value="0">Cancel</button>
</div>
</div>

Categories