Linking a modal to an entry field and validating using JavaScript - 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>

Related

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

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:

How to get the id and name of an object on button click and display them in a modal in asp.net view

I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</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">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" 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">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</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">Save</button>
</div>
</div>
</div>

auto resizing textarea in a modal

I'm creating a ASP.NET Webpage using Bootstrap and jQuery.
I have recently implemented a modal to show a log. The modal is shown when clicking a link:
<a data-toggle="modal" data-target="#logData">Open</a>
<div class="modal fade" id="logData" tabindex="-1" role="dialog" aria-labelledby="logDataLabel">
<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">Log for #Html.DisplayFor(model => model.Alias)</h4>
</div>
<div class="modal-body">
<textarea class="form-control log" rows="5" placeholder="Log is empty.">#Html.DisplayFor(model => model.Log)</textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The modal contains a textarea that doesn't autoresize.
I have found the following code:
$('textarea').each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
which should enable my textareas to autoresize and it works other places in my code, but not in this modal above. At least not when typing in the textarea, but upon opening the modal it does seem to autoresize.
Does anyone have an idea of why? And eventually on how to fix it?
Thanks!
You can use this code which will work if the textarea is not hidden (e.g in a modal that is not shown yet)
let setHeight = (input) => {
input.style.overflow = 'hidden';
input.style.height = 0;
input.style.height = `${ input.scrollHeight + 2 }px`;
};
$('textarea').on('input, keyup', function () {
setHeight(this);
})
for bootstrap modal, u can do something like this:
$('.modal').on('shown.bs.modal', function () {
$(this).find('textarea').each(function () {
setHeight(this);
});
})

How to read an array and show it in a modal: PHP & Javascript

My code only show first row in my modal. I don't know how to show in modal all rows:
PHP:
$sql2="SELECT nombre, dias, COUNT(dias) as count FROM usuarios WHERE usuarios.id = '$id_user';
if ($stmt2 = $mysqli->query($sql2)){
$array = mysqli_fetch_array($stmt2, MYSQLI_ASSOC);
echo '<a data-toggle="modal" data-target="#exampleModal" data-whatever="'.$array["nombre"].'" data-dia="'.$array["dias"].'" href="#">'.$array["count"].'</a>';
}
HTML & Javascript
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">;
<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="exampleModalLabel">New message</h4>;
</div>;
<div class="modal-body">;
<form class="form-inline">;
<div class="form-group">;
<input type="text" class="form-control" id="recipient-name">;
</div>;
<div class="pull-right">;
<button type="button" class="btn btn-danger">Eliminar</button>;
</div>;
</form>;
</div>;
<div class="modal-footer">;
<button type="button" class="btn btn-active" data-dismiss="modal">Tancar</button>;
</div>;
</div>;
</div>;
</div>;
<script type="text/javascript">
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever')
var dia = button.data('dia')
var modal = $(this)
modal.find('.modal-title').text('Dies personals: ' + recipient)
modal.find('.modal-body input').val(dia)
})
</script>
This code work, but only show in modal 1 DATE, and i want to show all DATES from a USER

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