perform 3 javascript functions on single button click - javascript

I am using 3 javascript functions for textfield validation,
validate all the fields once all the fields are properly entered
yes/cancel confirmation should be also along with a
pop up window with the textfilled values which are display in a pageto verify entered values are correct
Once i select yes my button click event should occur if no is selected nothing sholud happen. pop up window can be closed by the user
Here is my js script,
I am getting all my textfields validated and getting confirmation box yes/cancel but popup window page is not displaying
<script type="text/javascript">
function UserDetailsConfirmation() {
return confirm("Are you sure you want to add this ?");
return openwin();
}
function openwin() {
window.open('PopupForConfirm.aspx?name1=' + name + '&age1=' + age + '&gen=' + gender + '', 'open_window', ' width=640, height=480, left=0, top=0');
}
function validate() {
var name= document.getElementById('<%=this.txtname.ClientID %>');
var age= document.getElementById('<%=this.txtage.ClientID %>');
var gender= document.getElementById('<%=this.txtgender.ClientID %>');
if (name.value) == "") {
alert("Please Enter Name");
name.focus();
return false;
}
else if (age.value) == "") {
alert("Please Enter age");
age.focus();
return false;
}
else if (gender.value) == "") {
alert("Please enter gender");
gender.focus();
return false;
}
else if (!UserDetailsConfirmation()) {
return false;
}
else {
return true;
}
}
</script>

You return right before you call openwin. How could it be reached? How about:
function UserDetailsConfirmation() {
return confirm("Are you sure you want to add this ?") && openwin();
}
BTW:
if (!UserDetailsConfirmation()) {
return false;
}
else {
return true;
}
boils down to:
return UserDetailsConfirmation();

<script type="text/javascript">
function UserDetailsConfirmation() {
var r = confirm("Are you sure you want to add this ?");
if (r == true) {
openwin();
} else {
return false;
}
}
function openwin() {
window.open('PopupForConfirm.aspx?name1=' + name + '&age1=' + age + '&gen=' + gender + '', 'open_window', ' width=640, height=480, left=0, top=0');
}
function validate() {
var name= document.getElementById('<%=this.txtname.ClientID %>');
var age= document.getElementById('<%=this.txtage.ClientID %>');
var gender= document.getElementById('<%=this.txtgender.ClientID %>');
if (name.value) == "") {
alert("Please Enter Name");
name.focus();
return false;
}
else if (age.value) == "") {
alert("Please Enter age");
age.focus();
return false;
}
else if (gender.value) == "") {
alert("Please enter gender");
gender.focus();
return false;
}
else if (!UserDetailsConfirmation()) {
return false;
}
else {
return true;
}
}
</script>
I have changed your code a bit ... While opening a popup return is not needed
I think this is enough to work

Try this on your onclick, call UserDetailsConfirmation:
<script type="text/javascript">
function UserDetailsConfirmation() {
if(validate() == true)
{
var r = confirm("Are you sure you want to add this ?");
if (r == true) {
openwin();
}
} else {
alert('Something went wrong');
}
}
function openwin() {
window.open('PopupForConfirm.aspx?name1=' + name + '&age1=' + age + '&gen=' + gender + '', 'open_window', ' width=640, height=480, left=0, top=0');
}
function validate() {
var name= document.getElementById('<%=this.txtname.ClientID %>');
var age= document.getElementById('<%=this.txtage.ClientID %>');
var gender= document.getElementById('<%=this.txtgender.ClientID %>');
if (name.value) == "") {
alert("Please Enter Name");
name.focus();
return false;
}
else if (age.value) == "") {
alert("Please Enter age");
age.focus();
return false;
}
else if (gender.value) == "") {
alert("Please enter gender");
gender.focus();
return false;
}
else{
return true;
}
}
</script>
Edited Option 2
This is actually based on your code..
<script type="text/javascript">
function UserDetailsConfirmation() {
return confirm("Are you sure you want to add this ?");
}
function openwin() {
window.open('PopupForConfirm.aspx?name1=' + name + '&age1=' + age + '&gen=' + gender + '', 'open_window', ' width=640, height=480, left=0, top=0');
}
function validate() {
var name= document.getElementById('<%=this.txtname.ClientID %>');
var age= document.getElementById('<%=this.txtage.ClientID %>');
var gender= document.getElementById('<%=this.txtgender.ClientID %>');
if (name.value) == "") {
alert("Please Enter Name");
name.focus();
return false;
}
else if (age.value) == "") {
alert("Please Enter age");
age.focus();
return false;
}
else if (gender.value) == "") {
alert("Please enter gender");
gender.focus();
return false;
}
else if (UserDetailsConfirmation() == true) {
openwin();
}
else{
return false;
}
}
</script>

Related

How to get jQuery dropdown data on change of value

I have added values Validate and Submit the a form. now i want to add a select box and add the data to the Validation
The plan is to have 2 dropdown boxes, collect all the select box data, Validate said data before submit using jQuery, Ajax, and PHP
Any ideas or suggestions? Thanks.
My JS code
<script>
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var firstname = $('#inputfName').val();
var lastname = $('#inputlName').val();
var email = $('#inputEmail').val();
var telephone = $('#inputTel').val();
var category = $('#category').val();
var gender = $('#gender').val();
if (category.trim() == '') {
alert('Please select a category.');
$('#category').focus();
return false;
if (firstname.trim() == '') {
alert('Please enter your name.');
$('#inputfName').focus();
return false;
if (lastname.trim() == '') {
alert('Please enter your name.');
$('#inputlName').focus();
return false;
if (gender.trim() == '') {
alert('Please select your gender.');
$('#gender').focus();
return false;
} else if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
} else if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
} else if (telephone.trim() == '') {
alert('Please enter your Phone Number.');
$('#inputTel').focus();
return false;
} else {
$.ajax({
type: 'POST',
url: 'submit_Vform.php',
data: 'contactFrmSubmit=1&firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&gender=' + gender + '&category=' + category + '&telephone='
telephone,
beforeSend: function() {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function(msg) {
if (msg == 'ok') {
$('#category').val('');
$('#inputfName').val('');
$('#inputlName').val('');
$('#gender').val('');
$('#inputEmail').val('');
$('#inputTel').val('');
$('.statusMsg').html('<h1> Thank you for your interest!</h1><p>We\'ll get back to you soon.</p>');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
sample HTML of my the select box i wish to add
<div class="ui-widget">
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
While add a select, all you need to do is
get its value first by var drop = $('#drop').val();
validate it if (drop == '') ...
modified as below:
function submitContactForm() {
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var firstname = $('#inputfName').val();
var lastname = $('#inputlName').val();
var email = $('#inputEmail').val();
var telephone = $('#inputTel').val();
var category = $('#category').val();
var gender = $('#gender').val();
var drop = $('#drop').val();
var drop2 = $('#drop2').val();
if (category.trim() == '') {
alert('Please select a category.');
$('#category').focus();
return false;
}
if (firstname.trim() == '') {
alert('Please enter your name.');
$('#inputfName').focus();
return false;
}
if (lastname.trim() == '') {
alert('Please enter your name.');
$('#inputlName').focus();
return false;
}
if (gender.trim() == '') {
alert('Please select your gender.');
$('#gender').focus();
return false;
}
if (email.trim() == '') {
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}
if (email.trim() != '' && !reg.test(email)) {
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}
if (telephone.trim() == '') {
alert('Please enter your Phone Number.');
$('#inputTel').focus();
return false;
}
if (drop == '') {
alert('Please select drop\'s value');
return false;
}
if (drop2 == '') {
alert('Please select drop2\'s value');
return false;
}
$.ajax({
type: 'POST',
url: 'submit_Vform.php',
data: 'contactFrmSubmit=1&firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&gender=' + gender + '&category=' + category + '&telephone='
telephone+ '&drop=' + drop + '&drop2=' + drop2,
beforeSend: function() {
$('.submitBtn').attr("disabled", "disabled");
$('.modal-body').css('opacity', '.5');
},
success: function(msg) {
if (msg == 'ok') {
$('#category').val('');
$('#inputfName').val('');
$('#inputlName').val('');
$('#gender').val('');
$('#inputEmail').val('');
$('#inputTel').val('');
$('#drop').val('');
$('#drop2').val('');
$('.statusMsg').html('<h1> Thank you for your interest!</h1><p>We\'ll get back to you soon.</p>');
} else {
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}

Why my below javascript code in asp.net not working?

<script language="javascript" type="text/javascript">
function validate() {
summary += isvalidFirstName();
summary += isvalidMobile();
summary += checkPassword();
summary += checkEmail();
if (summary != "") {
alert(summary);
return false;
} else
return true;
}
function isvalidFirstName() {
var uid;
var temp = document.getElementById("<%=txtFirstName.ClientID %>");
uid = temp.value;
if (uid == "") {
return ("Please enter firstname" + "\n");
} else
return "";
}
function isvalidMobile() {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMob = document.getElementById(txtMobile);
if (mob.test(txtMob.value) == false) {
alert("Please enter valid mobile number");
txtMob.focus();
return false;
} else
return true;
}
function checkPassword(inputtxt) {
var pass = /^[A-Za-z]\w{7,14}$/;
if (inputtxt.value.match(pass)) {
alert("Password is correct");
return true;
} else {
alert("Wrong...!");
return false;
}
}
function checkEmail(inputtxt) {
var mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputtxt.value.match(mail)) {
return true;
} else {
alert("Please enetr a valid email id");
return false;
}
}
</script>
I have added the above javascript code inside an .ASPX page and called the function validate on button click but it is not working. Can anyone help me?

How to validate multi-functions using Javascript in .asp

I am attempting to validate 6 functions on a form. I am getting the appropriate alerts set for each function but the form does not seem to be validating correctly and is submitting the form when the 'Generate' button is pressed.
I would be extremely grateful for any advice on this
This is how I have it set at present:
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
<script type="text/javascript" language="Javascript">
function RequiredTextValidate() {
//check all required fields are completed
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
document.getElementById("<%=CompletedByTextBox.ClientID%>").focus();
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
document.getElementById("<%=CompletedExtTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
document.getElementById("<%=EmployeeNoTextBox.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
document.getElementById("<%=EmployeeNameTextBox.ClientID %>").focus();
return false;
}
return true;
}
function CheckDateTime() {
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if (document.getElementById("<%=SickDateTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickDateTextBox.ClientID %>").value.match(re)) {
alert("Invalid date format: " + document.getElementById("<%=SickDateTextBox.ClientID %>").value);
document.getElementById("<%=SickDateTextBox.ClientID %>").focus();
return false;
}
// regular expression to match required time format
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' && !document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re)) {
alert("Invalid time format: " + document.getElementById("<%=SickTimeTextBox.ClientID %>").value);
document.getElementById("<%=SickTimeTextBox.ClientID %>").focus();
return false;
}
return true;
}
function ReasonAbsenceValidate() {
//check that reason for absence field is completed
if (document.getElementById("<%=ReasonTextBox.ClientID%>").value == "") {
alert("Reason for absence field cannot be blank");
document.getElementById("<%=ReasonTextBox.ClientID%>").focus();
return false;
}
return true;
}
function ReturnDateChanged() {
// check that either Return date or Date Unknown fields are completed
var ReturnDateValid = document.getElementById("<%=ReturnDateTextBox.ClientID%>").value;
var ReturnDateUnknown = document.getElementById("<%=ReturnUnknownCheckBox.ClientID%>").checked;
if (ReturnDateUnknown.checked)
{
ReturnDateValid.disabled = false;
ReturnDateUnknown.disabled = "disabled";
}
if (ReturnDateValid == "" && ReturnDateUnknown == "") {
alert("You must enter at least one field for anticipated return");
return false;
}
return true;
}
function FirstDateChanged() {
// check that either First date of sickness or Date Unknown fields are completed
var FirstDateValid = document.getElementById("<%=FirstDateTextBox.ClientID%>").value;
var FirstDateUnknown = document.getElementById("<%=FirstDateUnknownCheckBox.ClientID%>").checked;
if (FirstDateUnknown.checked)
{
FirstDateValid.disabled = false;
FirstDateUnknown.disabled = "disabled";
}
if (FirstDateValid == "" && FirstDateUnknown == "") {
alert("You must enter at least one field for first day of sickness");
return false;
}
return true;
}
function ActualDateChanged() {
// check that either Actual date of return or Date Unknown fields are completed
var ActualDateValid = document.getElementById("<%=ActualDateTextBox.ClientID%>").value;
var ActualDateUnknown = document.getElementById("<%=ActualDateUnknownCheckBox.ClientID%>").checked;
if (ActualDateUnknown.checked)
{
ActualDateValid.disabled = false;
ActualDateUnknown.disabled = "disabled";
}
if (ActualDateValid == "" && ActualDateUnknown == "") {
alert("You must enter at least one field for actual date of return");
return false;
}
return true;
}
function ValidateFields(){
//Validate all Required Fields
if (RequiredTextValidate()&& CheckDateTime()&& ReasonAbsenceValidate()&&
ReturnDateChanged() && FirstDateChanged() && ActualDateChanged())return true;
}
</script>
update function like following:
You need to return flase in case of invalid input to prevent form from being posted.
function ValidateFields() {
//Validate all Required Fields
if (RequiredTextValidate() && CheckDateTime() && ReasonAbsenceValidate() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged()) {
return true;
} else {
return false;
}
}
Update
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value != '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
condition seems to be wrong. It should be like following.
if (document.getElementById("<%=SickTimeTextBox.ClientID %>").value == '' &&
!document.getElementById("<%=SickTimeTextBox.ClientID %>").value.match(re))
Use == instead of != operator.

How to validate multiple checkbox with javascript

I have simple page with multiple check boxes and radio buttons, This is only validating the first system check box and skipping over the next comm check box. I'm fairly new to js and I'm sure this is a simple fix. Any assistance would be appreciated thanks!!!
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
return false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
return false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
return false;
}
return true;
}
How can I get this to validate multiple check boxes? Will I also need to apply the same fix for multiple sets of radio buttons?
I think the problem is that you're returning from the function too soon. Try this:
function test() {
var valid = true;
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
valid = false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
valid = false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
valid = false;
}
return valid;
}
This way, it validates everything you want, alerts what you need, and returns the validity like you expect.
Another option, which instead of alerting for each validation, you can do something like this:
function test() {
var valid = true;
var messages = [];
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
messages.push('Please select System Access');
valid = false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
messages.push('Please choose a Department');
valid = false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
messages.push('Please select Comm Access');
valid = false;
}
if (messages.length > 0) {
alert(messages.join("\n"));
}
return valid;
}
In this case, you get one alert at the end with all the errors. Might be nicer for the user.
<script defer="defer" type="text/javascript"><!--function validateForm(formElement) {
if (formElement.first_name.value.length < 2)
return focusElement(formElement.first_name,
'Please enter a First Name that is at least 2 characters long.');
if (formElement.last_name.value.length < 2)
return focusElement(formElement.last_name,
'Please enter a Last Name that is at least 2 characters long.');
if (formElement.model_id.value.length < 7)
return focusElement(formElement.model_id,
'Please enter a Model ID that is at least 7 characters long.');
if (countSelected(formElement, 'checkbox', 'system[]') == 0) {
alert('Please select System Access');
return false;
}
if (countSelected(formElement, 'radio', 'department') == 0) {
alert('Please choose a Department');
return false;
}
if (countSelected(formElement, 'checkbox', 'comm[]') == 0) {
alert('Please select Comm Access');
return false;
}
return true; } function focusElement(element, errorMessage) {
alert((errorMessage.length > 0) ? errorMessage :
'You did not enter valid data; Please try again');
if (element.select) element.select();
if (element.focus) element.focus();
return false; } function countSelected(formElement, inputType, inputName) {
if (inputType == null) inputType = 'checkbox';
var returnValue = 0;
for (var loopCounter = 0; loopCounter < formElement.length; loopCounter++) {
var element = formElement.elements[loopCounter];
if (element.type == inputType && element.checked == true) {
if (inputName.length > 0)
if (element.name == inputName)
returnValue++;
else
returnValue++
}
}
return returnValue; } function countSelectedOptions(selectElement) {
var returnValue = 0;
for (var loopCounter = 0; loopCounter < selectElement.options.length; loopCounter++)
if (selectElement.options[loopCounter].selected == true)
returnValue++;
return returnValue;
}
//-->

Javascript showing alert without refreshing the page

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

Categories

Resources