I am doing a form window before you get in the main website so I tried to make it so that if you don't fill any of the spaces it will open a window alert asking to fill those spaces. Plus I'd like that you would only get to the main website if you fill all the spaces but yet the button on the form window always takes to the main website without requiring filling of the camps.
On the button I wrote this:
<a href="index1.html">
<input type="button" value="Terminar" onclick = location.href='index1.html' >
</a>
and on the js window I wrote the window alert command to each one of the categories:
if(frm.name.value=="" || frm.name.value==null || frm.name.length < 3) {
alert("Please write your first name ")
frm.name.focus();
return false;
It seems you are trying to validate the an input field based on a few criteria.
Your question is not clear. Is this what you are trying to do?
function validateInput() {
if (frm.value == "" || frm.value == null || frm.value.length < 3) {
alert("Please write your first name ")
frm.focus();
} else
location.href = 'index1.html'
}
<input type="text" id="frm" placeholder="Please write your first name" />
<input type="button" value="Terminar" onClick="validateInput()">
You want something like this. In your code the input is wrapped in an a tag. so it will always trigger the event. Adding a button the trigger the event will help.
button = document.getElementById('enter');
input = document.getElementById('fill');
button.onclick = function() {
if (input.value == null || input.value == "" || input.value == " ") {
alert('Please write your first name');
} else {
window.location.href = 'index1.html';
}
};
<input id="fill">
<button id="enter">Enter</button>
Related
I've written a program that should display an image of a beverage or an alert window depending on the user's age input. The problem is that regardless of what value is submitted it only executes the 'if' portion of the statement. None of the other conditions are being checked prior to execution. I have tried using getElementById with the element id in place of querySelector but the program did not run at at all. I have tried querySelector with the button tag as well as trying the input tag. That also did not work.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.querySelector('age');
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'images/cola.jpg';
} else if (patronAge >= 21) {
primaryImg.src = 'images/tallboy.jpg';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (patronAge == NaN) {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src="images/bar&grill.png" alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
Instead of writing this:
let patronAge = document.querySelector('age');
you should write the following:
let patronAge = parseInt(document.querySelector('#age').value);
There are a few problems with your approach.
querySelector('age') looks for an element with tag age, this does not exist. Since you're using querySelector you need to specify a # symbol to search for an id.
You need to access the value of the HTMLElement
You need to parse the value as a number
couple of minor problems. They are pretty easy to spot. Look over the snippet and let me know if you don't understand anything.
function strt() {
let theButton = document.getElementById('aButton');
theButton.addEventListener('click', verifyAge);
}
function verifyAge() {
let patronAge = document.getElementById('age').value;
let primaryImg = document.getElementById('mainImg');
if (patronAge < 21) {
primaryImg.src = 'https://via.placeholder.com/120';
} else if (patronAge >= 21) {
primaryImg.src = 'https://via.placeholder.com/150';
} else if (patronAge <= 0) {
alert('Please enter a valid number:');
} else if (typeof(patronAge) == 'string') {
alert('That is not a valid number. Please try again.');
}
}
window.addEventListener('load', strt);
<img src='https://via.placeholder.com/100' alt="barandgrill" id="mainImg">
<br>
<form>
<label for="age">Please enter your age:</label>
<input type="text" id="age" required>
<button id="aButton" type="button">Get Drinks</button>
</form>
Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?
Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>
Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0
I'm having problems getting this code to validate when clicking on the login button.
** my html code **
<form action="abc.php"
method="post"
onsubmit="return jcheck();">
<div id="id_box">
<input type="text"
name="email"
id="id_text" placeholder="E-mail" >
<div id="pass_box">
<input type="password"
name="password" id="pass_text" placeholder="Password">
<div id="submit_box">
<input
type="submit"
id="sub_box"
onClick="click_event()"
value="Login">
my javascript code:
function click_event(){
jcheck();
function validate_ID(){
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
if (filter.test(email.value)==false
&& filter1.test(email.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else
return true;
}
function validate_Pass() {
var pass =document.getElementById('pass_text');
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). 4,}$/;
if (filter.test(pass.value)==false ) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else
return true;
}
function jcheck();
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length == 0) && (pas.length == 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");$("#p_asterics").html("*"); }
else if (name.length == 0)) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if ((pas.length == 0)) {
if(name.length != 0)
{
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
$("#p_asterics").html("*");
$('#warn_pass').html("Password Required");
}
}
return false;
}
For starters you should always indent your code so errors are easier to find. I helped you do a bit of indenting and there are a lot of problems in the code. One thing you are doing wrong is you need to close functions, else branches and html tags.
All HTML tags should end with an end tag or be closed immediately.
Example <div></div> or <div /> if you don't do this the browser may render your page differently on different browsers. You have missed this on your input tags you divs and your form tag. Perhaps you should check the whole html document for more of these errors.
Functions should in javascript should always look like this
function name(parameters, ...) {
}
or like this
var name = function(parameters, ...) {
}
the the name and parameters may vary but generally the function should look like this.
if statements else branches and else if branches should all have enclosing brackets for their code.
if () {
//code
} else if () {
//code
} else {
//code
}
If you do not close start and close else brackets the javascript will behave in very strange and unexpected ways. In fact i think your code might not even compile.
If you are using chrome please press Ctrl + Shift + J and look in the Console tab. You should see some error messages there. When you click the submit button.
Also using onClick on the submit button may be dangerous as I don't think this blocks submit. A better way to achieve the requested functionality is probably to either use a button type input and go with onClick or use the onSubmit function on the form. You are currently using both and its really no way to tell if click_event or jcheck will run first. Perhaps you should debug and see in which order the function calls happen. You can use chrome to debug by pressing CTRL + Shift + J and setting debug points in the Source tab.
You have a minor stylistic error as well where you compare the result of the regexp test() with false. The return value of test is already a Boolean and does not need to be compared.
Here is a guestimation of how the HTML should look. Its hard to say if its right as I have no more info to go on than your code and it has a lot of problems.
<form action="abc.php" method="post" onsubmit="return jcheck();">
<div id="id_box">
<input type="text" name="email" id="id_text" placeholder="E-mail" />
</div>
<div id="pass_box">
<input type="password" name="password" id="pass_text" placeholder="Password">
</div>
<div id="submit_box">
<input
type="submit"
id="sub_box"
value="Login" />
</div>
</form>
Here is what the js might look like. Here the missing brackets makes it difficult to tell where functions should end so I have had to guess a lot.
/* I find it hard to belive you wanted to encapsule your functions inside the
click_event function so I took the liberty of placing all
functions in the glonbal scope as this is probably what you inteneded.
I removed the click_event handler as it only does the same thing as the onSubmit.
*/
function validate_ID() {
var email = document.getElementById('id_text');
var filter = /^[a-z0-9](\.?[a-z0-9]){1,}#threadsol\.com$/;
var filter1 = /^[a-z0-9](\.?[a-z0-9]){1,}#intellocut\.com$/;
var flag=0;
// Or feels better here as there is no way the email ends with bot #intellocut and #threadsol
// It also feels strange that these are the invalid adresses maby you messed up here and should change
// the contents of the else and the if branch.
if (filter.test(email.value) || filter1.test(email.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#e_asterics").html("");
return false;
} else {
return true;
}
}
// This funcion is not used Im guessing you should have used it in
function validate_Pass() {
var pass =document.getElementById('pass_text');
/* The filter below could cause problems for users in deciding password unless
you tell them some where what the rules are.
It was missing a { bracket before the 4 at the end that I added make sure
it is right now. If you are going to use the code.
*/
var filter = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s). {4,}$/;
if (filter.test(pass.value)) {
$('#warn_pass').html("Enter Valid Email or Password");
$("#p_asterics").html("");
return false;
} else {
return true;
}
}
/* There are betterways to deal with multiple validation than chaining them like
this but Im guessing this will work. Im guessing that if you want to use the
password validation you should call it some where in this function.
like so 'validate_Pass()'
*/
function jcheck() {
$("#e_asterics").html("");$("#p_asterics").html("");
$('#warn_text').html("");$('#warn_pass').html("");
var name = jQuery.trim($("#id_text").val());var pas = jQuery.trim($("#pass_text").val());
if ((name.length === 0) && (pas.length === 0)) {
$('#warn_text').html("*Indicates required field");
$('#warn_pass').html("* Indicates required field");
$("#e_asterics").html("*");
$("#p_asterics").html("*"); }
else if (name.length === 0) {
$("#e_asterics").html("*");
$("#p_asterics").html("");
$('#warn_pass').html("Email Id Required");
} else if (pas.length === 0) {
if(name.length !== 0) {
validate_ID();
} else {
$("#e_asterics").html("*");
$('#warn_text').html("Enter Email Id");
}
}
}
Hello I have a site with several Questions and i want an survey to click throw a few "divs" and with a check box if they want to give no answer:
!!! Every thing works but if i type in 0 in the input field the alert comes but then i Can't get further ? WHY !!!
My code for the Checkbox:
<input type="checkbox" id="CheckBoxFeld" name="CheckBox2" >
My Code For the Next Button:
<input type="button" value="Next">
My Code for the TEST:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
And my Code for the ShowHide Function:
// Show and Hide Div
function showHideDiv(idHide, idShow){
//document.getElementById(idShow).style.display = "block";
//document.getElementById(idHide).style.display = "none";
document.getElementById(idHide).style.visibility = "hidden";
document.getElementById(idShow).style.visibility = "visible";
}
Try checking the length of the value:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field.length == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
Try using, onclick="check2();" instead of onclick="onclick=check2();"
<input type="button" class="Button" value="Next" onclick="check2();">
Javascript:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
A few issues
poor practice and illegal html to wrap a button in a link
if you use a link, return false to avoid the HREF to be followed. In this case the browser would likely go to top and some browsers would partially unload the page, making for example animations stop
Like this
Next
OR
<input type="button" onclick="check2()" value="Next">
using
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && !checkbox2){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
But only if your field contains 0.
If you want to test if it is empty, you need field.length==0 instead
function validate() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==null || x==" ") {
alert("Enter username");
}
if(y==null || y==" ") {
alert("Enter password");
}
}
As Twonky commented, we need some additional information. The code that you posted is just a function. I suppose you have two inputs and a button? Do you want the alerts to show when a user clicks the button and the input fields are empty? If you do, you need to add this function as a callback to onclick event.
More about the events:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
https://www.bitdegree.org/learn/onclick-javascript
https://www.w3docs.com/snippets/html/how-to-make-button-onclick-in-html.html
Edit: added corrected code and some links for further reading. The mistake was with looking for white space, instead for an empty string (" ", instead of "")
<!doctype html>
<html>
<head>
<title>Welcome</title>
<script>
function validateForm() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==="" || x===null) {
alert("Enter username");
};
if(y==="" || y===null) {
alert("Enter password");
};
};
</script>
</head>
<body>
<div>
Username:<input type="text" name="un" id="user"/>
Password:<input type="password" name="ps" id="pass"/>
<input type="submit" onclick="validateForm()"/>
</div>
</body>
</html>
Further articles about these topics:
Stackoveflow thread about whitespace and empty strings
An article about the difference between == and ===
P.S.: I had also changed the element from form to div. Since you are using your function in this case as a security so the user wouldn't submit empty data, this is better for now, since form is submitted with your function call and div isn't. You can check the network tab to see, that the page reloads after the function is executed with form element and is not reloaded with the div element.
if(x === undefined || x === null || x.trim() === '') alert('Please enter a username');
if(y === undefined || y === null || y.trim() === '') alert('Please enter a password');