document.getElementById JS HTML CSS - javascript

I am trying to get my forms NOT TO reset. I am making a <input type="password" /> and whenever I click the button to submit the password, and they get it wrong, I need there to be something that shows that it is incorrect. It works, but only for a split second. Can you help me?
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
margin-top: 220px;
}
#wrg {
visibility: visible;
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="desktop()" id="pass">Sign In</button>
<p id="wrg"></p>
</center>
</form>

The button ends up submitting the form, which causes the window to refresh because there's no action attribute on the form.
You can prevent this by either making the button type="button" (rather than the default submit), using event.preventDefault(), or by returning false, as below. (But as noted in comments below, return false may not be the best approach: it's easy to forget to include the return in both the function and the onclick attribute, without which the form will submit anyway. event.preventDefault is the most explicit and therefore probably best way to handle this.)
function desktop() {
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;")
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
return false;
}
#pass {
border-radius: 8px;
padding: 5px;
margin-bottom: 5px;
}
#user {
margin-bottom: 10px;
padding-bottom: 0px;
/*margin-top: 220px;*/
}
<form>
<center>
<h1 id="user">User</h1>
<input type="password" id="pass" placeholder=" Password" /><br>
<button onclick="return desktop()">Sign In</button>
<p id="wrg"></p>
</center>
</form>
(You do have duplicate pass IDs, which should be unique, and of course clientside authentication as done here isn't the least bit secure, but neither of those issues is directly relevant to your question. getElementById winds up returning the first matching element, which happens to be the one you wanted.)

You are using duplicate IDs for your button and input elements: pass.
Also, it would be easier to just add an event listener to the Sign In button and capture that event inside your function.
document.getElementById("pass").addEventListener('click', desktop);
function desktop(evt) {
evt.preventDefault();
var pass = document.getElementById("pass").value;
if (pass == "555") {
alert("Welcome;");
} else {
document.getElementById("wrg").innerHTML = "Incorrect Password";
}
}
If you do it this way, remember to remove the onclick attribute from the button.

Related

Check box not working on form before allowed to submit

Hello guys trying to get my checkbox to need to be clicked before submitting my button which is an onclick not submit??
<form>
<p>
<input style="padding:14px; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; width: 300px; border: none;" placeholder="Enter Date Here... e.g 17/05/1981" />
</p>
<p>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat" required="true"> <label style="color: #fff; font-size: 10px;"> Please Accept Terms</label></p>
<p><a id="generateButton" href="generate.html" class="progress-button red" data-loading="Creating..." data-finished="Start Over" data-type="background-vertical" onclick="getRandomImage()">Start Search</a></p>
</form>
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, or javascript, you can easily control if a checkbox group has at least one checked element.
function myFunction() {
document.getElementById("myCheck").required = true;
}
<form action="/action_page.php">
Checkbox: <input type="checkbox" id="myCheck" name="test">
<input type="submit" onclick="myFunction()">
</form>
You can add logic to your clickHandler to check that the box is checked. So instead of calling getRandomImage() directly you add some logic to conditionally call the function.
function clickHandler() {
// get the checkbox element from the DOM
const checkboxElement = document.getElementById('vehicle3');
// see if the checkbox is checked
if (checkBoxElement && checkBoxElement.checked) {
getRandomImage();
} else {
console.log("The checkbox wasn't checked!");
}
}
// add the handler to the button
document.getElementById('generateButton').addEventListener('click', clickHandler);

class name not showing when trying to validate email

I have a form the is trying to validate email. If the email is incorrect the class for the input does not show. Below is the code for the html:
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit">
<p id="addedText"></p>
</form>
and below I have implemented the following javascript:
function ValidateEmail(inputText) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.value.match(mailformat)) {
alert("You have entered a correct email addresss")
document.form1.text1.focus();
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML += "This is the wrong email address";
document.getElementByClassName("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
the css I am trying to activate is the following:
.invalidEmail {
border: 1px solid red;
background-image: url("/images/icon-error.svg");
background-repeat: no-repeat;
background-position: 75% 25%;
}
At the end of the day I want the an image to appear in the form like this. . The issue is nothing seems to appear.
To add a class to your input element, you need to use element.classList.add and to remove it you need element.classList.remove.
Also, document.getElementsByClassName("invalidEmail") will get you all the elements which contain invalidEmail classname. So it is not required here
Have gone through the repo which you mentioned:
CSS specificity is one of the culprit here. Adding !important will work fine now (check border in the snippet) but ideally you should read about it and then fix the css without using !important
It seems you are not hosting your project and opening the index.html file directly. Host your project on some server (e.g. localhost) and it should work fine (python -m SimpleHTTPServer is a simple command to help you spawn a local server quickly which you can use but there are others as well).
function ValidateEmail was not using proper regex test for email testing. Read here for more details
Have tried to fix it for you
function ValidateEmail(inputText) {
var mailformat = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;;
if (mailformat.test(inputText.value)) {
document.getElementById("addedText").innerHTML = "";
alert("You have entered a correct email addresss")
//document.form1.text1.focus();
document.getElementById("test").classList.remove("invalidEmail")
return true;
} else {
// var img = document.createElement('img');
// img.src = "/images/icon-error.svg"
document.getElementById("addedText").innerHTML = "This is the wrong email address";
document.getElementById("test").classList.add("invalidEmail")
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
.invalidEmail {
border: 1px solid red !important;
/*Check here*/
background-image: url("https://image.flaticon.com/icons/png/128/752/752755.png");
background-repeat: no-repeat;
background-position: 75% 25%;
background-size: 12px 12px;
}
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" placeholder="Email Address" value="" onclick="return ValidateEmail(document.form1.text1)">
<input type="image" src="images/icon-arrow.svg" alt="submit" >
<p id="addedText"></p>
</form>
</div>
Hope it helps. Revert for any doubts.
Note: This is how icon image and red boundary is coming for me

Clear form after form post

I am trying to do something a little bit tricky.
I am trying to clear my form, inputs especially after I've submitted the form. Whatever, when I am trying to do so. The form clears but the post never executes. I want it do do both, why it is a little tricky is since I am using so I don't have to reload the page after the form post.
<script>
function submitForm() {
$('form[name="cform"]').submit();
$('input[type="text"], textarea').val('');
return;
}
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" onclick="submitForm()" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
Is there even a solution?
Using submit() on its own simply submits the form as if the submit button was pressed with no JS present. Additionally, you'll need to use AJAX for what you're after. Try something like this (adapted from the example on https://api.jquery.com/jquery.post/):
<script>
$('form[name="cform"]').submit(function(e) {
e.preventDefault();
var $form = $( this ),
data = $form.serialize(),
url = $form.attr( "action" );
var posting = $.post( url, data );
posting.done(function( data ) {
$('input[type="text"], textarea').val('');
});
});
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
You'll need to further modify to take into account things like submission failures, but that should get you moving in the right direction. I recommend reading through the documentation at the link listed above for more info on callbacks (e.g. .done() in code above).
submitForm() must return true in order to have the form actually submit.
MKM's answer is correct. To clear all input types on a page, use this instead of $('input[type="text"],textarea').val();
This example clears all inputs in three forms. Tested except for select-multiple.
$(':input','#Form1','#Form2','#Form3').each(function()
{
switch(this.type)
{
case "text":
case "textarea":
case "hidden":
{
this.value = ''; break;
}
case "radio":
case "checkbox":
{
this.checked=false; break;
}
case "select-one":
{
// Set dropdowns to default value
$(this).prop("selectedIndex", 0); break;
}
case "select-multiple":
{
$(this).prop("selectedIndex", 0); break;
}
case "file":
{
$(this).value = ""; break;
}
}
});

Clear a single form field in HTML

I am creating a simple HTML login page, but if I enter data into the fields it stays there when I refresh the page. I have tried
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
but this doesn't do anything (I placed it into onLoad on the inputs of the login.)
HTML:
`
<title>Login</title>
</head>
<body>
<form>
<fieldset>
<legend><h3>Please Login:</h3></legend>
<input type="text" placeholder="Username" name="userId" id="userId" onLoad="pageInit('userId');"><br>
<input type="password" placeholder="Password" name="passwd" id="passwd" onLoad="pageInit('passwd');"><br>
</fieldset>
</form>
</body>
CSS:
<style>
html {
font-family: sans-serif;
text-align: center;
}
a {
font-weight: normal;
}
a:hover {
font-weight: bold;
}
#userId, #passwd {
width: 30%;
height: 40px;
text-align: center;
}
</style>
JS:
<script>
function pageInit(ID) {
this.browserbot.getCurrentWindow().document.getElementById(ID).value = '';
}
</script>
As far as I can tell, the previous answers to not cover the full extent of the question. The original question requests a function to be called to clear the field. However, I'm going to address this in several different ways.
This can be achieved with no JavaScript at all, but simply setting the value attribute as below:
<input type="text" placeholder="Username" name="userId" id="userId" value="" />
<input type="password" placeholder="Password" name="passwd" id="passwd" value="" />
The above will ensure that the fields are clear when the page is loaded, but using only HTML. To do this via JavaScript, multiple things have to be taken into consideration. First, a function should be defined, which needs to be called when the page is loaded.
function clearValue(id) {
document.getElementById(id).value = "";
}
This will simply set the value to blank. However, this gets us back to the original issue. Setting onload for each element does not work, instead we must use window.onload.
window.onload = function() {
clearValue("userID");
clearValue("passwd");
}
This will clear each value one-by-one. However, there is an even better way to do this. JavaScript has built-in functions that make it easy to clear the entire form, or access the elements of the form by their name, even if they are the child of another element within the form. However, keep in mind that only valid input (includes textarea, etc...) fields can be accessed in this way.
So, assuming that the form's ID is myform, this would clear the entire form, no matter how many fields:
document.getElementById("myform").reset();
It's that simple. Using the form element, you can also access the fields by name, as mentioned above.
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
Using the above code makes it much quicker, especially if you have more fields.
Putting the JS together, it might look like this:
window.onload = function() {
// using function
clearValue("userID");
clearValue("passwd");
// or, reset entire form
document.getElementById("myform").reset();
// or, clear each field one-by-one
var f = document.getElementById("myform").elements;
f["userId"].value = "";
f["passwd"].value = "";
}
May be it will help you.
<input type="text" value="initial" id="field">
<button id="reset">reset</button>
<script type="text/javascript">
document.getElementById('reset').onclick= function() {
var field= document.getElementById('field');
field.value= field.defaultValue;
};
</script>
Set the input value to " " - in other words, nothing.
This way, the value will be cleared when the page loads.
Implment this like so:
<input value="">
If you'd rather use JS, add this to your onload event:
window.onload = myOnloadFunc;
function myOnloadFunc() {
document.getElementById('userId').value = ''
}

Php Clear textbox when user checks a checkbox

at the moment I am trying to add some functionality for a user to be able to submit an anonymous suggestion. I am trying to clear a textbox that contains the users name when the user checks the checkbox. However my code does not clear the checkbox when checked. is there a way to clear the checkbox before the form is submitted?
Thanks
<div>
<label style="display: inline-block; margin-left: 10px; letter-spacing: 2px; color: #007A8E;">
<div align="left"><b>Name:</b> </div>
</label>
<div align="left">
<input type="checkbox" style=" margin-left: 110px; outline: 1px solid #0078AE; " name="Anonymous" value="Anonymous" onClick="CheckAnon">
</div>
<label style="margin-left: 2px; color: #0078AE;">
<div align="left">Anonymous</div>
</label>
<div align="left">
<?
function CheckAnon()
{
if(isset($_POST['Anonymous']) == 'Anonymous')
{
$anonFirstName="Anon";
$anonLastName="Anon";
}
else if (isset($_POST['Anonymous']) != 'Anonymous')
{
$anonFirstName = $firstName;
$anonLastName= $lastName;
}
}
?>
</div>
</div>
<div align="left">
<input name="firstname" style="height: 34px; width: 268px; margin-left: 10px; margin-top: 5px; color: #007A8E;
border: 1px solid #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;" type="text"
value="<? echo $anonFirstName?> <? echo $anonLastName?>">
</div>
You can do this at client side using jquery or javaScript.
Assume this text box:
<input type="text" id="fname" />
JavaScript Method:
<script type="text/javascript">
function clearTextBox() {
// Code to clear textbox on Checkbox tick
var textname = document.getElementById("fname"); //get textbox id
textname.value = ""; // clear the textbox
}
</script>
You can do it in PHP as you want.
But, doing it in jQuery is quite simple.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
$("#Anonymous").change(function(){
if ($(this).is(':checked')) {
$("#firstname").val('');
}
});
});
</script>
You are confusing clientside scripting (JavaScript in your case) with what the server receives (PHP).
The function you call:
onClick="CheckAnon"
Does not exist on the client. Also use: onClick="CheckAnon();"
There are more problems in your code. I advice you to use Firefox and look in the errorlog of javascript. This will help you a lot to trace the bugs.
Also make sure you understand what happens in the client (browser), and the server (after you post a form)
I think you need to clear that up first before you start clearing textboxes with JavaScript)

Categories