I have problem with my checkbox validation on my Tip Area Soccer Game. So if the user likes to tip a game, he must have to use 2 inputs field and the confirmation checkbock. But if the user uses 2 inputs fields and "more than one" confirmation checkbox, then he must get an alert error message. Because the right combination consists from "2 input fields + confimration checkbox" Here, in my screenshot you see the right combination for the green submit button:
And in the second screenshot you see the error combination:
I don't have any idea of how to code the alert for the error message on the display if the user uses the second combination.
Here's my Javascript code:
function chkAddTip(){
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
// boolean flag
var foundValid = false;
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length && !foundValid; i += 3){
if (inputs[i].type !== "submit" && (inputs[i].value && inputs[i + 1].value && inputs[i + 2].checked)) {
// set the flag to true when a valid bet is found
foundValid = true;
}
}
// determine the return value depending on the flag
if (foundValid) {
return true;
}
else {
alert("Bitte deinen Tipp und die Bestättigung abgeben.")
inputs[0].focus();
return false;
}
And here my form code:
<form action="Ctipservlet" id="AddTip" onsubmit="return chkAddTip()" method="POST">
<div id="inhalt"><h1>Tip Area</h1>
<table>
<tbody>
<tr>
<th>Playdate</th>
<th>Playtime</th>
<th>Games</th>
<th>Your Tip</th>
<th>Confirmation</th>
</tr>
<tr>
<td>21.07.</td>
<td>19:30 Uhr</td>
<td>Schalke - Bayern</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a0" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b0" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check0"></td>
</tr>
<tr>
<td>22.07.</td>
<td>20:30 Uhr</td>
<td>Dortmund - Leverkusen</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a1" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b1" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check1"></td>
</tr>
<tr>
<td>23.07.</td>
<td>15:30 Uhr</td>
<td>Wolfsburg - Nürnberg</td>
<td><input style="width:30px!important; text-align: center;" type="text" name="team_a2" maxlength="2" size="2">:<input style="width:30px!important; text-align: center;" type="text" name="team_b2" maxlength="2" size="2"></td>
<td><input type="checkbox" name="check2"></td>
</tr>
</tbody>
</table>
<input class="button_green" type="submit" name="tip" value="Submit Tip">
<input class="button_blue" onclick="this.form.onsubmit = null" type="submit" name="back" value="Back">
</div>
</form>
I hope someone have idea for this checking
We talked in chat, looked at this. Below is my solution but first... this is badly structured. You are doing validation and form submission in one step. I would break it up in to more then one. It just makes debugging/extension easier in the long run. I would validate inputs first. Save into object. Send to submit function. Then submit to DB. This right now is trying to do all that in one function. Anyway....
The problem is the loop for checking if there are inputs. When it finds the first true result it will call a submit and exit the function.
That's why you can input 2 fields, a checkbox and other checkboxes and foundValid is true.
My fix was to check for invalid input first. Have an outer boolean as an error. If it passes it submits. The only issue with it right now is empty fields will return a true condition and submit. Check the JS Fiddle http://jsfiddle.net/Komsomol/EDdUU/4/
var error = false;
var results = [];
function chkAddTip() {
var inputs = document.getElementById('AddTip').getElementsByTagName('input');
console.log(inputs);
// early exit the loop if at least one valid bet has been found
for (var i = 0; i < inputs.length; i += 3) {
if (!inputs[i].value && !inputs[i + 1].value && inputs[i + 2].checked) {
console.log("inputs inputed wrong!");
error = true;
} else {
results.push(inputs[i].value,inputs[i + 1].value,inputs[i + 2].checked);
}
}
submit();
}
function submit(){
console.log(results, error);
if(error == true){
alert("error in inputs");
} else {
alert("posting to server");
}
}
Related
I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance
Nvm it only works with addEventListener
I am using the following code to try to autofill my daily hours at the company Ι'm working at.
(function() {
'use strict';
//debugger;
var date = document.querySelector("#filter_day").value
var alreadyRun = GM_getValue(date, false);
if (!alreadyRun) {
GM_setValue(date, true);
document.querySelector("#fstjid_1").selectedIndex = 5;
document.querySelector("#time_start_MM_1").setAttribute('value', "00");
document.querySelector("#time_start_HH_1").setAttribute('value', "10");
document.querySelector("#time_end_MM_1").setAttribute('value', "00");
document.querySelector("#time_end_HH_1").setAttribute('value', "19");
document.getElementById("save_btn").click();
}
})();
For some reason though, when setting the hourly fields with the script and clicking the save button (whether the script does it manually οr not), the form isn't sent, the page is simply refreshed and values are cleared.
It seems as though there is something different between setting the hourly fields manually and when the script sets it, though I cannot say why.
I tried using setAttribute as well as simply .value=. I tried using double brackets " as well as a single '. Nothing seems to work and analyzing the HTML there's nothing special about these fields as far as I can tell.
The table's HTML:
<table border="0" dir="rtl" width="100%" cellspacing="0" cellpadding="0" style="table-layout:fixed;color:#4e546d ">
<tbody>
<tr iminnertable="true">
<td rowspan="99" style="BORDER-RIGHT: #80a3a8 1pt solid;text-align:center" major="1" dir="ltr" align="center" nowrap=""><input class="input_text_fix" type="text" name="time_start_HH_1" id="time_start_HH_1" value="10" maxlength="2" fieldname="time_start_HH" caption="" style="width:22.0;background-color:#f8f8fb; " onkeypress="return !(window.event && window.event.keyCode == 13);"
onkeyup="if(event.keyCode!=9) if(this.value.length>=2) this.nextSibling.nextSibling.focus()" onchange="flag_touched(this);" tabindex="10">:<input type="text" class="input_text_fix" name="time_start_MM_1" id="time_start_MM_1" value="00" maxlength="2"
fieldname="time_start_MM" caption="" onkeypress="return !(window.event && window.event.keyCode == 13);" style="width:22.0;background-color:#f8f8fb; " onchange="flag_touched(this);" tabindex="10.5">
</td>
<td rowspan="99" style="BORDER-RIGHT: #80a3a8 1pt solid;text-align:center" major="1" dir="ltr" align="center" nowrap=""><input class="input_text_fix" type="text" name="time_end_HH_1" id="time_end_HH_1" value="19" maxlength="2" fieldname="time_end_HH" caption="" style="width:22.0;background-color:#f8f8fb; " onkeypress="return !(window.event && window.event.keyCode == 13);"
onkeyup="if(event.keyCode!=9) if(this.value.length>=2) this.nextSibling.nextSibling.focus()" onchange="flag_touched(this);" tabindex="10">:<input type="text" class="input_text_fix" name="time_end_MM_1" id="time_end_MM_1" value="00" maxlength="2"
fieldname="time_end_MM" caption="" onkeypress="return !(window.event && window.event.keyCode == 13);" style="width:22.0;background-color:#f8f8fb; " onchange="flag_touched(this);" tabindex="10.5">
</td>
<td align="center" rowspan="99" style="BORDER-RIGHT: #80a3a8 1pt solid;text-align:center" major="1" val="9.00">
<input type="text" dir="rtl" name="work_hours_1" value="9.00" class="tableDyn" fieldname="work_hours" style="direction:rtl;width:44;background-color:#f8f8fb;font-size:11px;; border:none;" readonly="" tabindex="10"></td>
<td style="display:none;width:0" rowspan="99" major="1"><input type="hidden" name="units_1" id="units_1" value="" fieldname="units"></td>
</tr>
</tbody>
</table>
The save button ΗΤΜL:
<input class="button_free_width" id="save_btn" type="button" onclick="try{dontPopWarn=1;submit();this.disabled=true;if (save_btn_1) save_btn_1.disabled=true;}catch(e){;}try {document.getElementById("loadingmsg").style.visibility = "visible";document.getElementById("loadingmsg").display = "block";} catch(e) {;}"
value=" שמור " name="right">
One thing may prevent your code from working.
On every input there is onchange="flag_touched(this);" which may cause the web page to store the current value in some internal JavaScript state. That means you have to manually dispatch a change event on the inputs in order to mimic a user input.
Try using a function like this to effectively change the value of the inputs:
function changeInputValue(element, value) {
if (element instanceof HTMLInputElement) {
element.value = value;
}
else if (element instanceof HTMLSelectElement) {
element.selectedIndex = value;
}
element.dispatchEvent(new Event('change', { bubbles: true }));
}
The submit button has some JavaScript on the click event, but it's not of type="submit" so it doesn't behave like a native submit button, then the document.getElementById("save_btn").click(); line should be enough to mimic a user interaction with this button.
If that doesn't work, you should check for potential "JavaScript registered" event listeners (with addEventListener) on the inputs and the submit button, and add them to the question.
Can anyone help me on my issue, it seems that my loop doesn't work. I created a random number guessing game, and I wanted to have only 5 tries. And once it hits the 5th try, it will display a message. But it seems that I was able to do it countless time.
function RandomNumber()
{
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
var maxtries=5;
for(var i=0;i<=maxtries;i++)
{
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
else if (i==maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
}
}
This is my <form> codes
<td style="text-align:center">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()"><br/>
<br/><span id="numbers1"></span>
</td>
</tr>
<tr>
<td style="text-align:center">
<br/><input id="rand" type="submit" value="submit" onclick="Random()" disabled><br/>
<input id="guess" type="text" value="Random Number Generator">
</td>
</tr>
<tr>
<td style="text-align:center">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</td>
There's a couple problems here. The first and biggest (maybe) is that your loop counts down right away and doesn't give the guesser a chance to make another guess. The second problem is that the 3rd if statement that checks for the number of guesses can never be reached. I have refactored this check to the beginning on the function.
You should call RandomNumber when the user submits a new guess
You can fix this like:
function RandomNumber()
{
if (!this.guesses) {
this.guesses = 1;
} else {
this.guesses++;
if (this.guesses > 5) {
document.getElementById("correct").innerHTML="No more tries";
return; // max guesses exceeded
}
}
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
}
Right now, your loop runs 6 times in a row. What you want is no loop at all, but a simple counter that can keep track of how many guesses have been made and when the count reaches the max, the guessing is over.
Other Notes:
You seem to have an excessive amount of input elements and since
this is just a game and you are not actually submitting the data
anywhere, you shouldn't be using submit buttons and adding name
attributes to the form fields.
You should not be using tables for page layout - - that's the job of
CSS.
Don't use .innerHTML when you aren't working with strings that
contain HTML as .innerHTML has security and performance
implications. Use .textContent instead.
Don't use inline HTML event attributes. Do you JavaScript separately
from your HTML.
Don't use self-terminating syntax.
const checkAnswer=document.getElementById("guessing");
const d1= document.getElementById("digit1");
const d2= document.getElementById("digit2");
const guess = document.getElementById("guess");
const rand = document.getElementById("rand");
const result = document.getElementById("correct");
const maxtries=5;
let count = 1;
let answer = null;
d2.addEventListener("blur", function(){
rand.removeAttribute("disabled");
});
rand.addEventListener("click", function(){
console.log(d1.value, d2.value);
answer = Math.floor(Math.random() * (d2.value - d1.value + 1) + d1.value);;
console.log(answer);
});
checkAnswer.addEventListener("click", randomNumber)
function randomNumber() {
if(count < maxtries){
if(guess.value == answer){
result.textContent="Correct";
} else {
result.textContent="Guess " + count + " Not correct";
}
count++; // Increase the counter
} else {
result.textContent="No more tries";
}
}
<div>
Lowest number: <input id="digit1" type="text">
<br><span id="numbers"></span>
</div>
<div>
Highest number: <input id="digit2" type="text">
<br><span id="numbers1"></span>
</div>
<div>
<input id="rand" type="button" value="Generate Random" disabled><br>
</div>
<div>
Enter your number<br>
<input id="guess" type="text"><br>
<input id="guessing" type="button" value="Check Answer"><br>
<span id="correct"></span>
</div>
I am trying to get an alert whenever a user clicks on the username or password input field and exits it without entering. However, I am able to get this to work after using "onblur" instead of "onfocus" (Thanks to Gurvinder's answer below). Now, the alert seems to work for both the fields when I click outside of the form using "onfocus". However, when I use tab key to get to password field from username field to password field, the "passwordCheck" function keeps running. Please help.
<!DOCTYPE html>
<html>
<head>
<title>Javascript exercises</title>
<meta charset="UTF-8">
</head>
<body>
<form name="myForm" >
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onfocus="userNameCheck();"></input></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id ="password" type="password" onfocus="passwordCheck();"></input></td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input></td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if(document.myForm.username.value == ""){
alert("User Name cannot be blank");
}
else{
return false;
}
}
//password field validator - Alert a message for empty input fields
var passwordCheck = function() {
if(document.myForm.password.value == ""){
alert("Password cannot be blank");
}
else{
return false;
}
}
</script>
</body>
</html>
I want the username input to show an alert if the user clicks on it
and tabs to the next field without entering any data.
If you are using focus event to check for the input validity, then unless value is pre-populated, alert will keep coming.
Use blur event, onblur instead of onfocus.
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input></td>
Demo
<body>
<form name="myForm">
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id="password" type="password"></input>
</td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input>
</td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if (document.myForm.username.length >= 1) {
//Nothing happens
} else {
alert("User Name cannot be blank");
return false;
}
}
</script>
</body>
Why not create your own 'alert' div for more control (and better user experience).
$("input").focus(function(){
var x = document.forms["myForm"]["password"].value;
if (x == "") {
/*alert("Password cannot be blank");*/
$('.alert').show();
return false;
}
});
And to specify tab key scenario, try:
function checkTabPress(key_val) {
if (event.keyCode == 9) {
$('.alert').hide();
}
}
I have a computing assignment to do.
I've done most I'm just stuck on this task:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<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 (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</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>
</html>
All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/
function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert