Why is my form submitted after cancelling the confirm dialog? - javascript

Here is my sample code:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.
Any suggestions?
PS: This code is a demo and different from the real one. But the concept is the same.

You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().
<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
if(con){
return true;
} else {
e.preventDefault();
return false;
}
} else {
return true;
}
}
</script>
You can also return the result of CheckData so the default action will be prevented if it returns false.
<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
return con;
} else {
return true;
}
}
</script>

Change your HTML to this:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation:
The onsubmit event handler is called when the form is submitted.
When the event handler returns false the submission is aborted.

Related

How to validate JavaScript created element in asp.net core mvc

I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:

Form not submitting with single click

I have a form where I bound action with validation. Following is line of form which calls JavaScript check.
<form id="signup_form" method="post" action="javascript:check();">
I have following JavaScript:
function check(form){
flag = 0
doValidations();
if(flag==1){
return;
} else {
$('#signup_form').submit();
$('#signup_form').attr('action', 'NewSignupConfirm.php');
return false;
}
}
When I click on submit, it does all validation and even show message of else statement but do not submit form. Than I again click on submit button and it submits form. What is wrong with it? any suggestion.
<form id="signup_form" method="post" action="NewSignupConfirm.php" onsubmit="return check();">
function check(form){
flag = 0
doValidations();
if(flag==1){
return false;
} else {
return true;
}
}
You can try this below code
function check(form){
if(doValidations()){
return true;
} else {
return false;
}
}
You don't need to add flag variable just return true or false from doValidations method

Change button type to submit

I'm trying do something like this:
Initially, the user has button "Edit booking", but after clicking on it something activates and button becomes a submit button. When the user enters his info and clicks submit, this data goes to servlet.
It works partially, but the problem is that when the button changes, I don't have a moment when the user can enter their data.
Here is my current code:
<c:if test="${booking.status == 'Checking'}">
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="editButton"
onclick="activate(); changeButton();">
</form>
<script>
function activate() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
editButton.setAttribute('type','submit');
}
else {
document.getElementById(editButton).action = "/BookingUpdate";
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
}
}
</script>
<script>
function changeButton() {
var editButton = document.getElementById("editButton");
if (editButton.value == "Edit booking") {
editButton.value = "Submit";
}
else {
editButton.value = "Edit booking";
editButton.setAttribute('type', 'button');
}
}
</script>
</c:if>
Actually, you can submit a form data by either using a submit button or calling a submit function document.getElementById("myForm").submit()directly in javascript code.
thus, you can try something like below:
<form name="myForm" id="myForm">
<input type="button" value="Edit booking" id="smartButton" onclick="doSomethingSmart();">
</form>
<script>
var smartButton = document.getElementById("smartButton");
var myForm = document.getElementById("myForm");
function doSomethingSmart() {
if(smartButton.value == "Edit booking") { // we gonna edit booking
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
smartButton.value = "submit"; // let it in disguise as submit button
}
else { // we gonna submit
if( isUserInputValied() ) {
myForm.submit(); // submiiiiiiiiiiiiiiiiiit !
// restore everything as if nothing happened
document.getElementById("bookingDate").disabled = true;
document.getElementById("returnDate").disabled = true;
smartButton.value="Edit Booking";
}
else {
alert("please fill your form correctly!");
}
}
}
function isUserInputValid() {
// check whether the user input is valid
}
</script>
You need to prevent the default event if it's in edit mode so that it won't submit the form. You can always have your button type as submit no need to change it to button.
This should work:
var button = document.getElementById('editButton');
button.addEventListener('click', toggleButton);
function toggleButton(e){
var isEdit = button.value === 'Edit booking';
if(isEdit){
document.getElementById("bookingDate").disabled = false;
document.getElementById("returnDate").disabled = false;
button.value = 'Submit';
e.preventDefault();
}
}

how to Validate Text boxes before submitting using javascript?

I have 2 text boxes with default value 0 and a submit button.Before submitting I am calling the following javascript function onSubmit="return(validate_myfrm());".I am not able to validate text_1 with value 0.But for text_2 the default value 0 is validated.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
}
return false;
}
if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
If i return true; after document.myfrm.txt_2.focus(); the page is redirected to next page without confirming the values for txt_2.Pls help
your first condition should be like this
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
}
Use Else If Instaed of if function now it will validate before submission.
function validate_myfrm()
{
var ans;
if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 1?");
if(ans== true)
{
document.myfrm.txt_1.value=0;
document.myfrm.txt_2.focus();
}
else
{
document.myfrm.txt_1.focus();
return false;
}
}else if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0)
{
ans=confirm("Do you still want to continue with value 0 for text 2?");
if(ans== true)
{
document.myfrm.txt_2.value="0";
return true;
}
else
{
document.myfrm.txt_2.focus();
}
return false;
}
return true;
}
}
document.myfrm.txt_bb1.value==0
should be: document.myfrm.txt_1.value==0
also:
Upon setting a return, the function will end and return the false or true set out in your function.
the first if when values are "" or 0 according your condition will always return false. since it is returning false, the function will end and return false.
edit:
here a simple validation example:
<form id="myfrm" name="myfrm" onSubmit="return(validate_myfrm());">
<input type="text" name="txt_1" value="" />
<input type="text" name="txt_2" value="" />
<input type="submit" value="submit" />
</form>
<span id="result"></span>
<script>
function validate_myfrm()
{
if(document.myfrm.txt_1.value!="" && document.myfrm.txt_2.value!="")
{
return true;
} else {
document.getElementById("result").innerHTML="Error fields cannot be empty";
return false;
}
}
</script>
remember in this, that whenever you use return in a function, it will stop the function and return the value set.

Its not validating on my submit button click using javascript

I have this code in my view
function Validate() {
if (document.getElementById('MandateName').value == "") {
var err = document.getElementById('MandateNameErr');
err.innerHTML = "Please enter a value for the Mandate Name";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateNameErr').style.display = "none";
}
if (document.getElementById('MandateDescription').value == "") {
var err = document.getElementById('MandateDescriptionErr');
err.innerHTML = "Please enter a value for the Mandate Description";
err.style.display = "block";
return false;
}
else {
document.getElementById('MandateDescriptionErr').style.display = "none";
}
return true;
}
and I have on submit button I am validating before submiting?
<button name="Submit" onclick="Validate()" >Add Variables to Mandate</button>
I called Validate function but its showing me if I am not entering anything on the text box if I click Button its showing me my validation message but same time its going to my view and throwing me the message?
even I put the return false; its not working is that something I am doing wrong?
You need to put return in the onclick, like this:
<button name="Submit" onclick="return Validate()" >Add Variables to Mandate</button>
Otherwise you're executing the validation...but not really caring about the result.

Categories

Resources