ASP.NET when form onsubmit called DOM elements disappear - javascript

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>

Related

How to get viewbag data in jquery?

Hi I am developing web application in mvc5. I have login form with username and password fields as below.
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid",
#class = "form-control validate[requiredInLogin] text-input "})
#Html.Password("txtPassword", null, new { #maxlength = "15", id =
"txtPassword", #class = "form-control validate[requiredOutLogin] text-input" })
<input type="submit" class="btn btn-primary btnLogin red"
value="SIGN IN" name="submit" />
}
I have below action method,
[HttpPost]
public ActionResult ClickAction()
{
//Some logic
//When 3 unsuccessful attempts made to login then i set
//ViewBag.captcha = true;
return View();
}
I will make 3 unsuccessful attempts to login then i will set ViewBag.captcha to true. Once i set ViewBag.captcha to true i want to access the ViewBag.captcha value in View and i want to display captcha. May i know how can i access Viewbag value in view? any help would be appreciated. Thanks,
Meanwhile i tried below options,
#{
var message = ViewBag.captcha;
}
Then in JS
var message = '#message';
if (message)
{
alert(message);
}
Below is my login view.
<html>
<head></head>
<body>
<div id="formID">
#*<form id="formID">*#
<div class="loginContainer">
<div class="loginContentArea">
<div class="loginLogo"><img src="~/images/c3card.png" alt="C3 Card" align="middle" /></div>
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid", #class = "form-control validate[requiredInLogin] text-input ", placeholder = "Username", autocomplete = "off" })
</div>
<div class="loginUsernamePassword">
<i class="fa fa-lock"></i>
#Html.Password("txtPassword", null, new { #maxlength = "15", id = "txtPassword", #class = "form-control validate[requiredOutLogin] text-input", placeholder = "Password", autocomplete = "off", Style = "background:#FFFFFF;" })
</div>
<div class="errormessage">#TempData["Message"]</div>
<div class="captcha" id="captcha">
<div class="g-recaptcha" data-badge="inline" data-sitekey=#System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>
<br />
</div>
<div class="loginButton">
<input type="submit" class="btn btn-primary btnLogin red" value="SIGN IN" name="submit" />
</div>
<div class="loginLink">#Html.ActionLink("Forgot Your Password?", "Index", "ForgotPassword")#**#</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('input[type=password]').each(function () {
$(this).attr('data-background-color', $(this).css('background-color'));
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
$(this).focus(function () {
$(this).attr('type', 'password');
$(this).css('background-color', $(this).attr('data-background-color'));
});
$(this).blur(function () {
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
});
});
});
jQuery(document).ready(function () {
#{ var message = ViewBag.captcha; }
alert(message);
if (message) { alert(message); }
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});
$("#myinput").rules("add", {
minlength: 2
});
</script>
</body>
</html>
This does not work for me.
May i know proper way to access viewbag value in the above scenario? Any help greatly appreciated. Thank you so much.
Since you are using Razor you could do this:
1. Get your ViewBag value to a variable
<script type="text/javascript">
var message = "#ViewBag.captcha";
</script>
You don't have to set it inside your document ready.
2.The variable is of type string however. In order to use it in a function you will have to do something like that:
If(message.toLowerCase() == "true")
in order to get the desired effect.
To convert it to boolean you could use something like that
message = message.toLowerCase() === "true"
Hope it helps
You can initialize a ViewBag value like this:
ViewBag.captcha = "true";
Then you can access it like this in a view:
var message = #ViewBag.captcha;
From here on you will be able to use message. What you essentially did was the following:
you initialize ViewBag.captcha (note that this part is commented out)
you put that into a variable called message
you try to get #message as a string, but you are not using the Javascript value calculated
Can you change the message variable like below in JS and then try
jQuery(document).ready(function () {
var message = '#ViewBag.captcha'; //change it here
if (message)
{
alert(message);
}
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});

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();
}
});
});

Meteor: form with two submit buttons (determine button clicked in event handler)

I have a simple form with two inputs: "title" and _"description", and two buttons: "save" (save for later) and "submit". For both I would want to get the values of my form fields and insert/update my collections accordingly.
<template name="NewScenarioForm">
<form id="newScenarioForm" >
<textarea type="text" id="title" name="title" rows="1" cols="75" placeholder="Type to add a title"></textarea><br/>
<textarea type="text" id="description" name="description" rows="4" cols="100" placeholder="Type to add a description" ></textarea><br/>
<input type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
</form>
</template>
Right now I'm detecting the event like this:
"click #saveScenarioButton": function(event, template) {
event.preventDefault();
var title = template.find("#title").value;
var description = template.find("#description").value;
...
//Do stuff with this information to persist information
Meteor.call("saveScenario", title, description);
....
}
And I need to repeat the whole function for the other button. I would would like to detect the event and determine which button was pressed instead.
I have been struggling with an event handler like:
"submit #newScenarioForm": function(event) {
But then I don't know how to determine the button clicked, since I can't figure out an event property. Is there a way to determine the button if I wanted to use the form ID in my event handler instead of the ID of each button (or a smarter way to approach this altogether?)?
You could make the event target inputs with type submit:
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
// Save the scenario
} else if ($(e.target).prop("id") == "submitScenarioButton") {
// Submit the scenario
}
}
});
You could also make it check the clicked button's value, and drop the ID field
Please note that this will not handle other ways of submitting the form, for example the user pressing Enter in an input field. An approach to handle this as well could be to define a few functions:
function scrapeForm() {
// Collects data from the form into an object
}
function saveData() {
var formData = scrapeForm();
// More logic to save the data
}
function submitData() {
var formData = scrapeForm();
// More logic to submit the data
}
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
saveData();
} else if ($(e.target).prop("id") == "submitScenarioButton") {
submitData();
}
},
"submit #NewScenarioForm":
// Default action on submit.
// Either save the data
saveData
// or submit the data
submitData
// or nothing, requiring the user to actually click one of the buttons
function(e) {e.preventDefault();}
});
Why not just give them both the same class like submitForm
<input class="submitForm"** type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input class="submitForm" type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
then have a onClick for .submitForm like so:
$('.submitForm').on('click', function () {...});
and inside the function get id by doing:
var id = $(this).attr('id');
full code:
$('.submitForm').on('click', function () {
var id = $(this).attr('id');
... the rest of your code ...
});
I do this to correctly identify buttons using class or id.
helloWorld.html
<head>
<title>helloWorld</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button class="plus5">+5</button>
<button class="minu5">-5</button>
<button id="plus1">+1</button>
<button id="minu1">-1</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
helloWorld.js
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);
Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.hello.events({
'click button.plus5': function () {
Session.set('counter', Session.get('counter') + 5);
},
'click button.minu5': function () {
Session.set('counter', Session.get('counter') - 5);
},
'click button#plus1': function () {
Session.set('counter', Session.get('counter') + 1);
},
'click button#minu1': function () {
Session.set('counter', Session.get('counter') - 1);
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
click .plus5, click #plus1 also work.

submit button does not invoke the action

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?

Javascript enable/disable button not working as expected

This is my logon view:
#model SuburbanCustPortal.Models.LogOnModel
#{
ViewBag.Title = "Log On";
}
<h2>Log On</h2>
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<p>
If only you wish to make a payment on your account and do not want to create a website login, #Html.ActionLink("click here", "RedirectToPaymentPage", "Account").
</p>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field focus">
#Html.TextBoxFor(m => m.UserName, new { #class = "GenericTextBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<button name="btn" value="Log On" onclick="disableButton()" disabled="disabled">Log On</button>
</p>
<p>
If you need to retrieve your username #Html.ActionLink("click here.", "ForgotUsername", "Account")<br/>
If you need to reset your password #Html.ActionLink("click here.", "ForgotPassword", "Account")
</p>
</fieldset>
</div>
}
This is my widget.js:
function enableLogonButton() {
if ($('#UserName').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
$('#btn').removeAttr('disabled');
}
function logonDisableSubmitButtons(clickedButton) {
$("input[type='button']").each(function() {
if (this.name != clickedButton)
$(this).attr("disabled", "disabled");
else {
//hiding the actually clicked button
$(this).hide();
//Creating dummy button to same like clicked button
$(this).after('<input type="button" disabled="disabled" value="' + $(this).val() + '" class="' + $(this).attr('class') + '" />');
}
});
}
function disableButton() {
$('#btn').click(function (e) {
$(this).attr('disabled', 'disabled');
});
}
I'm not having the button enabled no matter what I do.
What I am wanting is two things:
When the user has something in the logon and username, enable the submit button.
When they click submit, the button is disabled so they cannot click it twice.
I'm not having luck with either.
I have made the changes suggested below but the button is still not being enabled once I have entered something in the fields
** FURTHER TESTING**
I added the alerts() as suggested as such:
function enableLogonButton() {
alert("start");
if ($('#UserName').val() == "") {
alert("username");
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
alert("password");
$('#btn').attr('disabled', 'disabled');
return;
}
alert("enabled");
$('#btn').removeAttr('disabled');
}
Not one of them are firing off. At least, I'm getting no prompt.
So, then I changed the call to this to make sure it was even seeing the JScript:
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButtonX()" })
And I get this message:
Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
So, I believe it is seeing the JScript.
I then added this:
<script>
function myFunction() {
alert("hit!");
}
</script>
And changed this:
<button name="btn" value="Log On" onclick="myFunction()" disabled="disabled">Log On</button>
And my "hit" worked. So, I believe the onclick is working also.
disabled is a boolean property, not an attribute.
To set:
$('#btn').attr('disabled', 'disabled');
To clear:
$('#btn').removeAttr('disabled')
Unless I'm not reading your question close enough (which, admittedly, could be the case since it is after 5 here...time for beer) or you have a typo in your question, I think your error message gives you everything you need to debug this.
Here is your message: Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
Here is your function name: enableLogonButton
So, according to the error message, you are calling the function enableLogonButtonX() but your function is named enableLogonButton. Change to this:
#Html.PasswordFor(m => m.Password, new {
#class = "GenericPasswordBox",
onkeyup = "enableLogonButton()" })
Instead of changing the value of disable attribute remove it completely from element.
i.e. Replace this
$('#btn').attr('disabled', false);
With
$('#btn').removeAttr('disabled');

Categories