How do I enable cancel button with form validation? - javascript

I'm using the frmvalidator javascript found here for my code.
I had to create a custom validation because I'm validating two input fields with the same id (I'm using an array). The validation is working, the problem now though is when I click the cancel button, the validation still takes effect meaning I can't close the dialog box unless I fill in all fields.
Here's my code:
<form name="UpdateIndustry" action="addIndustry.jsp" method="get">
<table align="center">
<c:forEach var="row" items="${paramValues.industries}">
<jsp:setProperty property="tableId" name="bean" value="${row}"/>
<c:set var="ctr" value="${ctr + 1}"/>
<input type="hidden" name="hello" value="${row}"/>
<tr><th>INDUSTRY NAME</th>
<td><div id='UpdateIndustry_industryName_errorloc' style="color:red;"></div>
<input type="text" name="industryName" size=40 value="${bean.thisIndustry.INDUSTRYNAME}"/></td></tr>
</c:forEach>
<input type="hidden" name="finalCount" value="${ctr}"/>
<tr><td style="text-align:center" colspan="3">
<input type=submit name="submit" value="Update Industry" onclick="btnUpdate_click()"/>
<input type=submit name="submit" value="Cancel" onclick="btnCancel_click()"/></td></tr>
</table>
</form>
and the script:
<script language="JavaScript">
var frmvalidator = new Validator("UpdateIndustry");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
function btnUpdate_click(){
frmvalidator.setAddnlValidationFunction(FinalValidator); }
function btnCancel_click(){
frmvalidator.clearAllValidations();
window.close(); }
</script>
and here's the FinalValidator function, where the validation happens.
function FinalValidator()
{
var myForm = document.forms["UpdateIndustry"];
if (myForm.industryName.length > 0) {
for(var i=0; i <= myForm.industryName.length; i++)
{
if(myForm.industryName[i].value.length == 0)
{
sfm_show_error_msg('Please enter industry name.', myForm.industryName[i]);
return false;
}
}
}
return true;
}
How can I get the cancel button to work? Thanks in advance for the help! :)

$(document).ready(function () {
$("#YourButtonID").click(function () {
error = false;
$(".span1").remove();
if ($("#YourTextBoxID").val() == "") {
$("#YourTextBoxID").after("<span class='span1'>Write Your Error</span>");
error = true;
}
});
});
Try this.

Related

Add more/remove functionality is throwing out of validation

I am trying to submit a form in that I have Addmore functionality in it.
Example: I have entered name and then I have used addmore button so now remove appeared in second tr.
When I click the remove that tr is removed now, but when click the form submit button it is skipping the phone number validation,
so to remove the functionality is throwing out validation.
My html somewhat looks like this:
<form>
Name<input type="text" name="name" id="name" placeholder="Name Your Name "/>
<table class="skillsTable" id="jobSkills">
<tbody>
<tr class="gdskilltr">
<td><button type="button" class="addSkills"> Add Skill</button></td>
<td><button type="button" class="removeSkill"> Remove Skill</button></td>
</tr>
</tbody>
</table>
phone<input type="text" name="phone" id="phone" placeholder="enter Your phone "/>
<button type="submit" id="JobSubmit">Submit</button>
</form>
And here my Javascript validation starts:
var skillcount = 1;
$(".addSkills").click(function () {
$('#jobSkills tr:last').after('<tr class="gdskilltr "><td></td></tr>');
skillcount++;
});
$("#jobSkills").on('click', '.removeSkill', function () {
$(this).parent().parent().remove();
});
$("#JobSubmit").click(function () {
if ($("#name").val() == '') {
$("#warning_message").html('Please Enter name');
$("#name").focus();
return false;
}
if ($("#phone").val() == '') {
$("#warning_message").html('Please Enter name');
$("#phone").focus();
return false;
}
}

How can I pop up a message box according to the button-clicked condition?

There is a form containing two buttons. And then I suppose that when I click different buttons, a relevant message box will be popped up. Once the button is clicked, it will trigger a further action called "Approval".
However, at the current situation, the alert box only shows one status. I know the current status are getting the same ID and it is a wrong operation. But I don't know the solution now. Could anyone help me?
I looked into this ref: Form onSubmit determine which submit button was pressed, but could not quite understand the concept the solution provided.
<script type="text/javascript" language="javascript">
function ConfirmOnDelete() {
var a = document.getElementById('a_action').value; //I want to change this
if (a == "Approve")
{
if (confirm("Are you sure to approve?") == true)
return true;
else
return false;
}
else
{
if (confirm("Are you sure to delete?") == true)
return true;
else
return false;
}
}
</script>
<form id="Batch" action="Approval" method="post" onsubmit="return ConfirmOnDelete();">
#<text>
#If ViewBag.unapprovedCount > 0 Then
#<div style="float: left;">
<br />
<input type="hidden" name="batch_action" value="Delete" />
<input type="hidden" id="a_action" name="additional_action" value="Delete" />
<input type="submit" id="submit4" name="submit" class="button" value="Delete" style="width:100px;">
</div>
End If
#If ViewBag.unapprovedCount > 0 Then
#<div style="float: right;">
<br />
<input type="hidden" name="batch_action" value="Approve" />
<input type="hidden" id="a_action2" name="additional_action" value="Approve" />
<input type="submit" id="submit3" name="submit" class="button" value="#ViewBag.batch_action" style="width:100px;">
</div>
End If
</text>
</form>
On your #a_action element, you can add a data-* attribute and do some magic.
<input type="hidden" id="a_action" name="additional_action" value="Delete" data-value="Approve" />
Notice at the end it says data-value="Approve". Now you can grab that value like this:
var a = document.getElementById('a_action').getAttribute('data-value');
And check if the value is equal to something, just like in your example.
if (a == "Approve") {
//This would be true in this example, as data-value == "Approve"
}
Was this was you were looking for?
The reason you are only getting one status is because
var a = document.getElementById('a_action').value; //get by Button click
retrieves the value based on ID. ID should be unique, but both of your inputs have the id a_action. So the getElementById only returns the first value, in this case that is Delete.
What you can do is the following
Instead of binding `ConfirmOnDelete' on the form, you can bind in on the buttons and pass the action as an argument.
See this fiddle https://jsfiddle.net/j3rvter5/1/
notice the addition of { and }in your code. that's the correct syntax for javascript if statement.
UPDATE
you want to call the ConfirmOnDelete()depending on which button the from was submitted with, either the approve or delete. forgive me for using jquery
$("#Batch").on("submit", function() {
// Does the element have focus:
var hasApproveFocus = $("input[id='submit3']").is(':focus');
var hasDeleteFocus = $("input[id='submit4']").is(':focus');
//checking which of the submit button has focus to determine which was click on submit
if (hasApproveFocus == true) {
if (confirm("Are you sure to approve?") == true) {
return true;
} else {
return false;
}
} else if (hasDeleteFocus == true){
if (confirm("Are you sure to delete?") == true) {
return true;
} else {
return false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="Batch" action="Approval" method="post">
<div style="float: left;">
<input type="submit" id="submit4" name="submit" class="button" value="Delete" style="width:100px;">
</div>
<div style="float: right;">
<br />
<input type="submit" id="submit3" name="submit" class="button" value="Approve" style="width:100px;">
</div>
</form>
This is the solution I achieved.
<script type="text/javascript">
function question_submit(input) {
if (input == 1)
{
if (confirm('Are you sure you want to delete?')) {
document.getElementById("action").value = "Delete";
$('#Batch').submit();
}
else {
alert('You have not submitted this form');
}
}
else {
if (confirm('Are you sure you want to approve?')) {
document.getElementById("action").value = "Approve";
$('#Batch').submit();
}
else {
alert('You have not submitted this form');
}
}
}
</script>
<form id="Batch" name="myform" action="BatchApproval" method="post" >
<input id="action" type="hidden" name="batch_action" />
<div style="float: left;">
<br />
<input type="button" id="submit4" name="submit4" class="button" value="Delete" style="width:100px;" onclick="question_submit(1)">
</div>
<div style="float: right;">
<br />
<input type="button" id="submit3" name="submit3" class="button" value="Approve" style="width:100px;" onclick="question_submit(2)">
</div>
</form>

Newbie: Need explanation of a Js function

So I am doing a HTML and JavaScript related assignment which I am not required to have any prior knowledge of these scripting and programming languages. I was required to produce a document explaining how HTML and JavaScript brings about an entry form, and how JavaScript does validation check etc.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" /> : AS<br />
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
There's a task where I need to create 3 additional radio buttons for different level entries and then I was required to create a function which does a confirmation check, to ask the user to either confirm or cancel the choice after they have selected on a specific level entry. As I do not have any prior knowledge of programming(or I have learnt a little during the course of my assignment), I do not know how to create a function. Therefore, I googled it and found this page (It's the same assignment btw) From what I know from this page, I am required to change the radio buttons into:
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
and implement a function as such:
function confirmation() {
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an option');
return false;
} else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
And great now I have done what it said, there's now an alert box which pops out and confirms choice of radio button with the user, so clicking on the radio button will trigger an onclick event which returns the function. Now my question is how does this function do the confirmation check?
(I am sorry if I wrote too much, my previous post was put on hold by as too broad by a few of people, because I wasn't being clear enough what I am suppose to say.)
Just add result &= confirmation(); in your validation code. Some where between your two if statements.
You need to watch the click event and determine whether or not you want to permit the action:
$(document).ready(function () {
$('input[type="radio"]').on('click', function () {
var r = confirm("Are you sure?");
if (r == true) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
}
});
});
http://jsfiddle.net/LTQ9p/1/

Form submit button does not work in Firefox but works in Chrome or IE

I have a form with some input fields and a submit button. The form should submit to a servlet.
When I hit submit/return, everything is fine in Chrome or IE, but it does nothing on Firefox. Any idea about the issue?
HTML:
<body>
<div align="center">
<form>
<table cellpadding ='2' border ='0'>
<tr>
<td>
<label for="Database">Database</label>
</td>
<td>
<input id="database" type="text" onchange="setdirtybit()" name="Database" style="width:200px"></input>
</td>
</tr>
<tr>
<td>
<label for="Script">Script</label>
</td>
<td>
<input id="script" type="text" onchange="setdirtybit()" name="Script" style="width:200px"></input>
</td>
</tr>
</table>
<br />
<input type ='submit' value='Submit' onclick='Close()'></input>
</form>
</div>
</body>
JavaScript:
function Close()
{
window.returnValue = "";
if(window.dirtyFlag)
{
document.forms[0].method="post";
document.forms[0].action="/nbreports/updates/";
document.forms[0].submit();
window.returnValue = getValue('database') + '/' +
getValue('script') ;
}
window.close();
}
function getValue(varName)
{
if(document.getElementById(varName) == null)
return "";
if(document.getElementById(varName).value == null)
return "";
else
return document.getElementById(varName).value;
}
function setdirtybit()
{
window.dirtyFlag = 1;
}
$('#mytextfield').change(function(e) {
$('input[type=submit]').focus();
});
put an Id on your submit button, them do like this:
$(document).ready(function(){
$('#submitButtonId').click(function(){
var url = 'myServletUrlHere';
var data = $('form').serialize();
$.ajax({
type: 'POST',
url: url,
data: data,
success: alert("It worked!")
});
});
});
I am not sure but I do know that the following form does not work in Firefox but it works in all the other browsers:
<form method="POST">
<textarea rows="4" cols="60" name="body"></textarea><br>
<input type="submit" value="Submit">
</form>
It's like the submit button doesn't even process the mouse clicks.

Enter key hook with html form

I implemented form in HTML:
<form id="loginForm" action="/?do=login" method="post" >
<table width="50%" border="0">
<tr>
<td colspan="2">
<span id="LoginErr"></span>
<div>Login:</div>
<input id="Login" type="text" maxlength="32" name="Login" value="{VAR %LOGIN}"/>
</td>
</tr>
<tr>
<td valign="bottom">
<span id="PasswordErr"></span>
<div>Passoword:</small></div>
<input id="Password" type="password" maxlength="128" name="Password" value=""/>
</td>
</tr>
<tr>
<td>
Enter
</td>
</tr>
</table>
</form>
This is the check and post function (using jQuery):
function checkLogin()
{
var focused = false;
function report_error(field, err)
{
$('#' + field + 'Err').html(err);
if (!focused)
{
$('#' + field).focus();
focused = true;
}
}
$('#LoginErr').html('');
$('#PasswordErr').html('');
$login = jQuery.trim($('#Login').val());
$password = jQuery.trim($('#Password').val());
if ($login.length == 0)
report_error('Login', 'The login field is empty!');
if ($password.length == 0)
report_error('Password', 'The password field is empty!');
if (!focused)
$('#loginForm').submit();
}
But I have trouble with enter key. When i press this key form is posted without my javascript check.
I need call my function when enter key is pressed and no more action.
Thanx!
Update:
Correct code is:
in form tag need add: onSubmit="return checkLogin()
in javascript if (!focused) $('#loginForm').submit(); need change on return !focused;
Thanks to rdamborsky.
use onSubmit form event:
$(function() {
$('#loginForm').onSubmit = checkLogin;
});
It will be called just before your form's data are actually sent whatever triggers the submit event (click on button, pressing enter within one of fields...)

Categories