how do i stop a form submit with jQuery - javascript

I have this form here and i dont want them to go to the next page without certain selections
<form method="post" action="step2/" id="form1">
....
....
....
<input type="submit" class="submit notext" value="Next" />
and here is my jquery
$('.submit').click(function(e) {
var business = $(".business_type_select").find('.container strong').text();
alert(business);
if(business == "Select Business Type"){
alert("BusinessBusinessBusiness");
e.preventDefault;
return false;
}
});
any ideas what i am missing to get this to stop submitting

Try using the submit event:
$("#formID").submit(function(e) {
var business = $(".business_type_select").find('.container strong').text();
alert(business);
if(business == "Select Business Type"){
alert("BusinessBusinessBusiness");
return false;
}
});
Also, the e.preventDefault() is a function, but is redundant as the return false will work just the same.

preventDefault is a function - use e.preventDefault().

There are sometimes issues with .preventDefault() in IE try adding this:
if (e.preventDefault) // checks to see if the event has a preventDefault method
e.preventDefault();
else
e.returnValue = false;

$("#formID").submit(function(e) {
var business = $(".business_type_select").find('.container strong').text();
alert(business);
if(business == "Select Business Type"){
alert("BusinessBusinessBusiness");
e.preventDefault();
return false;
}
});

If your asp.net MVC razor form looks something like this:-
You can use (document) ID to validate form values using JavaScript. JavaScript validations fire prior to validations done using HTML Helpers ( #ValidationFor etc)..
#using (Html.BeginForm("MyRequestAction", "Home", FormMethod.Post))
{
#Html.ValidationSummary(true)
code goes here...
}
$(document).submit(function (e) {
var catVal = $("#Category").val();
if (catVal == "") {
alert("Please select Category!");
return false;
}
if (catVal == "--Select One--") {
alert("Please select Category!");
return false;
}
});

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:

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

emberjs input checkValidity and setCustomValidity

Is there a way to use checkValidity() setCustomValidity() within ember? For example, in my controller upon submission I have:
var inpObj = this.get('name');
if (inpObj.checkValidity() == false) {
alert('ok');
}
and of course this is my handlebar code:
{{input id="name" type="text" value=name placeholder="Your Name" required="true"}}
Upon submission of this, I get this error message:
inpObj.checkValidity is not a function
You would need to get HTML5 element instead of string to call checkValidity function.
var inpObj = this.get('name'); // this is only a string
You can use jQuery instead:
var inpObj = Ember.$('#name')[0];
if (inpObj.checkValidity() == false) {
alert('ok');
}
Working demo.
If you want to avoid jQuery, you could set an action on your submit button that runs the valid check for you.
<button {{action "submitForm"}}>Your Button</button>
Then have an action in your contoller:
actions: {
submitForm() {
var inpObj = this.get('name');
if(!inpObj.checkValidity()) {
// error handling
alert('ok');
} else {
// save your data, or whatever you need to do
this.transitionTo('some.route');
}
}
}

If/Else statement doesn't run inside function

I am trying to validate some input fields. More specifically, the number always has to be positive.
EDIT: JS code
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
$('input[class="price"]').each(function() {
priceValue = $(this).val();
console.log(priceValue); //only runs until here and seems it exists the function then
if (priceValue <= 0) {
evt.preventDefault();
return false;
} else {
}
});
}
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
priceCheck();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate("
checkBox.isObligatory ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
evt.preventDefault();
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
return false;
});
});
I have written a function that I separately call on form submit. But it only runs until the console log. Why is the if else statement not executed?
You are using evt.preventDefault() but you didn't capture the event in evt.
For example, you could try this instead: add the evt parameter to the priceCheck function, and then pass evt to that function when you call it, like this: priceCheck(evt)
HOWEVER, you do not need to use preventDefault here. You can simply return a boolean value from priceCheck and use that in your submit handler.
You also you had a couple errors with string concatentation. $('.error-message-container').append("<%= pdo.translate(" checkBox.isObligatory ") %>"); was missing the + to concat those strings together . You can view errors like this in the Console tab of your JavaScript debugger. (UPDATE This is JSP injection, but it may not work the way you are trying to use it here. The server function pdo.translate will only execute once, on the server side, and cannot be called via client script... but it can emit client script. Focus on solving other problems first, then come back to this one.)
Finally, you were reading string values and comparing them to numbers. I used parseFloat() to convert those values from the input fields into numbers.
Here is the fixed code.
$(document).ready(function($) {
$('.error-message').hide();
function priceCheck() {
var priceValid = true; // innocent until proven guilty
$('input[class="price"]').each(function() {
priceValue = parseFloat($(this).val()) || 0;
if (priceValue <= 0) {
priceValid = false;
return false;
}
});
return priceValid;
}
$("form").on("submit", function() {
$("#offerInquiry").trigger('valid.fndtn.abide');
});
//POST FORM
$("#offerInquiry").on('valid.fndtn.abide', function(evt) {
//prevent the default behaviour for the submit event
// Serialize standard form fields:
var formData = $(this).serializeArray();
var checked = $("#terms").is(":checked");
var priceValid = priceCheck();
if (priceValid) {
$('.error-message').hide();
if (checked == false) {
$('.error-message-container').empty();
$('.error-message-container').append("<%= pdo.translate(" + checkBox.isObligatory + ") %>");
$('.error-message').show();
$('.bid-error').css("display", "block");
return false;
} else {
loading();
$.post("/inquiry.do?action=offer&ajax=1", formData,
function(data) {
window.top.location.href = data.redirectPage;
});
}
}
else
{
$('.error-message').show().text("PRICE IS NOT VALID");
}
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="offerInquiry">
Price 1
<input type="text" class="price" id="price1" value="0.00" />
<br/>Price 2
<input type="text" class="price" id="price1" value="0.00" />
<br/>
<input type='submit' />
<div class="error-message">ERROR!</div>
</form>

Submit button using jQuery not working in IE9 and FF9

This submit button works in both Safari and Chrome but not IE9 or FF9.
Submit button -
<img type="submit" src="lib/send_feedback.jpg" border="0" class="feedback-submit-img" onClick="javascript: validate(); return false;"/>
Related jQuery -
// Submit form to next page
function submitForm() {
// document.forms["feedbackform"].submit();
document.feedbackform.submit();
}
// Submit form and validate email using RFC 2822 standard
function validateEmail(email) {
// Modified version original from: http://stackoverflow.com/a/46181/11236
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// Return true if email field is left unchanged
function originalText(email){
var defaultMsg;
defaultMsg = "Enter your email address (optional)";
if(defaultMsg == email){
return true;
}
return false;
}
// Verify or decline with error message
function validate(){
$("#result").text("");
var email = $("#email").val();
if ((validateEmail(email)) || originalText(email)) {
w.value = screen.width;
h.value = screen.height;
submitForm();
} else {
$("#result").text(email + " is not a valid email.");
$("#result").css("color", "red");
}
return false;
}
$("form").bind("submit", validate);
Also for what it's worth when I alter the submit button to be more basic to ensure it submits the hidden field that w and h are suppose to update are not filled in.
Here is the entire code and the CSS
type isn't a valid attribute of the img tag: https://developer.mozilla.org/En/HTML/Element/Img
Instead I think you want a <input type="image" /> tag: https://developer.mozilla.org/en/HTML/Element/Input.
The <img type="submit" /> didn't work for me either but using a <input type="image" /> did: http://jsfiddle.net/HXrNb/1/
You can then just bind the validate() function to the submit event for the form:
$('form').on('submit', function () {
...
if ((validateEmail(email)) || originalText(email)) {
...
return true;
} else {
...
return false;
}
});

Categories

Resources