Controller
[Authorize]
public ActionResult Create()
{
var LeaveType = new SelectList(new[]
{
new { ID = "0", Name = "" },
new { ID = "1", Name = "Full day leave" },
new { ID = "2", Name = "Half day AM leave" },
new { ID = "3", Name = "Half day PM leave" },
new { ID = "4", Name = "Time off" },
},
"ID", "Name", 0);
ViewData["LeaveType"] = LeaveType;
return View();
}
View
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<label class="text-center">Leave Type</label>
#Html.DropDownList("LeaveType", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>
Script
$('#LeaveType').change(function () {
var value = $(this).val();
if (value == "0") {
$('#EndDate').closest('.form-group').hide();
$('#StartDate').closest('.form-group').hide();
$('#datetimepicker6').closest('.form-group').hide();
$('#datetimepicker7').closest('.form-group').hide();
$('#leaveReason').closest('.form-group').hide();
$('#createBtn').closest('.form-group').hide();
$('#cancelBtn').closest('.form-group').hide();
}
else if (value == "1") {
$('#EndDate').closest('.form-group').show();
$('#StartDate').closest('.form-group').show();
$('#datetimepicker6').closest('.form-group').hide();
$('#datetimepicker7').closest('.form-group').hide();
$('#leaveReason').closest('.form-group').show();
$('#createBtn').closest('.form-group').show();
$('#cancelBtn').closest('.form-group').show();
#*#Html.ValueFor(CurrentApplication.)*#
}
else if (value == "2") {
$('#EndDate').closest('.form-group').hide();
$('#StartDate').closest('.form-group').show();
$('#datetimepicker6').closest('.form-group').hide();
$('#datetimepicker7').closest('.form-group').hide();
$('#leaveReason').closest('.form-group').show();
$('#createBtn').closest('.form-group').show();
$('#cancelBtn').closest('.form-group').show();
}
else if (value == "3") {
$('#EndDate').closest('.form-group').hide();
$('#startDate').closest('.form-group').show();
$('#datetimepicker6').closest('.form-group').hide();
$('#datetimepicker7').closest('.form-group').hide();
$('#leaveReason').closest('.form-group').show();
$('#createBtn').closest('.form-group').show();
$('#cancelBtn').closest('.form-group').show();
}
else {
$('#EndDate').closest('.form-group').hide();
$('#StartDate').closest('.form-group').hide();
$('#datetimepicker6').closest('.form-group').show();
$('#datetimepicker7').closest('.form-group').show();
$('#leaveReason').closest('.form-group').show();
$('#createBtn').closest('.form-group').show();
$('#cancelBtn').closest('.form-group').show();
}
});
My LeaveType is a drop down list where users can select what kind of leave they want to apply for (eg. Full day/half day/time off). When they select the value on the drop down list, i want to hide or show certain elements because some may not be required based on the type of leave.
I have a startDate and endDate textbox and for half day, i won't show the endDate textbox but i want to set the endDate to be the same as startDate if the user selects the halfday selection from the dropdownlist. I'm guessing I should have a if else loop and I know how to write the codes but I have no idea where to put it.
Also, when i display the data in a table, my drop down list values are display as the ID. How do I display the Name of the LeaveType instead? All help appreciated ^^ Thanks!
You can do it using the change event of #StartDate like following. Hope this will help you.
$('#StartDate').change(function() {
var endDate = $('#EndDate');
if ($('#LeaveType').val()==2) {
endDate.val($(this).val());
}
});
Related
I have a form with a Website text field and multiple (5-6) checkboxes. I need specific text to be populated into the Website field based on which checkbox has been selected.enter image description here
You can probably do it with an event listener, getting the name of the checkbox input and inject it into your website input.
Here is an example with just one checkbox
const mc_checkbox = document.getElementById("checkbox_mc");
mc_checkbox.addEventListener("click", function () {
if(mc_checkbox.checked){
document.getElementById("input_website").value = mc_checkbox.name;
}
else{
document.getElementById("input_website").value = '';
}
});
<div>
<label>Website</label>
<input type="text"id="input_website" />
</div>
<div>
<input type="checkbox" id="checkbox_mc" name="MC" />
<label>MC</label>
</div>
Well, my husband figured out how to accomplish this task.
Target text box is read only.
Using the 'calculate' tab, choose custom calculation script and add the following:
event.value = "";
if (this.getField("Division").value == "Yes") {
event.value = this.getField("Website").value;
event.value = "website address"}
if (this.getField("Division").value == "Choice2") {
event.value = this.getField("Website").value;event.value = "website"
}
if (this.getField("Division").value == "Choice3") {
event.value = this.getField("Website").value;event.value = "website"
}
if (this.getField("Division").value == "Choice4") {
event.value = this.getField("Website").value;event.value = "website"
}
if (this.getField("Division").value == "Choice5") {
event.value = this.getField("Website").value;event.value = "website"
}
if (this.getField("Division").value == "Choice6") {
event.value = this.getField("Website").value;event.value = "website"
}
Replace "choice" with your checkbox name and "website address" with the desired information for the text field.
Hope this is helpful for anyone else who may need this task.
I am working with datepicker jquery for 2 input "from" and "to" filter.
I want to make it required if one of the filters (from/to) has been selected. And if the user doesn't want to use the date filter, I want to remove the required attribute.
However, after I select a date in my "from" input, the action is not affected on first submit.
Somehow the "from" input didn't recognize value from datepicker on the first load.
Anyone know why it can't work on the first submit?
here is the code for jquery:
$(document).ready(function () {
if ($('#to').val().length == 0 && $('#from').val().length == 0) {
$('#from').removeAttr('required');
$('#to').removeAttr('required');
}
else if ($('#to').val().length > 0 ) {
$('#from').attr('required');
}
else if ($('#from').val().length > 0) {
$('#to').attr('required');
}
});
for the input from and to, I set it required by default.
#Html.TextBoxFor(modelitem => Model.startdate, new { #class = "datepicker form-control" ,#placeholder = "Select From Date" , #id="from" , #required = "required" })
#Html.TextBoxFor(modelitem => Model.finishdate, new { #class = "datepicker form-control", #placeholder = "Select To Date" , #id = "to" , #required = "required" })
Please let me know the problem!
try to remove it inside the document.ready function like
<script>
if ($('#to').val().length == 0 && $('#from').val().length == 0) {
$('#from').removeAttr('required');
$('#to').removeAttr('required');
}
else if ($('#to').val().length > 0 ) {
$('#from').attr('required');
}
else if ($('#from').val().length > 0) {
$('#to').attr('required');
}
</script>
or use:
Alert("this is want to know on first run")
inside your if else statement
Addition to:
Right click the page = > console menu on first run and check some errors or any jquery is running or not.
I kind of messed up the logic of my code, and I can't figure out how to fix it. I have a Bootstrap navtab panel that when the tabs are clicked, based on which tab is clicked it runs an MVC C# function in my controller. I actually need this to happen on a button click. SO the user enters a date into the datepicker, clicks submit, and then based on which tab is selected, a function will be run. How can I do this on a button click?
Here is my datepicker and button:
<div class="row spiff-datepicksection">
<div class="col-lg-6 pull-right">
<div class="col-sm-5 col-lg-offset-4">
<div class="form-group">
<div class="input-group date">
<input id="startDate" type="text" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-lg-3">
<input class="spiffdate-btn" type="submit" value="Submit" />
</div>
</div>
</div>
Here is my javascript:
<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var wrongid = $('.tab-content .active').attr('id');
$('a[data-toggle="tab"]').removeClass("active");
$(this).addClass("active");
var correctid = $(this).data("id");
alert($('.tab-content .active')[0].outerHTML);
var startDate = $('#startDate').val();
if (correctid == "delayedspiff")
$.get("#Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
else
$.get("#Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });
});
</script>
And here is my controller if it is needed:
public ActionResult DelayedSpiffDate(DateTime startDate)
{
var available = _appService.GetFeatureStatus(1, "spiffDashboard");
if (!available)
return RedirectToAction("DatabaseDown", "Error", new { area = "" });
var acctId = User.AccountID;
//startDate = DateTime.Today.AddDays(-6); // -6
var endDate = DateTime.Today.AddDays(1); // 1
Dictionary<DateTime, List<SpiffSummaryModel>> dict = new Dictionary<DateTime, List<SpiffSummaryModel>>();
try
{
var properties = new Dictionary<string, string>
{
{ "Type", "DelayedSpiff" }
};
telemetry.TrackEvent("Dashboard", properties);
dict = _reportingService.GetDailyDelayedSpiffSummaries(acctId, startDate, endDate);
}
catch (Exception e)
{
if (e.InnerException is SqlException && e.InnerException.Message.StartsWith("Timeout expired"))
{
throw new TimeoutException("Database connection timeout");
}
var error = _errorCodeMethods.GetErrorModelByTcError(PROJID.ToString("000") + PROCID.ToString("00") + "001", "Exception Getting DelayedSpiff Dashboard View", PROJID, PROCID);
error.ErrorTrace = e.ToString();
_errorLogMethods.LogError(error);
return RedirectToAction("index", "error", new { error = error.MaskMessage });
}
var spiffDateModels = new List<DelayedSpiffDateModel>();
foreach (var entry in dict)
{
var spiffDateModel = new DelayedSpiffDateModel();
spiffDateModel.Date = entry.Key;
spiffDateModel.Carriers = new List<DelayedSpiffCarrierModel>();
foreach (var item in entry.Value)
{
var spiffCarrierModel = new DelayedSpiffCarrierModel();
spiffCarrierModel.Carrier = item.CarrierName;
spiffCarrierModel.CarrierId = item.CarrierId;
spiffCarrierModel.ApprovedSpiffTotal = item.ApprovedSpiffTotal;
spiffCarrierModel.EligibleActivationCount = item.EligibleActivationCount;
spiffCarrierModel.IneligibleActivationCount = item.IneligibleActivationCount;
spiffCarrierModel.PotentialSpiffTotal = item.PotentialSpiffTotal;
spiffCarrierModel.SubmittedActivationCount = item.SubmittedActivationCount;
spiffCarrierModel.UnpaidSpiffTotal = item.UnpaidSpiffTotal;
spiffDateModel.Carriers.Add(spiffCarrierModel);
}
spiffDateModels.Add(spiffDateModel);
}
spiffDateModels = spiffDateModels.OrderByDescending(x => x.Date).ToList();
return PartialView(spiffDateModels);
}
Any ideas on how to make this happen on a button click?
You can try to create a handler of the 'click' event, which should retrieve a valid identifier of the selected tab and send a GET request to the server.
$(".spiffdate-btn").click(function(){
var correctid = $(".tab-content .active").attr("id");
var startDate = $("#startDate").val();
if (correctid == "delayedspiff")
$.get("#Url.Action("DelayedSpiffDate", "Dashboard")", { startDate: startDate });
else
$.get("#Url.Action("InstantSpiffDate", "Dashboard")", { startDate: startDate });
});
I realize this is an old question, but I am struggling with a similar issue so I am looking at old questions.
I think I see your problem though:
<script>
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
Your script calls "on shown".
If you do not want it running when it is shown, change it to "on click".
How? I can't help you with that yet. My javascript isn't that good.
I need to be able to require certain fields if someone selects a value of "Yes" from a dropdown. I've used the following code but it doesn't seem to work.
$(function () {
$('#anyAdditionalInc').keyup(function () {
if ($(this).val() == "No") {
$('#additionalIncomeSource').removeAttr('required');
$('#additionalIncomeAmt').removeAttr('required');
} else {
$('#additionalIncomeSource').attr('required', 'required');
$('#additionalIncomeAmt').attr('required', 'required');
}
});
});
My dropdown looks like this
<div class="form-group">#Html.LabelFor(m => m.anyAdditionalInc, new { #class = "col-sm-2 control-label" })
<div class="col-sm-10">
<div class="col-sm-4">#Html.DropDownListFor(m => m.anyAdditionalInc, new SelectList(new List
<Object>{ new { value = "", text = "----"}, new { value = "Yes", text = "Yes"}, new { value = "No", text = "No"}, }, "value", "text"), new { #class = "form-control", id = "anyAdditionalInc" }) #Html.ValidationMessageFor(m => m.anyAdditionalInc)</div>
</div>
</div>
Any help is appreciated. It doesnt seem to want to require the validation on the source and amt fields when selecting yes.
A dropdown (I guess you mean a <select> element by that) doesn't have much keyup events. Try change instead:
$(function () {
$('#anyAdditionalInc').change(function () {
var active = $(this).val() != "No"),
fields = $('#additionalIncomeSource, #additionalIncomeAmt');
fields.prop('required', active);
if (!active) fields.val("");
});
});
Even though #Bergi answered the question from a client-side perspective, since you tagged the question asp.net-mvc-4 I presume you may wish to know how it's done on the server side (where it really matters!):
You can simply check it in your controller:
public ActionResult Foo(SomeModel someModel) {
if (someModel.anyAdditionalInc != "Yes") {
ModelState.AddModelError("", "You must select yes");
}
}
Or if you want to push the logic into your model itself:
public class SomeModel: IValidatableObject {
public string anyAdditionalInc {get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (this.anyAdditionalInc != "Yes") {
yield return new ValidationResult("You must select yes");
}
}
}
Notice how the model:
Implements IValidateableObject
Has a method named Validate which returns the type IEnumerable<ValidationResult>
During the model binding process this method will automatically be called and if a validation result is returned your ModelState will no longer be valid. So using this familiar code in your controller will make sure you don't take any action unless your custom conditions check out:
public class SomeController {
public ActionResult SomeAction() {
if (ModelState.IsValid) {
//Do your stuff!
}
}
}
I am looking to force a submit once a user selects a value for DropDownList as long as it is not 'Custom'. If it is 'Custom' I don't want the form submitted. Instead I would like to have the startingDate and endingDate to show. However, I don't want the startingDate or endingDate to show unless Custom was selected. I am thinking this has to be done with jQuery or JavaScript. Can anybody tell me how to achieve this?
Here is the code I have in the controller to pass the starting date, ending date and list for the drop down to the view:
List<SelectListItem> rangeList = new List<SelectListItem>();
rangeList.Add(new SelectListItem { Text = "Today", Value = "Today" });
rangeList.Add(new SelectListItem { Text = "Yesterday", Value = "Yesterday" });
rangeList.Add(new SelectListItem { Text = "Past 7 Days", Value = "Past 7 Days" });
rangeList.Add(new SelectListItem { Text = "Past 30 Days", Value = "Past 30 Days" });
rangeList.Add(new SelectListItem { Text = "Last Month", Value = "Last Month" });
rangeList.Add(new SelectListItem { Text = "Custom", Value = "Custom" });
ViewBag.rangeList = rangeList;
ViewBag.startingDate = startingDate;
ViewBag.endingDate = endingDate;
ViewBag.specifiedRange = specifiedRange;
EDIT
I modified my code to show an attempt at adding the script. Below is the code I have in the view now. It is not doing anything.
<script type="text/javascript">
$("#range").change(function ()
{
if ($(this).val() == "Custom")
{
$("p.down").toggle();
}
else
{
$("form").submit();
}
});
</script>
#using (Html.BeginForm())
{
<p>
#Html.DropDownList("specifiedRange", new SelectList(
ViewBag.rangeList as System.Collections.IEnumerable,
"Text",
"Value",
new { #Id = "range" }))
</p>
<p class = "down">
Starting Date: #(Html.Telerik().DateTimePicker().Name("startingDate"))
Ending Date: #(Html.Telerik().DateTimePicker().Name("endingDate"))
<input type="submit" value="GO" />
</p>
}
Yes it needs to be done with jquery.Something like this:
$(document).ready(function(){
$("#idofyourdropdown").change(function(){
if($(this).val() == "Custom")
{
$("p.down").toggle();
}
else{
$("form").submit();
}
});
});
And class "down" to your <p> that you want to show.
Is this what you are looking for?
$('#specifiedRange').change(function() {
if($(this).val() !== 'Custom') $(this).closest('form').submit();
})