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.
Related
I have TextBoxFor and PasswordFor in Razor, I want to check using js if both of them are filled with some data?
My code works, but only in case when there are two TextBoxes. How to make it works also for PasswordFor?
#Html.TextBoxFor(m => m.Login, new {#class = "form-control", #id="tekst1"})
#Html.PasswordFor(m => m.Password, new {#class = "form-control", #id="tekst2"})
<script type="text/javascript">
function disableButtons() {
$("input[type='submit']").attr("disabled", true);
}
function enableButtons() {
$("input[type='submit']").attr("disabled", false);
}
$(document).ready(function () {
disableButtons();
var $textInputs = $('input[type="text"],textInputs');
$('input').on('change', function () {
var anyEmpty = $textInputs.filter(function () { return this.value == ""; }).length > 0;
if (!anyEmpty) {
enableButtons();
} else {
disableButtons();
}
});
});
</script>
This Razor code:
#Html.TextBoxFor(m => m.Login, new {#class = "form-control", #id="tekst1"})
#Html.PasswordFor(m => m.Password, new {#class = "form-control", #id="tekst2"})
renders something like this to the browser:
<input type="text" class="form-control" id="tekst1">
<input type="password" class="form-control" id="tekst2">
(it likely also renders a label and possibly other attributes, but these are the important bits).
When you run the following code:
var $textInputs = $('input[type="text"],textInputs');
jQuery looks for elements like:
<input type="text" (any other attributes)>
<textInputs></textInputs>
As you can see, <input type="password" class="form-control" id="tekst2"> does not match either pattern. So, the only thing in $textInputs is:
<input type="text" class="form-control" id="tekst1">
If you've entered a value into that input, then after the filter:
$textInputs.filter(function () { return this.value == ""; }).length
will be equal to 0 and therefore anyEmpty will be false and enableButtons will be called.
If you want to find all input elements that are empty, regardless of their type attribute, change the line to:
var $textInputs = $('input');
Or, you could do all of this in a single function, like:
$(function() {
$(':input:not(:button):not(:submit)').on('change', function() {
$(':submit').prop('disabled', $(':input:not(:button):not(:submit)').filter(function(el) {
el.value === '';
}).length > 0);
});
});
Note that ':input:not(:button):not(:submit)' is a selector that will match all form elements except buttons, while ':submit' matches only submit buttons. See jQuery's documentation on form selectors.
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());
}
});
I have an EditorTemplate - which works great. Inside it, I have a dropdownlist which i decorate with a Class, and 2 divs
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
Im trying to show the 1 of the 2 divs based on the selection of the dropdown list
the dropdownlist populates fine, as is shown as a dropdown list with 2 items "Calendar" and "Email"
I have the following Javascript:
function checkSelection() {
$(".EmailDiv").hide();
$(".CalendarDiv").hide();
var selectedItem = $(this).val();
if (selectedItem == "Email") {
$(".EmailDiv").show();
} else if (selectedItem == "Calendar") {
$(".CalendarDiv").show();
}
};
var myobject = new checkSelection();
$(document).ready(function () {
checkSelection();
$(".TypeSelector").change(checkSelection);
checkSelection.apply($(".TypeSelector"));
});
The javascript file loads (I can see it in my firefox debugger)
But doesn't get hit for some reason.
Either of the divs do not show.
What am i doing wrong?
Enclose the html for each item in a container to make it easier to select relative elements
<div class="container"> // add this or similar
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
</div>
and the css
.EmailDiv, .CalendarDiv {
display:none;
}
Then the script (in the main view)
$(document).ready(function () {
// Set initial visibility
$('.TypeSelector').each(function(index, item) {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
}
});
// Update visibiity on selection
$('.TypeSelector').change(function() {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
container.find('.EmailDiv').hide();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
container.find('.CalendarDiv').hide();
} else { // this may or may not be necessary
container.find('.EmailDiv').hide();
container.find('.CalendarDiv').hide();
}
});
}
I have a Kendo AutoComplete which populated when we type something in it.Now I want to validate this AutoComplete when user dont select the Option from Populated fields.
e.g If I have a list of Countries and when i type a first 3 char then autocomplte pops up.Now User must select the any field from pop ups.I mean i want to force the user to select the Countries.My code so far goes as follows:
#(Html.Kendo().AutoComplete()
.Name("Account")
.DataTextField("AccountName")
.Filter("contains")
.MinLength(3)
.Template("#=data.AccountName#")
.Events(events => events.Select("AccountSelect").Change("ChangeEntity"))
.HtmlAttributes(new { style = "width: 240px;" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetTransaction123", "Cashbox");
})
.ServerFiltering(true);
})
)
I want to write some code on change event of this Auto Complete
function ChangeEntity(e)
{
$(document).ready(function () {
$("#transaction").validate({
success: "valid",
submitHandler: function () { alert("Submitted!") }
})
});
}
You can use the Select and Change events to test if the user has selected or typed a valid option. If text that is entered is not in the list, this will blank it out.
#(Html.Kendo().AutoComplete()
.Name("Account")
.DataTextField("AccountName")
.Filter(FilterType.Contains)
.HtmlAttributes(new { style = "width: 100%" })
.Suggest(true)
.HighlightFirst(true)
.MinLength(3)
.Events(e => e.Select("accountSelect"))
.Events(e => e.Change("accountChange"))
.DataSource(source => source
.Read(read =>
read.Action("GetTransaction123", "Cashbox")
)
.ServerFiltering(true)
)
)
<script>
var accountIsValid = false;
// This was a valid account! Set the accountIsValid flag.
function accountSelect(e) {
accountIsValid = true;
}
// Clear the account field if the choice was not valid
function accountChange(e) {
if (!accountIsValid) {
this.value('');
}
// Reset the accountIsValid flag for next run
accountIsValid = false;
}
</script>
From my understanding, you want to give validation on AutoComplete while submitting form
If this is a scenario then you may use form validation, some thing like below
<div id="yourForm">
#(Html.Kendo().AutoComplete().Name("Account")......
<span class="k-invalid-msg" data-for="Account"></span>
</div>
<script>
$("#yourForm").kendoValidator({
rules: {
customRule1: function(input) {
if (input.is("[name=Account]")) {
return input.val() === "";
}
return true;
}
},
messages: {
customRule1: "Account field is required"
}
});
</script>
I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});