CSHTML. Need to make sure field(s) are entered - javascript

The application is a Web MVC application in C#. When the user is editing a record and clicks on a checkbox I want to make sure 3 fields are filled in.
On the controller I have created a clientside script which is called checkfields:
checkBoxProperties.ClientSideEvents.CheckedChanged =
"function (s,e) { checkfields(); }";
On the CSHTML I have
function checkfields()
{
alert("Value Empty");
return false;
}
When I check the checkbox I am getting the alert pop up but how do I reference the model fields and popup alert if one of the fields are empty.

You can just use JQuery to select each checkbox and query if it has been checked.
How to check whether a checkbox is checked in jQuery?
$("#myCheckBox").on("click", function () {
if ($("#myCheckBox").is(':checked')) {
Now you can show a hidden message (show a hidden label, for example), do a popup, or whatever.

Related

IS Accessing DropList Value of Sitecore WFFM Control in Javascript Possible?

I am using Sitecore 7.2 with Web Forms for Marketers 2.4.
Using wffm form designer I created a form that has a droplist in it.
I want to be able to hide or unhide another field in the same form based on the selected value of the droplist. Through my research I came up with exporting the form (via form designer export) and pointing the sublayout to that exported form.
I then added and onChange event to the droplist.
<cc3:droplist runat="server" title="Country" emptychoice="True" id="field_xyz" cssclass="scfDropListBorder fieldid.%7bxyz%7d name.Country" controlname="Country" fieldid="{xyz}" enableviewstate="False" onchange="checkField()">
I then added a javascript to the bottom of the page.
function checkField() {
alert("Hello! I am an alert box!!");
var a = document.getElementById("field_xyz");
alert(a.options[a.selectedIndex].value);
var cityTextBox = document.getElementById("field_abc").parentNode.parentNode;
if (a == "United States") {
cityTextBox.style.display = "block";
} else {
cityTextBox.style.display = "none";
}
alert("Ending Script");
}
I can get the 'Hello!' alert to show every time but not the 'ending' alert and the value of 'a' is always null from what I can tell.
Is what I'm trying to do even possible in Sitecore?
I read something else that said they had a problem because of encapsulation and protection levels.
I can also confirm that when I submit the form it does show up in the WFFM reports so I know it is submitting properly.
Any help/advice/direction would be appreciated.
I've never used the export functionality so can't comment to it's effectiveness or ease of use. My suggestion would be to simply use from custom css classes and jquery on the front-end to hide/show depending on the selected value.
Create 2 new css classes under /sitecore/system/Modules/Web Forms for Marketers/Settings/Meta data/Css Classes. Call them "hide-dependent" and "dependent-field"
Add your fields and then on the country field select "hide-dependent" as the CSS class, and for the City select "dependent-field"
Add the following Javascript to your own sites js file.
The code will bind a handler to fire onchange, checked the selected value and then hide/show all field with the dependent-field class. Specifying the chained field-border ensures that we are hiding the whole row and not just the select box.
(function ($) {
var HideDependentFied = function (value) {
var condition = (value == "USA");
$(".dependent-field.field-border").toggle(condition);
};
$(document).ready(function() {
var $field = $(".hide-dependent.field-border select");
$field.on("change", function() {
HideDependentFied(this.value)
});
HideDependentFied($field.val());
});
})($scw);
The above code is using an Immediately Invoked Function Expression and passing is $scw, which is the jQuery variable used by WFFM.
You may also want to fire the function on document ready, to ensure the field is hidden on load and only shown when the appropriate value is selected.

angular forms validation issues when using plugins

I have an Single Page Application build using Angular and i am having some issues with the form.
Form is using a check box a drop down and two text boxes.
first text box (Name) has no validation.
check-Box is using a third party plugin called "iCheck".
Drop down is using a plugin called "bootstrap-select".
Validation is using a library called "Jquery Validation Engine".
The plunker is setup here
The expected behavior is. In simple words the text box and drop are required if check-box is checked.
1) On Page load because form is not dirty (none of the controls were supplied any value) if i click the save button it should hit the save function because there were no validation on the controls, hence there should be no validation message prompt on the screen.
2) If i click the check box. the drop down and the text box below becomes required. it means that both drop down and text box has conditional validation (feature of Jquery Validation Engine) which is already setup and working .
so now if i click Save, it should not hit the save function and display the validation prompt.
3) it should keep on restricting the function access and display the validation error prompt unless form controls are valid i.e. some value is selected in drop-down and text boxed is filled.
4) and if i un-check, validation described in point number 3 goes away.
But whats happening is:
a) On page load if i click the save button it does not hit the save function.
b) If i click the check box it still does not hit the save function and validation error prompts are display on both drop down and text-box which is fine thats how it should behave.
c) When is fill the required text box it makes the form ng-valid and it hit the
save function how ever the drop is still in ng-invalid.
d) Even if i select some thing from the drop down the validation prompt remains on the drop down and it still hits the save functions.
e) (Not that much worried about this issue) lastly want to setup a custom value in the drop down that should act as default e.g. "--Select One--" and if the default is selected it should be considered as nothing is selected and it should be considered as invalid when validation is active.
all of this code is in dashboard.html and dashboard.js since i am using plugins so i needed directives to work with them properly. Directives for check-box, Select and Validation are in dashboard.js under the controller code.
Controller code is setup like this.
(function () {
'use strict';
var controllerId = 'dashboard';
angular.module('app').controller(controllerId, ['$scope', dashboard]);
function dashboard($scope) {
var vm = this;
vm.title = 'Dashboard2';
vm.CurrCustomer = {};
vm.CurrCustomer.Name = ""; //first text box
vm.CurrCustomer.Logic = false;
vm.CurrCustomer.SetThreshold = false;
vm.CurrCustomer.Threshold;
vm.saveChanges = function () {
alert('function called');
var NewCustomer = vm.CurrCustomer;
// submit NewCustomer to DB.
};
$scope.toggleSelection = function () {
vm.CurrCustomer.SetThreshold = !vm.CurrCustomer.SetThreshold;
};
}})();

Hiding/showing fields conditionally w/ checkboxes

I'm using a conditional fields form from Bootstrap Validator and don't know enough Javascript to make one last thing work.
The form as it is now is live here
My problem is both "...a brochure to be sent to me" and "...to arrange a field demonstration" need to open the same address fields, however, if you check "...a brochure sent to me," then check "...to arrange a field demonstration" the fields open and then close again.
How do I create an if statement to verify if the field is already visible and leave it open if it IS, and open it is it's NOT?
It looks the bootstrapValidator.js file is addressing the checkboxes by class, both of your checkboxes have the name "topic[]" with the same value of "address". You could give each field its unique ID, add in javascript that tells the page to see if either of the checkboxes are checked, and then make the style display set to block.
Try
//HTML - Added ID's to each and the onclick='showblock()'
<input type='checkbox' value='address' name='topic[]' id='address1' onclick='showblock()'></input>
<input type='checkbox' value='address' name='topic[]' id='address2' onclick='showblock()'></input>
<div data-topic="address" style="display: block;" id="addressform">
//JS
function showblock() {
if (document.getElementById("address1").checked == true || document.getElementById("address2").checked == true) {
document.getElementById("addressform").style.display = "block";
} else {
document.getElementById("addressform").style.display = "none";
}
}
This should work, if it doesn't then the bootstrapValidator is probably overwriting it, you can just change the value of "address" to something other than address.

RequestVerificationToken value empty after hiding html element with jquery

I have a ASP.NET MVC 4 form where there are checkboxes to show and hide some HTML elements. On visiting the form page, the RequestVerificationToken value is created as a hidden field correctly. The certain HTML elements are by default hidden.
I then tick a checkbox to show some HTML elements after I untick the checkbox (which hides those HTML elements) the RequestVerificationToken value disappears.
So when I submit the form by clicking create button, the following error appears:
The required anti-forgery form field "__RequestVerificationToken" is not present
If I do not untick the checkbox back, the value for RequestVerificationToken is present and form is submitted successfully.
The HTML elements are shown hidden using jQuery/javascript.
Why is this happening? How can I solve this issue? Researching the error online only suggests adding the attributes as below.
I have already added the attributes in the Create action method, but not the GET method:
// POST: /Document/Create
[HttpPost]
[ValidateAntiForgeryToken]
...
In the Create form page I also added:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
...
Here is the Javascript to show and hide elements:
$('div.section .input_control').change(function () {
var $target = $(this).closest('div').find('.showSection');
if (this.checked) {
$target.show();
} else {
if (confirm("Are you sure you want to exclude this section?") == true) {
$target.hide();
jQuery(':hidden').val('');
} else {
$(this).prop("checked", true);
}
}
});
Use jQuery .not(). http://api.jquery.com/not-selector/ or http://api.jquery.com/not/
It will be something like this:
$(':hidden').not('__RequestVerificationToken').val('');
Doing that you will get all the hidden fields except for the antiforgery one.

I need help understanding a simple JavaScript script

if(document.frmMain.POL_NO.value == "")
{
alert("Select Policy Number");
document.frmMain.ENDT_NO.value="";
document.frmMain.POL_NO.focus();
return false;
}
Can anyone explain the above code to me? I am new to Javascript.
It appears to be a bit of validation code to make sure a user has entered a value for an item referred to as "Policy Number". It is the sort of code that gets called when submitting a form to check that the values the user has entered are valid.
In detail:
if(document.frmMain.POL_NO.value == "")
Only run this code if the item called in POL_NO the form called frmMain doesn't have a value yet.
alert("Select Policy Number");
Display a message to tell the user that they need to enter a value.
document.frmMain.ENDT_NO.value="";
Set the ENDT_NO item of frmMain to a blank value.
document.frmMain.POL_NO.focus();
Set the focus to the POL_NO item (the same as the user tabbing to it or clicking on it).
return false;
Return false to the code that called the function that this code is in. If this code is used in the event handler for the submit button on a form then returning false will stop the form from being submitted to the server until the POL_NO item has a value.
If the contents of the item POL_NO from the form frmMain is empty, then throw an alert and change the value of the ENDT_NO item value to nothing (empty) and after that focus on the element POL_NO. Return false after that (I assume this code executes at onSubmit event, so the form won't be submitted if POL_NO doesn't have a value)
Probably the logic is that the ENDT_NO can't have a value if POL_NO is empty.
Enjoy!
document.frmMain is a form in the page, and POL_NO and ENDT_NO are fields in the form, presumably listboxes.
This code is a simple validation script to make sure you filled out the form correctly.
//if POL_NO hasn't been set (no policy number selected):
if(document.frmMain.POL_NO.value == "")
{
//show a message box
alert("Select Policy Number");
//clear the value (if any) of ENDT_NO
document.frmMain.ENDT_NO.value="";
//set the form focus to POL_NO (select it, as if you had clicked on it)
document.frmMain.POL_NO.focus();
//stop the form from being submitted
return false;
}
I'm assuming this code is part of a function which is called by frmMain's onSubmit event (and event handler) -- when the function returns false the submit is cancelled. Were this not here, it would show the message box, clear ENDT_NO, select POL_NO and then submit anyways.
Note that referencing members of a form in the document.formName.fieldName.property fashion is deprecated. The correct way is to use getElementById or a similar function:
document.frmMain.ENDT_NO.value = ""; //bad
document.getElementById("ENDT_NO").value = ""; //correct
HTML document
your HTML document has this defined somewhere in its content
<form id="frmMain" ...>
<input type="..." id="POL_NO">
<input type="..." id="ENDT_NO">
</form>
SCRIPT code
So. Your script checks whether your POL_NO input field has a value.
If it doesn't (it's an empty string),
it displays an alert (information window) and
empties ENDT_NO field's value and
puts focus on the POL_NO field - so the user can immediately start selecting/typing a value in this field
returns false - probably to cancel form submission
Business logic
Based on the logic of this script, the business process obviously doesn't allow any value in ENDT_NO field, until there's a value in POL_NO.
Observation
If you need to change something about this code (if there's a bug in it), I strongly suggest you get to know Javascript/DOM/HTML before doing any changes.
Actually your code does a pretty simple validation, just read the code and find the fields POL_NO and ENDT_NO in your HTML output. Here is my comments :
// if your POL_NO field is empty,
if(document.frmMain.POL_NO.value == "")
{
// warn user that he need to select Policy number
alert("Select Policy Number");
// set ENDT_NO field's value to empty
document.frmMain.ENDT_NO.value="";
// set POL_NO active - focussed
document.frmMain.POL_NO.focus();
return false;
}
If the value of the input named POL_NO in the form frmMain is empty, then show a message "Select Policy Number", empty the input named ENDT_NO, give the focus to the input named POL_NO, and the exit the function with the return value "false".

Categories

Resources