In my page i have a textbox and a dropdown list, when i select my item number 10 it shows me a modal, in this modal i have a textbox and i'd like to take the information entered by the user and put it in my page texbox when i submit it in the modal.
But can't figure how to do get this information to my textbox on page.
If someone could help, would be nice :) here is my script.
$(function () {
$("#Dropdown1").change(function () {
//Recupere la value de la liste
selection = $(this).val();
//Mettre la valeur du choix de liste.
if (selection == 10) {
//Affiche le modal
$('#myModal').modal('show');
}
});
})
;
My view (some things have been deleted) :
<h4 class="mb"><i class="fa fa-angle-right"></i> Example</h4>
<div class="form-horizontal style-form">
<div class="form-group">
#Html.LabelFor(m => m.X.Y, new { #class = "col-sm-d col-sm-2 control-label" })
<div class="col-sm-2">
#Html.TextBoxFor(m => m.X.Y, new { #class = "form-control" })
</div>
<div class="col-sm-2">
#Html.EnumDropDownListFor(m => m.X.Y, new { #class = "form-control", #id = "Dropdown1" })
</div>
And i'd like to fill the #Html.textboxfor with wha's inside my modal.
I made this so :
$('#myModal').on('hidden.bs.modal', function () {
$('#X_Y').val($('#Y_X'));
})
but still getting [object Object] in my field instead of what's inside the modal.
Related
I am trying to passed the value from the MVC form to JavaScript. I am using bootstrap to hide and show field. when I remove the bootstrap hide and show functionality on the form I will get the value in the message box but when the Hide/Show is enable I cannot get the value as shown by the image below. can anyowne tell me where I am going wrong
HTML
#using (Html.BeginForm("SearchPatient","HOME", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Search Criteria", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SearchCriteria,
new List<SelectListItem> {
new SelectListItem { Value = "" , Text = "Select Search Criteria" },
new SelectListItem { Value = "1" , Text = "Patient Id" },
}, new { #class = "form-control selectchosen" })
</div>
</div>
<div class="form-group" id="PatientId" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PatientId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientId, new { htmlAttributes = new { #class = "form-control " } })
</div>
</div>
</div>
<div class="form-group" id="AllShow" style="display:none">
<div class="form-group">
<div class="col-lg-offset-2">
<input type="button" value="Search" class="btn btn-success" id="btnSubmit" onclick="Enablecontrols();" />
</div>
</div>
</div>
</div>
}
JavaScript
<script type="text/javascript">
$('#SearchCriteria').change(function () {
if ($("#SearchCriteria").val() == 1) {
$("#AllShow").show();
$("#PatientId").show();
ValidateField("PatientId", true);
}
function Enablecontrols() {
$(document).ready(function () {
var patientid = $("#PatientId").val();
if ($("#SearchCriteria").val() == 1) {
alert("I am an alert box! the patient number is" + patientid);
}
}
}
</script>
rather than use the show/hide methods of bootstrap, use toggle. It's more reliable.
If that doesn't work you can also use $('#PatientId').css('display','block');
Issue fixed by changing the ID of the Div to dPatientId
Stupid mistake
You have a button that calls to a Modal window...
Agregar Producto <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
this is the javascript that executes it
<script type="text/javascript">
$(document).ready(function () {
$('#agregarproducto').click(function (e) {
e.preventDefault();
var $link = $(this);
var title = $link.text();
$('#AgregarProducto.modal-title').html(title);
var url = $(this).attr('href');
$.get(url, function (data) {
$('#AgregarProducto .te').html(data);
$('#AgregarProducto').modal();
$('#editorfocus').focus() // set focus
});
});
});
</script>
and the partial view looks like this ...
It is looking to put the EditorFor "disabled" and the checkbox unchecked (false) when the modal is executed, and in the case that the user checks the checkbox to unblock the text box in question ... it also seeks to validate that when they press the "submit" button of the form, validate that the checkbox is marked or unmarked .... in case it is marked, a value will be verified in the ... otherwise it will send the message
"You must enter a quantity or uncheck the box"
I have the following modal view "AgregarProducto.cshtml"...
<h2>Agregar Producto</h2>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="form-group">
<div class="col-md-10">
<label>Agregar Cantidad</label>
<input type="checkbox" name="checkcantidad" id="idcheckcantidad" value="false" />
#Html.EditorFor(model => model.d_Cantidad, new { htmlAttributes = new { #class = "form-control", id = "editorprecio" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Kn_CodigoProducto, "Producto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Kn_CodigoProducto, new { htmlAttributes = new { #class = "form-control", #autofocus = "true" , id = "editorfocus" } })
<div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn btn-success" id="mybtn" type="submit">
Agregar Producto
<i class="glyphicon glyphicon-ok"></i>
</button>
</div>
</div>
</div>
}
</body>
</html>
and I have the following script in the main view...
<script type="text/javascript">
$(function () {
var st = $("#idcheckcantidad").attr('checked');
$("#idcheckproveedor").change(function () {
st = this.checked;
if (st) {
$("#txtSearch").prop("disabled", false);
}
else {
$("#txtSearch").prop("disabled", true);
}
});
$("#mybtn").click(function () {
if (st && ($("#txtSearch").val() == "" || $("#txtSearch").val() == null)) {
alert("Debe Ingresar una cantidad o desmarcar la casilla");
return false;
}
});
});
</script>
My code does not do anything ... when opening the modal, only the focus defined in the button that opens the modal is executed, but I am not able to block the EditorFor from the modal view and obviously my validation does not work, I am setting the code correctly? , what's going on? any help for me?
PS: when changing the script to my modal window "AddProduct.cshtml" nothing happens either
you can use begin form and keep your form content in it and on submit call the javascript function to validate it. if validation is successfull then return true from that method otherwise prevent form submit
#using (Html.BeginForm("method", "controller", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))
{
// HTML form COntent goes here
}
javascript code for validation
<script>
function validateForm(event)
{
//default is validation fail
var isValid = false;
// validation rules goes here - update isValid value to true if pass else fail
// your code here
// check whether form valid
if(!isValid) {
//if validation fails then prevent submit
event.preventDefault();
}
return isValid;
}
Well, im trying to do something with javascript and the button is not firing the event, first i tryed to knew how to prevent to posting back, then i used something like this:
<div class="form-group">
#Html.LabelFor(model => model.Requerimentos, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.TextBoxFor(model => model.Requerimentos,new { id = "Requerimento", #class = "form-control" })
<input type="button" onclick="acrescenteLista();return false;" value="Adicionar" id="Adicionar" />
#Html.ValidationMessageFor(model => model.Requerimentos, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<ul id="Requerimentos">
</ul>
</div>
</div>
the button should call the acrescentaLista() function that is in my script that is called correctly.
Here is my script
function acrescenteLista() {
var texto1 = document.getElementById("Requerimento").value;
var texto = document.getElementById("Requerimentos");
console.log(texto);
console.log(texto2);
}
how can i solve this??
You script works properly here is the fiddle https://jsfiddle.net/ogtnfk75/4/
function acrescenteLista() {
var texto1 = document.getElementById("Requerimento").value;
var texto = document.getElementById("Requerimentos");
console.log(texto1);
console.log(texto);
}
Console.log(texto2) ? you dont have that variable in your script
I want to disable or hide a PartialView based on values inside two different ILists. Both of these lists are stored in two Session variables, _UserRoleList and _PartialRoleList.
The list contents of _UserRoleList are of type User which contains the following properties:
UserName
RoleID
RoleDescription
SID
The list contents of _PartialRoleList are of type PartialRole which contains the following properties:
PartialName
RoleID
AccessLevelID
AccessLevelDescription
Case 1 - Disable all input controls inside the Partial View:
Disable ALL input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") if a RoleID of 3 is found in both session lists.
Case 2 - Set all input controls to read-only inside the Partial View:
All input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") should have their read-only attribute set to true if aRoleID of 2 is found in both session lists.
Question:
Would it be better to retrieve the two lists and then use a jQuery .each to loop through and search for equality on the RoleID fields? Would another option be to use Razor? If pseudo code could be provided, that would be a great help.
Controller snippet:
public ViewResult Index() /* Master View, starting point of application */
{
int userID;
IList<User> userRoleList;
IList<PartialRole> partialRoleList;
WindowsIdentity identity = null;
identity = WindowsIdentity.GetCurrent();
userRoleList = _homeService.GetUserDetails(identity.User.ToString());
userID = userRoleList.First().ID;
partialRoleList = _homeService.GetPartialDetails(userID);
if (Session["_UserRoleList"] == null)
{
HttpContext.Session.Contents.Add("_UserRoleList", userRoleList);
}
if (Session["_PartialRoleList"] == null)
{
HttpContext.Session.Contents.Add("_PartialRoleList", partialRoleList);
}
return View();
}
Original View - ClientDetails.cshtml:
#using InvoiceManagement.Models
#model InvoiceClient
#{
InvoiceCreditNoteViewModel viewModel = new InvoiceCreditNoteViewModel();
viewModel.Client = Model;
ViewBag.Title = "Client Details";
List<User> userRoleList = Session["_UserRoleList"] != null ? (List<User>)Session["_UserRoleList"] : null;
List<PartialRole> partialRoleList = Session["_PartialRoleList"] != null ? (List<PartialRole>)Session["_PartialRoleList"] : null;
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$('input[type=radio][name=optionInvoiceCreditNote]').change(function () {
if (this.value == 'invoice') {
$("#InvoiceGrid").show();
$("#CreditNoteGrid").hide();
}
else if (this.value == 'creditNote') {
$("#InvoiceGrid").hide();
$("#CreditNoteGrid").show();
}
});
$('#showActive').click(function (e) {
if($(this).prop('checked') === true){
var url = '#Url.Action("FilterActiveOnlyAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
else {
var url = '#Url.Action("FilterAllAgreements")';
$.get(url, { invoiceClientID: '#Model.ID' }, function (result) {
$('#agreementGrid').html(result);
});
}
});
});
</script>
}
#Html.Partial("ClientDetailsFormPartial", viewModel.Client)
#if (viewModel.Client.ID > 0)
{
#Html.Partial("ClientDetailsAgreementPartial")
#Html.Partial("InvoiceCreditNoteContainerPartial", viewModel)
}
Partial View - ClientDetailsFormPartial:
#using InvoiceManagement.Models
#model InvoiceClient
#using (#Html.BeginForm("ClientDetails", "Client", FormMethod.Post, new { #id = "frmClientDetails" }))
{
<div class="container-fluid">
<div class="row">
<div class="col-xs-2">
<h2>Client Details</h2>
</div>
<div class="col-xs-2" style="min-height: 70px;">
Search New Client
</div>
<div class="form-group col-xs-2" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="client-ID">Client ID</span>
#Html.TextBox("ID", Model.ID, new { #class = "form-control", #readonly = "readonly" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.ID, String.Empty, new { #class = "help-block" })
</div>
</div>
<div class="form-group col-xs-3" style="min-height: 70px;">
<div class="input-group" style="top: 21px">
<span class="input-group-addon" id="accounting-ID">Accounting ID</span>
#if (Model.AID == null && Model.ID == 0)
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control" }) }
else
{
#Html.TextBoxFor(m => m.AID, new { #class = "form-control", #readonly = "readonly" }) }
</div>
</div>
<div style="padding-top: 22px;">
<div class="has-error">
#Html.ValidationMessageFor(m => m.AID, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-7">
<div class="input-group">
<span class="input-group-addon" id="client-name">Client Name</span>
#Html.TextBoxFor(m => m.InvoiceClientName, new { #class = "form-control", #name = "InvoiceClientName" })
</div>
<div class="has-error">
#Html.ValidationMessageFor(m => m.InvoiceClientName, String.Empty, new { #class = "help-block" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-1">Default Tax Code 1</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID1, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode1, new { #class = "form-control", #id = "default-tax-code1-ID", #name = "defaultTaxCodeID1" })
</div>
</div>
<div class="form-group col-xs-3 col-xs-offset-1">
<div class="input-group">
<span class="input-group-addon" id="default-tax-code-2">Default Tax Code 2</span>
#Html.DropDownListFor(m => m.DefaultTaxCodeID2, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode2, new { #class = "form-control", #id = "default-tax-code2-ID", #name = "defaultTaxCodeID2" })
</div>
</div>
</div>
<div class="row">
<div class="form-group col-xs-3">
<div class="input-group">
<span class="input-group-addon" id="status">Status</span>
#Html.DropDownListFor(m => m.StatusID, (IEnumerable<SelectListItem>)ViewBag.PopulateStatus, new { #class = "form-control", #id = "status-ID", #name = "statusID" })
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-7">
#if (Model == null || Model.ID == 0)
{
<button type="submit" class="btn btn-default">Add New Client</button>
}
else
{
<button type="submit" class="btn btn-default">Update Existing Client</button>
}
</div>
</div>
</div>
}
Since disabled controls will not post back, its pointless to generate all that extra html, and since readonly controls cannot be edited, again it seems pointless to generate all that extra html and then send it all back unchanged to the server when you submit your form.
A better approach, performance wise would be to have 2 partial views (say) _ClientDetails.cshtml and _ReadOnlyClientDetails.cshtml. The first would contain your form and its editable controls and submit button, and the second would contain only the text values of your properties, for example
#Html.DisplayNameFor(m => m.InvoiceClientName)
#Html.DisplayFor(m => m.InvoiceClientName)
Then in your controller method that generates you main view, set a view model property (or ViewBag property) to indicate which partial to display, for example
ViewBag.IsReadonly = true; // or omit depending on your logic
and in the main view
#if(ViewBag.IsReadonly)
{
#Html.Partial("_ReadOnlyClientDetails", viewModel.Client)
}
else
{
#Html.Partial("_ClientDetails", viewModel.Client)
}
Side note: Everything between you first #{ ... } except ViewBag.Title = "Client Details"; belongs in the controller method, not the view. And to do something like viewModel.Client = Model; makes no sense at all. Your view should be #model InvoiceCreditNoteViewModel and since you're not passing a model to the view, then viewModel.Client = Model; would not make sense anyway since its always null.
Its also not clear why your using Session. The code in your controller should be something like
IList<User> userRoleList = _homeService.GetUserDetails(identity.User.ToString());
int userID = userRoleList.First().ID;
IList<PartialRole> partialRoleList = _homeService.GetPartialDetails(userID)
List<int> values = new List<int>(){ 2, 3 };
if (userRoleList.Any(x => values.Contains(x.RoleID)) && partialRoleList.Any(x => values.Contains(x.RoleID)))
{
ViewBag.IsReadonly = true;
}
Good morning!
I have a checkbox in my Razor and it shows a div with a datepicker when the check box is checked.
My error is when I double click the checkbox shows the div with the datepicker when is not checked (Do the opposite of what I need).
Here is my code:
<div class="form-group">
#Html.LabelFor(model => model.SupHUBZoneCertified, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
<div class="checkbox" id="cb1">
<label>
#Html.EditorFor(model => model.SupHUBZoneCertified)
#Html.ValidationMessageFor(model => model.SupHUBZoneCertified, "HUB Zone Certified:")
</label>
</div>
</div>
</div>
<div class="form-group" id="dateCb1" style="display:none">
#Html.LabelFor(model => model.SupCategoryHUBZoneDate, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.SupCategoryHUBZoneDate, new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.SupCategoryHUBZoneDate, "", new { #class = "text-danger" })
</div>
</div>
and my javascript:
$("#cb1").click(function () {
$("#dateCb1").toggle(this.checked);
});
Assuming that you're using a jQuery UI datepicker, I can't see the toggle method in the api docs
There are only show and hide methods.
So you should modify your code:
$("#cb1").click(function () {
var action = this.checked ? "show" : "hide";
$("#dateCb1").datepicker(action);
$("#dateCb1").toggle(this.checked);
});
Thank you all I found the error, so basically I can't use the #cb1 as the checkbox ID because I need to use the ID of the input.
The ID for the input is self generated in ASP MVC and use the name declared in the MVC model.
So the code would be
$("#SupHUBZoneCertified").click(function () {
$("#dateCb1").toggle(this.checked);
});
I found the input class name using "Inspect Element in Internet Explorer"