How to associate condition-reaction with document.querySelector? - javascript

I don't know how to link the following condition-reactions to passid form input id:
I don't know where to put the document.querySelector() method so that indexed contion-reactions will be associated with it.
Here is the code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>
<body>
<form>
<label>Password</label>
<input type="password" id="passid" />
<br>
<input type="submit" value="Sign In" />
</form>
<script>
function passType() {
var password = ["p1", "p2", "p3", "p4", "p5"];
if (password.indexOf > -1) {
alert("That's great! Thank you!");
} else {
alert("Wrong, try again");
}
if (password.indexOf > -1) {
alert("It's wrong, you have one more try...");
} else {
alert("Get out now!");
window.close();
}
}
passType();
</script>
</body>
</html>
How should this be done?

These are some points that I would want to focus on :
To select a particular element using the query selector, remember these :
If you happen to know the id of the element, use document.getElementById(id). This is the most prominent way of selection, as usually id is unique for all elements.
If you happen to know the class of the element, use document.getElementsByClassName(class). This method has certain amount of risk, as there could be more than one element with the same class.
If you happen to know the tagName of the element, use document.getElementsByTagName(tag).
The easiest way to achieve element selection is by using document.querySelector('tag'/ '.class'/ '#id'). You can refer here for more about the same.
Now, you need to understand that your function passType(), which here validates the entered password based in the array of passwords you have defined, needs to be called only after the user has input the password and click the Sign In button.
In order to achieve this, you will have to bind the submit event to an EventListener. This can be achieved by using document.querySelector('form').addEventListener('submit', passType);
Now finally, as per the code snippet you provided, you want to give the user a second chance in case the user enters a wrong password at first attempt. For this, you will have to store the attempt counts in a variable. Also, the EventListener of the submit action button keeps bubbling, and in order to prevent it, you need to use event.preventDefault()
Keeping all this in mind, I believe this will solve your problem. Here is the rectified code snippet :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>
<body>
<form>
<label>Password</label>
<input type="password" id="passid"/>
<br>
<input type="submit" value="Sign In"/>
</form>
<script>
var attemptCount = 0;
function passType(event) {
event.preventDefault();
var enteredValue = document.querySelector('form').querySelector('#passid').value;
var password = ['p1', 'p2', 'p3', 'p4', 'p5'];
if (password.indexOf(enteredValue) > -1) {
alert("That's great! Thank you!");
}
else {
attemptCount++;
alert('Wrong, try again');
if (attemptCount <= 1) {
alert("It's wrong, you have one more try...");
document.querySelector('form').querySelector('#passid').value = '';
} else {
alert('Get out now!');
window.close();
}
}
}
document.querySelector('form').addEventListener('submit', passType);
</script>
</body>
</html>
Feel free to ask any queries you have on the same.

How to access form using query selector?
let frm = document.querySelector('form');
Then Listen for its submit event.
frm.addEventListener('submit', passType);
How can you access the input password?
You need to make changes to your function. First add the following to the top of your "passType" function. The following snippet saves the user input into the variable pass.
let p = frm.querySelector('#passid');//Get the DOM node
let pass = p.value;//Get the input value
Now Modify if (password.indexOf > -1) to if (password.indexOf(pass) > -1) to check for actual input.
DEMO
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>
<body>
<form>
<label>Password</label>
<input type="password" id="passid" />
<br>
<input type="submit" value="Sign In" />
<!-- We also have input type = "button" and events for both >>> onsubmit & onclick. -->
</form>
<script>
function passType() {
let p = frm.querySelector('#passid');
let pass = p.value;
var password = ["p1", "p2", "p3", "p4", "p5"];
if (password.indexOf(pass) > -1) {
alert("That's great! Thank you!");
} else {
alert("Wrong, try again");
if (password.indexOf(pass) > -1) {
alert("It's wrong, you have one more try...");
} else {
alert("Get out now!");
window.close();
}
}
}
let frm = document.querySelector('form');
frm.addEventListener('submit', passType);
</script>
</body>
</html>

I guess you're asking how to get the value the user typed into the password field. That's document.getElementById("passid").value. So you would write:
if (password.indexOf(document.getElementById("passid").value) > -1) {
alert("That's great! Thank you!");
}
Note that calling passType() in the top-level of the script won't work. That will run when the page is first loaded, not wait for the user to fill in the password. You should call it when the user submits the form. You should do:
document.querySelector("form").addEventListener("submit", passAll);
You should also change the passAll() function so it calls Event.preventDefault() if the user enters an incorrect password, to prevent submitting the form. See
return false on addEventListener submit still submits the form?
Also, checking a password in client-side Javascript is not very secure. There's nothing stopping the user from modifying the script or bypassing it. Passwords should be checked on the server, so that the user cannot override it.

If you're looking for a way to do something with the password field upon form submission you might want something along these lines:
// listen for submit events on the form
document.querySelector('form').addEventListener('submit', doSubmit);
// our form submit handler
function doSubmit(event) {
// prevent submission
event.preventDefault();
event.stopPropagation();
// get the password field
// event.target is the form
// could alternatively query by id using document.getElementById('passid')
var passwordField = event.target.querySelector('#passid');
// do something with the field or its value
console.log(passwordField.value);
return false;
}
<form>
<label>Password</label>
<input type="password" id="passid" />
<input type="submit" value="Sign In" />
</form>

Related

Manually trigger validation error in input box using javascript or jquery

I have an input box which is not part of a form. When a user clicks a button I want to display an error validation message if the field is empty. I found solutions for this when the input is part of a form, but is it possible to display validation error messages manually if the input box is not part of a form?
You can validate in the button's click handler https://jsfiddle.net/yzgmpqLo/. I think it would be better to show invalidation message in the "input" field itself.
<!DOCTYPE html>
<html>
<body>
<script>
function validateText() {
var txtInput = document.getElementById("txtInput");
if(txtInput.value.trim()=="") {
txtInput.value = "Invalid Entry";
txtInput.style.color = "red";
}else {
txtInput.style.color = "black";
}
}
</script>
<input id="txtInput" type="text">
<button type="button" onclick="validateText()">Validate</button>
</body>
</html>

Keep button from submitting form Javascript

I'm learning JavaScript and am unable to make a button inside of a form that doesn't submit the form. There is a similar question here but the most popular answer to specify type="button" doesn't work in my case and other answers involve jQuery, which I would like to leave out for now.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function submit(){
alert("Yo")
}
</script>
</head>
<body>
<form name="myForm" onsubmit="submit()">
<input type="button" value="Submit!" onClick="submit()" />
</form>
</body>
</html>
Since you're not using a type="submit" the only reason your form would submit anything is because you're literally calling the submit() method when the button is clicked. (well, sort of. It's actually form.submit() - the method you created is window.submit()).
By default, an input of type="button" will not do a form submission unless you literally call form.submit()
Pass along the event as an argument in your submit function, and prevent its default behaviour:
function submit(event) {
event.preventDefault();
alert('Yo');
}
onClick='submit(event)'
Dating from the introduction of Javascript by Netscape Corporation, form element event handlers defined as HTML attribute values were provided with a special scope chain which searches properties of the element clicked and the form element ahead of searching the global object. [This was a convenience for web programmers and predated the introduction of a Document Object Model with standardized methods for access and manipulation.] Hence
<input type="button" value="Submit!" onClick="submit()" />
when clicked executes the anonomous function created from the HTML attribute string:
function( event) { submit()}
which searches its scope chain for submit and finds it as a property of the enclosing form object. Possible solutions include
explicitly specifying the global version of the function to execute:
onclick="window.submit()"
naming the global function something else, say "preSubmit", which does not conflict with the property of the form object:
onclick="preSubmit()"
adding the click event handler to the button in javascript after the button element has been created (only function specified in HTML have a special scope chain).
Section `19.1.6. Scope of Event Handlers" within chapter 19 of "Javascript the Definitive Guide" from O'Reilly is the only link that I have been able to find which discusses this.
updated after #progysm's comment on another answer
The scope chain of an HTML provided event handler is now covered in the HTML5 standard, under internal raw uncompiled handler, list item 1.10, which indicates the lexical scope of the handler includes the element clicked, the form it belongs to (if any) and the document object. I would caution against relying on this too heavily: some browsers used to include every parent object of a clicked element in its scope chain, not just its form and document.
To prevent your button from submitting, you can either:
Use preventDefault() on the onsubmit event of the <form> or
Use return false at the end of the operation on the onclick event of the button.
The code:
<html>
<head></head>
<body>
<form name = "myForm" method = "POST">
<input name = "button" type="submit" value="Submit!"/>
</form>
<script type = "application/javascript">
document.forms.myForm.onsubmit = function(e) {
e = e || event;
e.preventDefault();
}
document.forms.myForm.button.onclick = function () {
// Your code
return false; // Prevents the button from trying to submit
}
</script>
</body>
</html>
Notes:
Be sure to use the method attribute in the <form> tag as it's required.
e = e || event means that e will be equal to e in all the browsers that recognise it and equal to event in browsers that recognise event.
document.forms.[form name].[input name] is another way to get an element based on its name, in contrast to document.getElementById() which requires the id of the element, which have not set in your HTML.
You can test the code's functionality live with the following snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head></head>
<body>
<!-- The form we don't want to submit -->
<form name = "myForm" method = "POST">
<input name = "button" type="submit" value="I will not submit!"/>
</form>
<!-- The form we want to submit -->
<form name = "myForm2" method = "POST">
<input name = "button2" type="submit" value="I will submit!"/>
</form>
<script type = "application/javascript">
// For the form we don't want to submit
document.forms.myForm.onsubmit = function(e) {
e = e || event;
e.preventDefault();
}
document.forms.myForm.button.onclick = function () {
console.log("NOT Submitted!");
return false;
}
// For the form we want to submit
document.forms.myForm2.button2.onclick = function () {
console.log("Submitted!");
}
</script>
</body>
</html>
function onFormSubmit()
{
console.log('FORM SUBMITTED');
return false;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form name="myForm" onsubmit="return onFormSubmit()">
<input type="submit" value="Submit form! [input type = submit]" /><br />
<input type="button" value="Submit form! [input type = button, onclick = form.submit]" onClick="return onFormSubmit();" /><br />
<!-- in real test change onClick behavior
return onFormSubmit();
to:
form.submit();
Here I used onFormSubmit() because when you calling form.submit() browser doesn't dispatch onsubmit event -->
<button>Submit form! [button]</button><br />
Submit form! [a, onclick = form.submit]<br /><br />
<input type="button" value="Click me, no submit! [input type = button]" /><br />
</form>
</body>
</html>
If you wish to conditionally consume the event or not, simply return true or false from your handler function, like so...
JavaScript:
function validate() {
var valid = true;
// the following two validation functions would return a Boolean.
valid = valid && validateUsername();
valid = valid && validatePassword();
// If validation is fine, return true and this allows post to continue.
// If validation is not fine, return false and this disallows the submission from going ahead.
return valid;
}
HTML:
<form name="frmTest" id="frmTest"
method="post" action="example.action"
onsubmit="return validate();">
</form>
If you don't need it to be conditional, just return false, of course.
This solution works in native javascript. Doesn't prevent return key in inputs, it does what it should - stop a form from submitting on enter
function preventReturnKeyFormSubmit(){
//listen to key press events
window.addEventListener('keydown', function(e){
//set default value for variable that will hold the status of keypress
pressedEnter = false;
//if user pressed enter, set the variable to true
if(event.keyCode == 13)
pressedEnter = true;
//we want forms to disable submit for a tenth of a second only
setTimeout(function(){
pressedEnter = false;
},100)
})
//find all forms
var forms = document.getElementsByTagName('form')
//loop through forms
for(i = 0; i < forms.length; i++){
//listen to submit event
forms[i].addEventListener('submit', function(e){
//if user just pressed enter, stop the submit event
if(pressedEnter == true) {
e.preventDefault();
return false;
}
})
}
}
//run this function inside document onload/domready/ or if using jquery .ready()
preventReturnKeyFormSubmit()
Simply make it return the function, and return false
<script type="text/javascript">
function submit(){
alert("Yo");
return false;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="submit()">
<input type="button" value="Submit!" onClick="return submit()" />
</form>
</body>
</html>

Send message from input field into database by pressing enter

i've done a web chat which the codes are:
<div id="namebox">Name: <input type="text" id="name" autofocus autocomplete="on" ></div>
<div id="msgbox" >Message: <input type="text" id="message"></div>
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit">Submit</button></div>
So, the message goes into the database fine by clicking the button submit, however i was wondering to ad a code to jut press enter and it will be sent, so there will be 2 options.
I am using onClick and onKeypress which it is not working.
<div id="submitbox"><button onClick="postMessageToDB(); return false;" id="submit" onkeypress="postMessageToDB(this, event); return false;">Submit</button></div>
Where the javascript is:
<script type="text/javascript">
function postMessageToDB(inputElement, event) {
if (event.keyCode == 13) {
inputElement.div.submit();
}
}
</script>
Im not using form because it was asked to be div, not form.
Really appreciate for any help.
Thank you very much
Your code provided will only work when postMessageToDB() is called... it's not listening for a keypress.
Using jQuery:
$(window).keyup(function(e) {
if( e.keyCode==13 ) {
postMessageToDB([...]);
}
}
You need to call the function, you can do this by adding an EventListener to document and then check if it's enter that was pressed.
var keyevent = (/Firefox/i.test(navigator.userAgent)) ? "keypress" : "keydown"; // fit browser
document.addEventListener(keyevent, function(e) {
if (event.keyCode == 13) {
var a = document.getElementById('name').value; //get field values
var b = document.getElementById('message').value; //get field values
postMessageToDB(inputElement, event); // as I said, not sure what this will do, but you need to get the data you want to pass first within this function.
}
});
Then, just remove the keypress checkup from you function and you should check this line, I can't see that this is going to work:
inputElement.div.submit();

calling a function again in javascript

<!DOCTYPE html>
<html>
<head>
<title>input number</title>
</head>
<body>
enter no:1<input id="t1" type="text"><br>
<button type="button" onClick="myFunction()">submit</button>
<button type="button" onClick="myFunction()">next</button>
<div id="div1" style="color:#0000FF">
</div>
<script>
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no))
{
alert("Not Numeric");
}
else{
if(no!=1){
if(no%2==0){
no=no/2;
}
if (no%2!=0) {
no=(no*3)+1;
}
}
}
document.getElementById("div1").innerHTML = no;
}
</script>
</body>
</html>
After entering number in the text box when I press submit button it shows the following output
enter no:1
submit next
16
but when i press next button it is not showing any output.My expected output is when I press next button it shoult show the next no. by executing the logic in the myFunction() function.Helpme...
You haven't set any case for when no = 1. You have a case for when no != 1 and when no%2 != 0 both of which are false when no = 1. There isn't any increment logic in here to find the next number and return it. I think you are missing a } at the end of the no%2==0 clause.
Also I fail to see why you have two identical buttons here, next and submit do the same thing. Moreover I would advice more descriptive IDs. div1 isn't a good name for a div.
The javascript part should look like this, if the intention is to implement Collatz conjecture. http://en.wikipedia.org/wiki/Collatz_conjecture
function myFunction(){
var no=document.getElementById("t1").value;
if(no==""||isNaN(no)) {
alert("Not Numeric");
} else {
if(no!=1) {
if(no%2==0) {
no=no/2; // Note the division operator instead of mod
} else {
no=(no*3)+1;
}
}
}
document.getElementById("t1").value = no; // Note that we are writing to the textbox
}
There are some basic HTML issues too, in your post you are using the input tag as
<input id="t1" type="text"> use it as: <input id="t1" type="text" />
Secondly, when you submit the data to the function, you are having some value there! Maybe 1 is the value or 16, whatever. But when you are trying to resubmit, either its not allowed or your input is now an empty field. So the function is not executing further than this step:
if(no==""||isNaN(no))
Try to save the value in the form.
Try using this:
document.getElementById("t1").value = no;
Make sure that the value is captured as it was, because your code is changing the value into some other form, use a new variable for this. That would save the value from the input and again write it back to that input.
This will set the value for that text input as it was before the function. It might make the input again ready for the submit!

Javascript form validation: how to force focus to remain on 'incorrect' field?

I can't believe that I can't find the answer to this question but I really have searched and can't find it! honest!
anyway - here is the question: I am trying to create a validation function for a form that will not permit the user to proceed to the next form field if the field doesn't validate.
I just want the 'incorrect' field to have focus until it is 'correct'.
because this is for a JS class I cannot use jQuery or any other framework.
here is one of the HTML fields:
<li>Number 1:<input class="field2" type="text" id="star1" onchange="validateAndDraw(this.value);"></li>
and here is a truncated version of the JS function:
function validateAndDraw(theValue) {
if (isNaN(theValue)) {
alert("no good");
} else {
[do stuff here]
}
}
I have tried using 'this.focus();' and 'this.parentNode.focus();' but no joy.
I am sure the answer is ridiculously simple, but I can't seem to find it.
thanks,
bennett
Try sending the object reference to the function instead of the value.
So in your input event:
validateAndDraw(this);
And change your function to:
function validateAndDraw(input) {
if (isNaN(input.value)) {
alert("no good");
input.focus();
} else {
[do stuff here]
}
}
As a side, I would suggest looking into Progressive Enhancement.
document.getElementById('star1').focus();
Using this inside your function will refer back to the function.
Alternatively, you could pass the object in the onclick event:
<input class="field2" type="text" id="star1" onchange="validateAndDraw(this);">
so the function could look like
function validateAndDraw(obj) {
alert(obj.value);
}
Try calling focus() in the blur event.
Also, this in your function refers to the global context, not the element.
(It only refers to the element inside the inline handler; you are making an ordinary function call from there)
You should change your function to accept the element as a parameter (which you can pass as this insidethe inline handler)
Why not pass in the element?
function validateAndDraw(theElement) {
var theValue = theElement.value;
if (isNaN(theValue)) {
alert("no good");
theElement.focus()
} else {
[do stuff here]
}
}
Send as trigger
There are for each loop function for check input in form.
If there are input[x].value = "", so alert and focus in it, next input and next alert
<html>
<body>
<form onsubmit="return validateForm(this)">
Name: <input type="text" name="name"><br />
E-mail: <input type="text" name="email"><br />
Password: <input type="password" name="password"><br />
<input type="submit" value="Send">
</form>
<script >
function validateForm(input) {
for (x in input) {
if (input[x].value == "") {
alert(input[x].name + " must be filled out");
input[x].focus();
return false;
}
}
}
</script>
</body>
</html>

Categories

Resources