Change Button Text After Validating Fields Are Completed - javascript

My form includes a search that takes about 10 seconds. The submit button is titled SEARCH and upon clicking I have set this up to change to SEARCHING. This is the code:
<input type=submit class=button
value= Search
onclick="javascript:formSubmit();this.value='Searching...'">
But now I need to validate that an email field and another field are completed so that the button text changes to SEARCHING only if validated.
I tried this, but it does not work:
<input type=submit class=button
value= Search
onclick="myFunction();javascript:formSubmit();this.value='Searching...'">
<script>
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' )
alert('The number of adults must be more than zero!');
document.getElementById("myEmail").required = true;
document.getElementById("demo").innerHTML = "The required property was set. The email field must now be filled out before submitting the form.";
}
</script>
Here is the html of the two fields being validated:
<select name=numberadults class=cboStyleZ>
<option value=0 selected>
0
</option>
<option value=1>
1
</option>
<option value=2>
2
</option>
<option value=3>
3
</option>
<option value=4>
4
</option>
<option value=5>
5
</option>
<option value=6>
6
</option>
<option value=--->
---
</option>
</select>
<input type="email" id="myEmail" class=cboStyleZ1 name="eaddr"
placeholder="Your email is all we need">

<script>
function myFunction() {
//other statements if required
document.getElementById("search").value = "searching";
}
</script>
<input type=submit class=button id="search"
value="search";
onclick="myFunction()">
I think this code can help you

The following click handler:
onclick="myFunction();javascript:formSubmit();this.value='Searching...'"
doesn't indicate how the validation in myFunction would affect the form submission and the text change.
There are several ways to skin a cat here, but in general, you could rely on control structures like if or using short-circuit operators to change the execution flow based on the value of an expression that interests you (e.g.: the return value of myFunction())
HTML
onclick="if(myFunction()) { javascript:formSubmit();this.value='Searching...'} "
JS
function myFunction() {
if ( document.getElementsByName('numberadults')[0].value == '0' ) {
// ...
// Display what is wrong with the form to the user
// ...
return false;
}
return true;
}

Related

why does my submit button not do anything?

I have created two html pages; main info, and Entrance page. the Entrance page is supposed to act similar to a password so that under aged users do not enter the page. problem is my submit button is not doing anything. I would highly appreciate if somebody could help me get it to work since I need to finish it today.
Here is the code I have so far:
<html>
<head>
<!-- this is how you add a code comment-->
<title> Entrance Page </title>
</head>
<body bgcolor="#CEF6F5">
<form>
<h2 align=center><u> Please fill out the following information to proceed to the festival: </u></h2>
<br><br>First Name:<input type="text" name="First Name" id="first"> Last Name:<input type="text"
name="Last Name" id="last">
<br><br> age:<select name="age" id="age">
<option value="1"> below 10 </option>
<option value="2"> 10 </option>
<option value="3"> 11 </option>
<option value="4"> 12 </option>
<option value="5"> 13 </option>
<option value="6"> 14 </option>
<option value="7"> 15 </option>
<option value="8"> 16 </option>
<option value="9"> 17 </option>
<option value="10"> 18 </option>
<option value="11"> 19 </option>
<option value="12"> 20 </option>
<option value="13"> above 20 </option>
</select>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p align="center"> <button type="submit" onclick="run()"> Submit </button> </p>
<p><p id="p1"> </p>
<script>
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
var age = document.getElementById("age").value
var isNum = " ";
isNum = isNum + isNaN(firstName)
function run() {
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
if (age < 10 ) {
window.alert("your too young to enter in this event!")//go back to Entrance page
} else if (age > 10) {
window.alert("welcome to the Oktoberfest website!");
window.location.replace("Cost%20of%20an%20Event.html");//go to main website
} else if (age == 10) {
window.alert("lucky! you are just barely old enough to join!")
window.location.replace("Cost%20of%20an%20Event.html");//go to main website
}
}
if (isNum == true) {
window.alert("your name cannot be a number");
}//go back to Entrance page
while (firstName.length ==0) {
window.alert ("you didn't enter a first name ")
document.getElementById("block").value//go back to Entrance page
while (lastNamet.length ==0) {
window.alert ("you didn't enter a last name ")
document.getElementById("block").value//go back to Entrance page
</script>
</body>
</html>
Because your submit button is outside of your form element. This is allowed, but you'd need to add form="id of form here" to associate it with the form.
Even if you fix this issue, all that will happen is that your page will refresh because you also need to specify an action and a method for your form so that it knows how and where to submit the form data.
Learn about the form element here.
You've also got several other problems:
You don't have closing brackets at the end of each of your while
blocks. Your while loops run immediately (before the user has had a
chance to input anything into the form) and so they immediately cause
alert() messages and get you into an infinite loop. You should
probably stay away from while and just check the input in the
submit event of the form and if the input isn't right, display
your error - - no need for a loop.
And your use of HTML is incorrect in several places:
The bgcolor and align attributes are deprecated. All formatting
should be done with CSS, not HTML.
The heading elements (h1, h2, etc.) are for defining sections of
the document. They should not be used because of the formatting
applied to the text within them. As such, you shouldn't have an h2
if you aren't creating a sub-section of an h1, which you are not.
The <br> element should not be used to create artificial vertical
white space. Again, CSS is for layout and styling. br is meant to
force a line break between content, not for introducing blank lines.

Is there a way to disable a dropdown to users while still being able to submit a form with the disabled dropdown?

I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;

How to make the chosen value of select list visible

How I can make the selected choice still visible until I re-choose another one?The list may contain more than 10 options
=====
<form method="get" action="Chairman.php" >
<select name="courses" id="courses" class="styled-select" >
<option value="courses"><--Courses--></option>
<option value="PHYS220">Physics for Engineers</option>
<option value="MATH210">Calculus II</option>
<option value="MATH225">Linear Algebra with Applications</option>
</select>
<input type="submit" value="Search Instructor"
onClick="checkDropdown()"></input>
<div id="error" style="color:red"></div>
=====
Also when I am trying to validate the select list,The error is displayed and then quickly it disappears
<script>
function checkDropdown () {
var courses = document.getElementById('courses');
if(courses.value==="courses") {
document.getElementById('error').innerHTML="PLEASE selecttt";
return false;
}
}
</script>
The select is reset and the error disappears because the form is still posted. The value that you return from the function doesn't stop the submission.
You should use the onsubmit event on the form instead of onclick on the button. Use return in the event code to convey the value from the function back to the event:
<form method="get" action="Chairman.php" onsubmit="return checkDropdown()">

Validate a form without submitting

I have the following code that checks to see that two select fields are identical. The code works alright when called with onsubmit. However after doing this validation the form is still submitted. How can i prevent the script or my form from submitting the incorrect data.
Please see code below:
var fieldalias="Email address field"
function verify(element1, element2) {
var passed=false
if (element1.value=='') {
alert("Please fill out the "+fieldalias+"!")
element1.focus()
}
else if (element2.value=='') {
alert("Please verify the "+fieldalias+"!")
element2.focus()
}
else if (element1.value!=element2.value) {
alert("The two "+fieldalias+"s do not match")
element1.select()
}
else
passed=true
return passed
}
You didn't include your HTML, so I'm going to assume you've added onsubmit() to your form element.
If so, make sure your call looks like this:
onsubmit="return verify(element1, element2)"
(replace element1 and element2 accordingly)
If this assumption is not correct, please include some additional detail so we can better assist.
Try calling stopImmediatePropagation() on the event to prevent any further processing of the submit event by any other handlers in the form element or higher level elements.
Call that code with different event, like i.e: onchange, or onfocusout. This way the validation will be performed every time user enter some values to your fields, certainly before submitting.
EDIT:
I'm not sure if I understand you correctly but I would have attached your JS code this way:
First assign your select box to the variable:
var object_input = document.getElementById("selectId");
And then:
if(object_input.addEventListener)
{
object_input.addEventListener('blur', focus_lost);
object_input.addEventListener('keypress', checkForEnter);
}
else
{
object_input.attachEvent('onblur', focus_lost);
object_input.attachEvent('onkeypress', checkForEnter);
}
and then perform your validation ith focus_lost or checkForEnter.
Assuming that in the html code you have something like this:
<form action="test2.html" method="post" onsubmit="return verify(e1, e2);">
<input type="text" name="e1" /><br/>
<input type="text" name="e2" /><br/>
<input type="submit" value="Validate" />
</form>
You have to put in onsubmit event:
return verify(e1, e2);
so you will not go to the submiting page if the data is not valida
EDIT:
I think the problem is the
element1.select()
in the 3rd if, that this select method does not exist for a select object.
You can use a
element1.focus()
The code that will work is:
var fieldalias="Email address field"
function verify(element1, element2){
var passed=false;
if (element1.value==''){
alert("Please fill out the "+fieldalias+"!");
element1.focus();
}
else if (element2.value==''){
alert("Please verify the "+fieldalias+"!");
element2.focus();
}
else if (element1.value!=element2.value){
alert("The two "+fieldalias+"s do not match");
element1.focus();
}
else
passed=true;
return passed;
}
And
<form action="test2.html" method="post" onsubmit="return verify(document.getElementById('e1'), document.getElementById('e2'));">
<select id="e1">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<select id="e2">
<option value="One">One</option>
<option value="two">two</option>
<option value="Three">Three</option>
<option value="four">four</option>
</select><br/>
<input type="submit" value="Validate" />
</form>

Validating Multiple Textbox Date with jQuery Validate

I'm trying to write a custom method to validate a date. The date however exists in three text boxes. Furthermore, there may be multiple instances of this date.
<div class="customDate">
<input class="month" id="dob_Month" maxlength="2" name="dob.Month" type="text" />
/
<input class="day" id="dob_Day" maxlength="2" name="dob.Day" type="text" />
/
<input class="year" id="dob_Year" maxlength="4" name="dob.Year" type="text" />
</div>
On submit, I'd like to validate any div containing the customDate class. I.e. make sure all boxes have been filled, make sure ranges are correct, etc. I'm using the following code:
$.validator.addMethod("customDate", function(element) { return false;}, "error message");
The validation function isn't firing however. What am I missing? Also, is there a better way to do this.
Note: I've stubbed out the functionality for the actual validation logic. I just need to know how to get the validation method to fire.
I have managed to create multiple field validation without use of a hidden field by following the guide at
http://docs.jquery.com/Plugins/Validation/multiplefields and amending it accordingly
might be overkill though :)
html code
<div class="whatever">
<!-- dob html -->
<div id="dobdate">
<select name="dobday" class="dateRequired" id="dobday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="dobmonth" class="dateRequired" id="dobmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="dobyear" class="dateRequired" id="dobyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<div id="joinedate">
<!-- date joined html -->
<select name="joinedday" class="dateRequired" id="joinedday">
<option value="">Day</option>
<option value="1">1</option>
</select>
<select name="joinedmonth" class="dateRequired" id="joinedmonth">
<option value="">Month</option>
<option value="January">January</option>
</select>
<select name="joinedyear" class="dateRequired" id="joinedyear">
<option value="">Year</option>
<option value="2010">2010</option>
</select>
<div class="errorContainer"> </div>
</div>
<br />
<input name="submit" type="submit" value="Submit" class="submit" title="Submit"/>
</div>
jquery code
// 1. add a custom validation method
$.validator.addMethod("CheckDates", function(i,element)
{
// function with date logic to return whether this is actually a valid date - you'll need to create this to return a true/false result
return IsValidDate(element);
}, "Please enter a correct date");
// 2. add a class rule to assign the validation method to the relevent fields - this sets the fields with class name of "dateRequired" to be required and use the method youve set up above
$.validator.addClassRules({
dateRequired: { required:true, CheckDates:true}
});
// 3. add a validation group (consists of the fields you want to validate)
$("#myForm").validate(
{
submitHandler: function()
{
alert("submitted!");
},
groups:
{
dob: "dobyear dobmonth dobday", joined : "joinedyear joinedmonth joinedday"
},
messages: { dob : " ", joined : " " // sets the invidual errors to nothing so that only one message is displayed for each drop down group
},
errorPlacement: function(error, element)
{
element.parent().children(".errorContainer").append(error);
}
});
JavaScript code
function IsValidDate(_element)
{
// just a hack function to take an element, get the drop down fields within it with a particular class name ending with day /month/ year and perform a basic date time test
var $dateFields = $("#" + _element.id).parent();
day = $dateFields.children(".dateRequired:[name$='day']");
month = $dateFields.children(".dateRequired:[name$='month']");
year = $dateFields.children(".dateRequired:[name$='year']");
var $newDate = month.val() + " " + day.val() + " " + year.val();
var scratch = new Date($newDate );
if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date")
{
return false;
} else {
return true;
}
}
I would try triggering an event on form submit before the validation which appends the values from the individual day/month/year inputs together into a separate hidden input, and then validate the hidden input instead.
You add a hidden field
<input id="month" maxlength="2" name="month" type="text" />
<input id="day" maxlength="2" name="day" type="text" />
<input id="year" maxlength="4" name="year" type="text" />
<input id="birthday" name="birthday" type="text" />
then concatenate the values in the hidden, and validate that field.
$('#day,#month,#year').change(function() {
$('#birthday').val($('#day').val()+'/'+ $('#month').val()+'/'+ $('#year').val());
});
then validate the hidden value.
I'm pretty sure that the validation plugin only supports validating inputs, not arbitrary DOM elements. The elements function filters out anything that isn't an element as well as submit, reset, image buttons and disabled inputs.
What you'd want to do is have validators for month, day, and year. Month and day would need to reference each other's values in order to perform correct validation logic.

Categories

Resources