submit button does not invoke the action - javascript

Im using the following button which is working fine and invoke the action as expected,
save button
#using (Html.BeginForm("edit", "user", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="actionbtn" value="Save" name="buttonType" />
</div>
</div>
}
Check button
#using (Html.BeginForm("Check", "User"))
{
<input type="submit" id="btnConnect" value="Check" />
<span id='result'></span>
}
now when I add the following code that should add some text if the operation was successful or not ,the save button does not invoke the action ,what am I doing wrong here?
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
i've try to remove e.preventDefault(); without sucess...

you need to check like this that form submitted via which button.
you have to do like this to restrict it:
$("form").submit(function (e) {
// Cancel the default submission
e.preventDefault();
if($(this).find('input[type="submit"]').val() === "Check") // form submitted via Check button
{
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
}
else
{
// form submitted from Save button
}
});

First of all you need to add ID to your form:
#using (Html.BeginForm("Check", "User",FormMethod.Post, new { Id = "CheckForm" })
Then you need to add submit event handler only to form that needed:
$("#CheckForm").submit(function (e) {
// Cancel the default submission
e.preventDefault();
// Perform the AJAX call
var target = $(this).attr('action');
$.post(target, function(result) {
// Check the value of result
if (result === "True") {
// It was successful, make result text green.
$("#result").css('color', 'green').html("Successful.");
} else {
// Otherwise, it failed, display as red.
$("#result").css('color', 'red').html("Failed");
}
});
});
There is also another thing. When you make Ajax submit like this - then it will make submit of empty form. Is what you need?

Related

Onclick and jQuery click working together but return false not working in jquery

Onclick and jQuery click working together but return false not working in jquery. I want to validate fields before on onclick open next page. Problem with my code is that if filed are blank in that case it open next page. I use return false in each empty case. So until all fields are not filled up. next page should not open.
Html Code
<button id="onepage-guest-register-button" type="button" class="button secondary" onclick="$('login:guest').checked=true; checkout.setMethod();"><span><span><?php //echo $this->__('Checkout as Guest') ?></span></span></button>
jQuery Code
jQuery('#onepage-guest-register-button').click(function(e){
var email=jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
alert("name"+login_name+'phone'+login_phone+'email'+login_email);
if(login_name==''){ jQuery('.login_name').text('Please enter full name'); return false; }else{ jQuery('.login_name').empty();}
if(login_phone==''){ jQuery('.login_phone').text('Please enter Phone Number');return false;}else{ jQuery('.login_phone').empty();}
if(login_email==''){ jQuery('.login_email').text('Please enter Phone email');return false;}else{ jQuery('.login_email').empty();}
//alert('trigger');
jQuery('#onepage-guest-register-button').trigger('onclick');
});
Don't mix onclick attribute with onclick event handler. It's just plain silly.
In most cases, it's better to go with the latter.
1) Remove onclick attribute
<button id="onepage-guest-register-button" type="button" class="button secondary"><span><span><?php echo $this->__('Continue') ?></span></span></button>
2) Move the logic into your onclick event handler.
jQuery('#onepage-guest-register-button').click(function(e){
// no idea
var email = jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
// get values
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
// flag if errors is found; assume no errors by default
var err = false;
// clear errors?
jQuery('.login_name').empty();
jQuery('.login_phone').empty();
jQuery('.login_email').empty();
// show errors if any
if (login_name == '') {
jQuery('.login_name').text('Please enter full name');
err = true;
}
if (login_phone == ''){
jQuery('.login_phone').text('Please enter Phone Number');
err = true;
}
if (login_email == ''){
jQuery('.login_email').text('Please enter Phone email');
err = true;
}
// do the appropriate action depending if there are errors or not
if (err) {
return false;
} else {
$('login:guest').prop('checked', true);
checkout.setMethod();
}
});

Double submit, prevent default not working

I hope someone can help me.
I have two buttons on my page in my form. "Save" and "Publish". This is the HTML:
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum({{ album.id }}, '{{ album.title }}')">Publish</button>
The first one saves the album, the second one sends an e-mail to the owner. The second one ("Publish") needs to trigger a confirm first ("Are you sure?"). When you click "Ok", the form should submit, but if you click "Cancel" (in the confirm box), it should do nothing.
Here is my JS:
function publishAlbum(album_id, album_title)
{
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
}
I tried literally everything (prevent default, return etc), but every time I click "Cancel", the form still submits and the e-mail is sent.
Can someone help me?
Publish
$('.publish-button').on('click',function(e){
e.preventDefault();
let albumId = $('#selectYourAlbumId');
let albumTitle = $('#selectYourAlbumTitle');
var result = confirm('Are you sure you want to publish this album?');
if(!result)
{
return;
}
// POST your form through an AJAX call
})
You need to get the event object somehow (e.g. by adding an event listener to the button). Then you are able to prevent the form submission, like so:
const album = {
id: 1,
title: 'Test',
};
document.querySelector('[name=publish]').addEventListener('click', function(e) {
if (!publishAlbum(album.id, album.title)) {
e.preventDefault();
}
});
function publishAlbum(album_id, album_title) {
var result = confirm('Are you sure you want to publish this album?');
if (!result) {
return false;
}
// do your stuff
return true;
}
<form action="https://example.org" method="POST">
<button type="submit" class="button">Save</button>
<input type="submit" class="button" name="publish" value="Publish" />
</form>
Assuming you have these buttons inside a form tag, you can try this:
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button type="submit" class="button">Save</button>
<button type="button" class="button" name="publish" value="true" onclick="publishAlbum()" id="myButton">Publish</button>
<script>
function publishAlbum() {
var txt;
if (confirm("Press a button!") == true) {
$("#myButton").trigger('submit');
} else {
txt = "You pressed Cancel!";
alert(txt)
}
}
</script>
</body>
</html>
I used this:
$(document).ready(function() {
$('#form-publish .button-publish').on("click", function(e) {
var c = confirm("Are you sure?");
if (c) {
return;
} else {
e.preventDefault();
}
});
});

Validation on input field using javascript

I wants to check, if entered field's value is valid or not using onchange before submitting the page. I have written like below.It validates well.But how to activate 'NEXT' button when there is no error on input entries.
<div><input type="text" name="your_name" id="your_name" onchange = "validate_Name(this,1,4)" />
<span id="your_name-error" class="signup-error">*</span>
</div>
<div><input type="text" name="your_addr" id="your_addr" onchange = "validate_Name(this,1,4)" />
<span id="your_addr-error" class="signup-error">*</span>
</div>
<input class="btnAction" type="button" name="next" id="next" value="Next" style="display:none;">
<script type="text/javascript" src="../inc/validate_js.js"></script>
<script>
$(document).ready(function() {
$("#next").click(function() {
var output = validate(); //return true if no error
if (output) {
var current = $(".active"); //activating NEXT button
} else {
alert("Please correct the fields.");
}
});
}
function validate() {
//What should write here?I want to analyse the validate_js.js value here.
}
</script>
Inside validate_js.js
function validate_Name(inputVal, minLeng, maxLeng) {
if (inputVal.value.length > maxLeng) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Max Characters:" + maxLeng;
} else if (!(tBox.value.match(letters))) {
inputVal.style.background = "red";
inputVal.nextElementSibling.innerHTML = "<br>Use only a-zA-Z0-9_ ";
} else {
inputVal.style.background = "white";
inputVal.nextElementSibling.innerHTML = "";
}
}
If by "activating" you want to make it visible, you can call $('#next').show().
However if you want to simulate a click on it, with jQuery you can simply call $('#next').click() or $('#next').trigger('click') as described here. Also, you might want to put everything in a form and programmatically submit the form when the input passes validation.
You could possibly trigger the change event for each field so it validates each one again.
eg.
function validate() {
$("#your_name").trigger('change');
$("#your_addr").trigger('change');
}

ASP.NET when form onsubmit called DOM elements disappear

I have simple Html.BeginForm with some data, and i want to check some condition using onsubmit() javascript function when user clicked "submit" button, before form will be send. And when this condition is false, I want to stop reloading page, just don't send my form to POST method. This is working fine, bit I met a problem, because DOM elements which I create in onsubmit() method disappear:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", **onsubmit=" return registerValidation()"**}))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #id = "emailVal"})
#Html.ValidationMessageFor(m => m.Email,"", new { #class = "validation-error-white", #id="emailValidation"})
<input type="submit" class="btn btn-warning btn-block add-item-button-text" value="Zarejestruj" />
}
<script type="text/javascript">
function registerValidation() {
var validForm = validateRegisterForm(email, login);
if (!validForm) {
$('#emailValidation').append('Those email already exists! Take another one');
return false;
}
return true;
}
</script>
So when I want to return false, and do not send form, text that I append to validation-div that says what's wrong disappear - it's not what I want to achieve, because it's very small period of time and user cannot even notice that!
You manually trigger the button click event. Make sure type is button.
You do not need **onsubmit=" return registerValidation()"**
<input id="btnSubmit" type="button" ... />
<script type="text/javascript">
$(function () {
// Trigger btnSubmit button's click event, when enter key is pressed.
// If you do not want that feature, you can ignore this.
$("form").keydown(function (event) {
if (event.keyCode === 13) {
$("#btnSubmit").click();
return false;
}
});
$("#btnSubmit").click(function () {
// Do something, then submit the form
$("form").submit();
});
});
</script>

JavaScript Prevent Form Submit

I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.
I have this code:
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var link = $(this).attr("href"); // "get" the intended link in a var
var result = confirm("Are you sure you want to log this fault?");
if (result) {
document.location.href = link; // if result, "set" the document location
}
});
});
The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.
My HTML code is:
<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">
<!-- other elements -->
....
....
....
<button type="submit" id="submit" class="btn btn-default">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
</form>
$(function() {
//this would do the same as button click as both submit the form
$(document).on("submit", "#myform", function (e) {
var result = confirm("Are you sure you want to log this fault?");
//if cancel is cliked
if (!result) {
return false;
}
//if ok is cliked, form will be submitted
});
});
the following like won't work since this reffers to the submit button which does not have an href attribute.
var link = $(this).attr("href"); // is invalid.
try
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var result = confirm("Are you sure you want to log this fault?");
if (result) {
$('#formId').submit(); // where formId is the id of your form
document.location.href = "url to which you want to redirect";
}
else
return false;
});
});
side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)

Categories