RequestVerificationToken value empty after hiding html element with jquery - javascript

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.

Related

Sending a html form with hidden elements

Today I came across a weird behaviour. I have made an html form using Bootstrap for users to subscribe. You can subscribe multiple users at once, but to see the second and the third user's input fields, you have to toggle a select button first (https://prnt.sc/t96lxt). The issue is that I can not send the form for only 1 or 2 users, because some fields of the hidden parts are set to be required.
So, my question is, how can a send a form with hidden parts that contain required fields?
My form is to be found at http://debosvrienden.alfapre.be/nl/inschrijving
Maybe you can try something like this using javascript
const checkBox = document.querySelector("YOUR_CHECKBOX");
checkBox.addEventListener("change", (e) => {
if (e.target.checked) {
document.querySelector(".hidden-input-field-1").setAttribute("required", true);
document.querySelector(".hidden-input-field-2").setAttribute("required", true);
} else {
document.querySelector(".hidden-input-field-1").setAttribute("required", false);
document.querySelector(".hidden-input-field-2").setAttribute("required", false);
}
});
Obviously, you would have to use your own selectors.
Here, you are just getting a reference to your checkbox, and once it changes, you are changing the required attribute of the inputs.

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

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.

jQuery form validation. How to prevent error messages appearing multiple times

I'm trying to validate a form in jQuery. I have it working, with 1 issue. If i click the submit button twice, the error messages will show twice, stacked on top of eachother.
EG
Name must not be empty
Name must not be empty
//Form Validation
//Store checkbox, and checkbox label in jQuery object
$terms = $('#terms');
$termsdoc = $('#terms-doc');
//Check if pet name is empty
if($name.val() == '')
{
$name.after('<p class="error">Name must not be empty</p>')
}
if($terms.is(':not(:checked)'))
{
$termsdoc.after('<p class="error">Please agree to the terms and conditions</p>')
}
Using .last() just adds the desired content as the last child of the target selection, so what you're seeing is a duplicate element being added.
SOLUTION:
You could target <p> tags with the class "error" and remove them before you add them with .last():
$("p.error").remove();
You could also disable the submit button in the handler. $(".submit").prop("disabled",true);
This would prevent duplicate submissions.

Hide the input field div class using javascript

I have a payment form,in which when I click on the internet banking ,all the input field be disabled and instead show some images. this is the fiddle upto which i have done http://jsfiddle.net/f8Fd3/4/ No where I cant hide the input text field using their class id.
this is the js
function cc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("visa");
}
function dc()
{
$('#cards.credit-card').removeClass("visa mastercard").addClass("mastercard");
}
function ib()
{
}
please check the fiddle to get a clear picture
It is because, by default, when 'button' tag inside a 'form' is clicked, 'form' will be submitted.
It's not redirecting for the other two because there's a HTML5 form validation that prevents the form from being submitted. (that's why you will see an error message when you click Visa/Mastercard)
if you insist on binding events in the dom...you can pass an event object to the handler:
<button onclick="javascript:ib(event)" class="btn btn-1 btn-1c">Internet Banking</button>
and in your function:
function ib(event) {
event.preventDefault();
}
you may wanna do the same to the other two handlers as well.
so the default submit action will be prevented.
and to disable all the text fields:
$('#cards input[type=text]').prop('disabled', true);
to hide them:
$('#cards input[type=text]').hide();
EDIT
by the way. you don't have to use selectors like $('#cards.credit-card'), 'id' should be unique in the DOM, just by using $('#cards') you will get the same element.
The syntax class="class=tokenex_data full gr-input" is incorrect.
Instead use, class="tokenex_data full gr-input"
Then use :
`function ib()
{
$(".tokenex_data").hide();
$(".monthgr-input").hide();
}
`
You want to select all input & select elements and set their property disabled to true:
$('#cards input, #cards select').prop('disabled', true);
Fiddle

Trying to Change Hidden Field Value In Form if a Certain Option is Selected

I have tried researching this and I cannot get it to work. People have asked similar questions but mine is a little different. Basically, we have a form that asks a user for an amount which has an id of amount_c in the form. The hidden field in the form is this:
So, if there amount selected is "$7,500 to $9,999" for amount_c then the hidden buyer value should be 2, otherwise (if they select any other dollar amount) it should submit the hidden buyer field with a value of 1.
Currently, there is another script that is called to validate the form on submission. It is done so like this:
<form action="http://www.example.com/submission.php" method="post" onsubmit="return validate_form(this); ">
Therefore,
Should I create another script or add to the existing one?
If I can add to the existing one, what have I done wrong below (see below)?
If I can create a separate script, how would the form action line change above to call that additional script?
Here is what I have as I added it to the existing script:
$(function() {
$('#amount_c').change(function() {
if (amount_c === "$7,500 to $9,999") {
var buyer = $("#buyer").val(2);
} else {
$("#buyer").val(1);
}
});
});
Any help is greatly appreciated.
$(function() {
$('#amount_c').change(function() {
if ($(this).val() === "$7,500 to $9,999") {
$("#buyer").val(2);
} else {
$("#buyer").val(1);
}
});
});

Categories

Resources