on button click, loop through text boxes javascript - javascript

I am trying to make a function actuated by a button click. On click, a function loops through each input type=text element, assigns their value attribute to variable, if that variable = null or variable = "" call method confirm('are you sure you want to save a blank row').
Here's my code/pseudo code:
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = $(this).attr('value');
var bool = false;
if(x == null || x == "")
{
bool = true;
}
else
{
send the request
}
if(bool == true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
send the request
}
else
{
do nothing or cancel the request
}
}
else
{
send the request
}
}
}
</script>
Here is my asp button code:
<asp:Button ID="btnSave" runat="server" Text="Save"/>
If you need more information, please let me know.
Thanks in advance

For ID issue, if you use ASP.Net 4.0 +, set ClientIDMode=Static
<asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save"/>
JS
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = this.value;
var bool = false;
if(x === null || x === "")
{
bool = true;
}
else
{
send the request
}
if(bool === true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
LoadData();
}
else
{
return;//do nothing
}
}
else
{
send the request
}
}
}
function LoadData()
{
$.ajax({
type: "GET",
url: 'page.aspx',
timeout: 1000,
success:function(data){
//do work
},
error:function(jqxhr, status){
if(status==="error"){
//handle error
}
});
}
</script>

Since it's ASP.NET, that ID is going to be rendered different, try grabbing the Client ID (if the JS is in the same file, if it is not, use a unique class and assign the handler via that)
$("#<%=btnSave.ClientID%>").click(function() {
$("input:text").each(function() {
if (!this.value.length) {
var confirm = confirm('are you sure you want to save a blank row')
..
}
});
});

You can also do like below....
<script type="text/javascript">
function isInputEmpty() {
var bool = false;
$("#btnSave").click(function () {
$('input[type=text]').each(function () {
var x = $(this).attr('value');
if (x == null || x == "") {
bool = true;
}
});
if (bool == true) {
if (confirm('Are you sure you want to save a blank URL?')) {
//send the request
}
else {
//do nothing or cancel the request
}
}
else {
//send the request
}
});
}
</script>

It's not entirely clear what your question is, but other answers here have rightfully focussed on the ID issue and .Net webforms changing the element's ID.
The other solutions suggested are fine, but there is also another way, and that is searching by partial ID. When clientIDmode isn't set to static (or if you're pre .Net 4.0) the .NET ID will always have the original id appended after an underscore, so you can find your element using jquery like this:
$("[id$='_btnSave']").click(function(){ ...

Related

Prevent sending data to DB/server if form validation is false (VueJS)

I want to stop sending information if form validation is false.
I have a button Save with two functions in it:
<span class="logInBTN" v-on:click="validationFields(); function2(model)">Save</span>
The form validation is being proccessed in validationFields():
validationFields() {
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
}
So if it's not chosen a type from the input field, function2() must not continue.
Update1:
<script>
export default {
components: {
},
data(){
return {
errors: [];
},
},
methods: {
validationFields() {
this.errors = [];
var falseValidation = false;
if (this.model.codePerson == '') {
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
falseValidation = true;
} else {
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
}
if (falseValidation == true) {
alert("Form validation:\n" + this.errors.join(""));
}
if(falseValidation == false){
this.createEori(eoriData);
}
}
createEori(eoriData) {
eoriData.state = '1';
eoriData.username = this.$session.get('username');
console.log("updateEori state: " + JSON.stringify(eoriData));
const url = this.$session.get('apiUrl') + 'registerEORI';
this.submit('post',
url,
eoriData
);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log('EORI saved!');
console.log('Response:' + response.data.type);
if("E" == response.data.type){
alert(response.data.errorDescription);
} else {
alert("Saved!");
}
})
.catch(error => {
console.log('EORI rejected!');
console.log('error:' + error);
});
},
},
}
</script>
createEORI is the function2
Update2
Now it works, but the data from the fields it's not send to the server. That's all fields from the page, some are datepickers or an ordinary input text field. Before the change in the browser console show this, if I write a name in the first field it will show up in c1_name etc:
{"state":"1","c1_form":"","c1_identNumber":"","c1_name":"","c1_shortName":"","c1_8_street":"","c1_8_pk":"","c1_8_name":"","c1_8_city":"","c1_8_codeCountry":"","c1_identNumber1":"","c3_name":"","c3_nameShort":"","c3_city":"","c3_codeCountry":"","c3_street":"","c3_pk":"","c3_phone":"","codePerson":"","codeActivity":"","c1_date":"","c5_date":"","c7_date":"","dateFrom":"","dateTo":"","c8_date":"","c1_numberVAT":"","c8_provider":"","c8_number":"","codeMU":"","agreed1":"","agreed2":"","username":"testuser"}
However, after the change the sent data or at least the seen data is only:
{"state":"1","username":"testuser"}
The log is from
console.log("updateEori state: " + JSON.stringify(eoriData));
from createEORI() function
I think it would be better practice to only call one function from the HTML. Something like this:
<span class="logInBTN" v-on:click="submit(model)">Save</span>
submit(model) {
if (this.validateForm(model) == true)
{
// submission process here (maybe call function2())
}
}
validateForm(model) {
if (this.model.codePerson == ''){
document.getElementById('codePerson').style.borderColor = "red";
this.errors.push("Choose a type!\n");
this.handleFalseValidation();
return false;
}
document.getElementById('codePerson').style.borderColor = "#CCCCCC";
return true;
}
handleFalseValidation() {
alert("Form validation:\n" + this.errors.join(""));
}
Ok I fixed the problems with sending the data.
It was my fault.
I will copy the Chris answer. That worked.
When you call this.createEori(eoriData);, eoriData is undefined. It doesn't exist. Use this.createEori(); instead, and in the createEori function, remove the parameter and add var eoriData = {}; as first line. (note this is very basic javascript, how functions and variables work, and completely unrelated to Vue or server requests)

Setting value in JS, but codebehind doesn't get updated value. ASP.Net

I'm using bootbox prompt to do validation before saving, in the callback function I'm setting a hiddenfield value and then going into a button click event. But hiddenfield in the C# part doesn't get the value I've set in the JS. How should I fix this?
JS:
function notePrompt() {
var protNumber = $("#hfProtNumberGen").val();
var hfNote = document.getElementById("<%= hfNote.ClientID %>");
var btnHidden = document.getElementById('btnHidden');
if (protNumber != "") {
bootbox.prompt({
title: "Въведете причина за промяната. Повърдете запазването на информацията.",
inputType: 'textarea',
buttons: {
confirm: {
label: "Запази"
},
cancel: {
label: "Откажи"
}
},
callback: function (result) {
if (result == null) {
hfNote.value = "";
}
else {
var MaxLenghtResult = result.slice(0, 200);
hfNote.value = MaxLenghtResult;
if (hfNote.value != "") {
setTimeout(function () { btnHidden.click(); }, 1000);
}
}
}
});
}
else {
setTimeout(function () { btnHidden.click(); }, 1000);
}
}
C#:
string Note = hfNote.Value; //always gets ""
you have to do like this , means you have to make control runat ="server" and in javascript need to udpate value in control by getting clientid of control
//axps file - this seems working for you
<asp:HiddenField ID = "hfName" runat = "server" />
//javascript --- you need to this change
document.getElementById("<%=hfName.ClientID %>").value = MaxLenghtResult;
//in aspx.cs file
string note = Request.Form[hfName.UniqueID];

Mousedown still submitting form, when it should not

hello i have a login validation form which uses a mix of jquery and ajax to do validations... if the values are ok the form should submit, if the values are not ok then the form should not submit... however in my case the form is submitting even when the values are incorrect ( i am using the mousedown function ) please see below my code..
<form method="post" name="loginform" action="models/login.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" />
<div class="errormsg" id="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" />
<div class="errormsg" id="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class="errormsglast" id="errormsg8"></div>
</form>
jquery and ajax
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val().toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password - See Forgot Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
/* ----------------- Stop on Submit */
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
Solution Tried - problem is that when user puts the wrong event that is fine, but if user then puts the correct values, the submit returns false on first time, then second time it returns true... it should return true in first go
<input type="button" name="login" id="login" value="Submit">
$( "#login" ).mousedown(function()
{
validate_email_login();
validate_password_login();
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
$('[name=loginform]').submit();
}
});
});
Instead of having a type="submit" button just have a normal button e.g<input type="button" name="login" id="login" value="Submit">. Then when you finished checking the values and happy that it should send then just call:
$('[name=loginform]').submit();
Because what is happening currently is that the form submits when you click on the button, because you are not stopping that event from happening.
If you want to prevent the form from submitting I would suggest either not using that button and initiating the submit yourself like I mentioned above, or alternatively you can use the onsubmit="someFunction()" on the form element way and just return false if it should not submit and return true if it should.
I would say your code suffers from a few issues and some bad practices.
I see you are trying to learn JS so forgive me for not directly solving your issue but to give you some pointers and point you to some best practices.
Logic -
It seems like you are doing a login form. I would say most of this checks should not happen in the client but on the server.
When user signups it might be wise to check user name length on the client as well and prompt the user that he can't use the user name he wants to register with, but during login all the client care is can I login or not.
Security -
You seem to have two serious security issues with your code
You allow to test if an e-mail/user exist or not using 'classes/validatelogin.php?f=1'. in general you should always test the user and password together if they exist and match the user should be able to login, if not the login should fail. you shouldn't notify the user why it fails (if the user name does not exist or if it exist but the password is wrong).
You don't seem to hash passwords in the database. I assume it by limiting the password max length. let the user choose as long password as he wants and hash it using a secure hashing algorithm (I'd suggest bcrypt but google around and find a suitable one). I know you are only learning but this is highly important I think hashing is the first thing you need to learn when handling user logins
Working with the DOM.
You should cache your DOM elements
so instead of calling $('#id') all the time in the main function scope set
var emailInput = $("#user_email2");
function submitForm() {
var email = emailInput.val().toLowerCase();
...
}
You should also probably set the text value of the element and not the html doesn't matter much now but since you are setting text value its good practice and will help you avoid unexpected injections and errors.
Since your using ajax you should not let the form to submit itself even when validation is successful.
Common logic should be packed into functions and reused.
There are many places where your original code can be split into shorter and reusable functions
handle async code better
jQuery supports the Promise API when using ajax requests, I would rather use it. Your original code had a few async calls if you needed to sync between them it would have been painful using plain callbacks (and it is probably what caused you issues in the first place)
Here is a simplified solution using my suggestions -
$(document).ready(function() {
"use strict";
var emailInput = $("#user_email2"),
emailError = $("#errormsg6"),
passwordInput = $("#user_password2"),
passwordError = $("#errormsg7");
function required (value) {
if (value) {
return true;
} else {
return false;
}
//this is just to make the code clear you could use
//`return value ? true : false` or `return !!value`
}
$('form:eq(0)').on('submit', function (e) {
var valid = true,
email = emailInput.val(),
password = passwordInput.val();
e.preventDefault();
if ( !required(email) ) {
emailError.text('Email is required');
valid = false;
}
if ( !required(password) ) {
passwordError.text('Password is required');
valid = false;
}
if ( valid ) {
$.ajax({
method: "POST",
url: "login.php",
data: {
email: email,
password: password
}
}).done(function (data, textStatus, jqXHR) {
//redirect user to main page
}).fail(function (jqXHR, textStatus, errorThrown) {
//show the user the error
})
}
});
});

Javascript confirm in if condition statement in asp.net

I've javascript confirmation function like this:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your team is incomplete. Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I want to show this when the team really incomplete. I check it in save button click. If false; I want to call JS confirm function:
if ((teamList.Contains("Purchasing") && teamList.Contains("Quality") && teamList.Contains("Process") && teamList.Contains("R&D")))
{ }
else
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CallMyFunction", "Confirm()", true);
}
If confirm returns yes, I want to save them. If no, I don't want to save them.
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Do save operations
}
These code snippets returns null first time, and it returns my confirm answer (yes or no) when the other button clicks.
How can I do?

asp.net delete popup using javascript and c#

I am bit struggling to understand how it works when you want to delete something using server side. I know how to use MessageBox but it is not ideal. I am advised to use popup on server side.
What I am trying to do is that when you click the button, popup should display to ask you if you are sure you want to delete it. If yes, delete it based on C# delete events. If no, cancel it. How to work with both of javascript and C#?
I got problem When I click the button, popup happens, and when i click yes, delete it which is working BUT when I click no, still delete it. How to handle with yes and no in C# or javascrpit? No idea how to do this.
Your excample code means alot to me. I need to understand. Thanks!!
Javascript
<script type='text/javascript'>
var result = confirm("Do you Want to Delete?");
if (result)
{
//do ajax call and delete from database
return true;
}
else
{
return false;
}
ASP.NET
<asp:Button runat="server" OnClick="btnDelete_Click" OnClientClick = " return confirm();" />
C#
protected void btnDelete_Click(object sender, EventArgs e)
{
//Delete operation
}
Html markup:
<asp:Button runat="server" OnClick="btnDelete_Click"
OnClientClick = " return myConfirm();" />
Js
<script type='text/javascript'>
function myConfirm(){
var result = confirm("Do you Want to Delete?");
if (result==true)
{
//do ajax call and delete from database
return true;
}
else
{
return false;
}
}
</script>
If you have a server button with both client and server events. You can check the client side, and decide weather the server side should be executed or not. for example :
add a CSS class to your button.
$('.CssClassOfYourButton').click(function (evt) {
if (condition)
return false;
// Post Back will not happen
}
if (confirm('Are you sure? \nDoing this will ......... .')) {
return true;
// if user clicks yes ,Post Back will happen and server side delete event is executed.
}
});
client side:
function confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you Want to Delete?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
return false;
}
document.forms[0].appendChild(confirm_value);
}
On server side:
protected void btnDelete_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
}
else
{
}
}

Categories