Problem with getting javascript answer after a subscription button - javascript

I'm doing a form with one field: a password form. When I submit it, I just want the JavaScript to tell the user if the password is the good one or if he has to try again.
Here's my code:
var x = document.forms["CodeForm"]["email"].value;
if (x == "MAX") {
$message._show('success', '✅ Code Correct !');
} else {
$message._show('failure', '❌ Code Incorrect !');
}
As you see, the "succes" and "failure" parts are for my CSS class who tells the script the color of the text just after. Now, my problem is when I enter anything, the "if" part works and it says "Code Incorrect !" in red (as I want) but if I enter the good code just after, it says "Code Correct" but in red, and not in green as it is in the CSS class "success". When I enter the good code first (after reloading the page) then it's in green.
If you wanna try it, here's my website, and the good code is "MAX" : http://enigma-door.000webhostapp.com
Here are the html code for the form and the _show method:
<form name="CodeForm" id="signup-form" method="post" action="#">
<input type="text" name="email" id="email" placeholder="Code" />
<input type="submit" value="Valider" />
</form>
$message._show = function(type, text) {
$message.innerHTML = text;
$message.classList.add(type);
$message.classList.add('visible');
window.setTimeout(function() {
$message._hide();
}, 3000);
};

Inside your $message._show method please remove the existing class then it will work.$message.classList.remove("failure");
Since your failure css class is not removed it is having high specificity and overriding for success

It's impossible to know for sure without seeing the _show method, but it sounds like perhaps you're not removing the .failure class when you're adding the .success class.
The way to find out is to inspect the html using chrome's dev tools and see what classes your input has. That will tell you why it's red.

Related

JavaScript native form abilities [duplicate]

I want to know if there is any way to programmatically show a HTML validation error, using a JavaScript function.
This is useful for scenarios where email duplication has to be checked. For example, a person enters an email, presses the Submit button, and then has to be notified that this email is already registered or something.
I know there are other ways of showing such an error, but I wanted to display it in the same way as how the validation error messages are shown (e.g. invalid email, empty field, etc.).
JSFiddle: http://jsfiddle.net/ahmadka/tjXG3/
HTML Form:
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
<button id="triggerMsg" onclick="triggerCustomMsg()">Trigger Custom Message</button>
JavaScript:
function triggerCustomMsg()
{
document.getElementById("email").setCustomValidity("This email is already used");
}
The above code sets the custom message, but its not automatically shown. It's only shown when the person presses the submit button or something.
You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in most browsers except Internet Explorer (see Browser compatibility at MDN). It reports validity errors without triggering the submit event and they are shown in the same way.
var applicationForm = document.getElementById("applicationForm");
if (applicationForm.checkValidity()) {
applicationForm.submit();
} else {
applicationForm.reportValidity();
}
reportValidity() method will trigger HTML5 validation message.
This question was asked over a year ago, but it's a good question that I recently encountered as well...
My solution was to use JavaScript to create an attribute (I went with "data-invalid") on the <label> of each <input>, <select> and <textarea> containing the validationMessage.
Then some CSS...
label:after {
content: attr(data-invalid);
...
}
... displays the error message.
Limitations
This only works provided each element has a label. It will not work if you put the attribute on the element itself, because <input> elements cannot have :after pseudo elements.
Demo
http://jsfiddle.net/u4ca6kvm/2/
As mentoned by #Diego you can use form.reportValidity();
To support IE and Safari include this polyfill, it just works:
if (!HTMLFormElement.prototype.reportValidity) {
HTMLFormElement.prototype.reportValidity = function() {
if (this.checkValidity()) return true;
var btn = document.createElement('button');
this.appendChild(btn);
btn.click();
this.removeChild(btn);
return false;
}
}

Javascript to replace all the input.value by '*' like a password typing

I have a
<input id="TxtBox" runat="server" autocomplete="off" onkeypress="">
And while doing the keypress, directly with js code, it replaces all the characters for '*'. Like a password typing.
Edit: 2022
As i read this old question i found imprecision why i wanted to avoid type="password" at that time. It was because if that attribute were in the tag the browser would remind a old password and it was annoying.
Edit:
I passed all day trying do put the autocomplete=off on all of my inputs to the browser stop asking password while someone is filling a form on my site, ddnt worked(a tried a few more things). And i thought in this type of solution i tried the javascript replace function but it only returned one char and decided to ask about a complete sequence of '*' while writing in a input. Tks for all the help.
sorry if i wasnt clear in the context i was just thinking in the code. i thought in some old i did before in C language but anyway i asked.
Edit:
I asked help how to do this in JS i did some stuff on keypress with JS functions like replace i did some code but i simply erased it and asked for some help. Next time i will post code to have some kick start code. I was doing something like
onkeypress="this.value=this.replace(this.value,'*')"
Tks in advance.
This is for in a visible input see a password typing and in a hidden i have it.
note: i want to avoid type="password"
Why do you need JavaScript to accomplish what HTML gives your for free? The element exposes all the same attributes/properties so you can still use it like a text box.
<input type="password">
If you feel you must reinvent the wheel, this can be done by using two fields. The user will type in the first and it will display the mask character and the actual key will be stored in a hidden input field for processing:
// Get references to DOM elements:
var txt = document.getElementById("txtMask");
var hdn = document.getElementById("pass");
// This keeps track of how many characters should be displayed
var maskLen = 1;
// Set up input event on first box
txt.addEventListener("keydown", function(evt){
// Manually put the right amount of mask characters into the box
// and update the maskLen value
var str = '#'.repeat(maskLen++)
this.value = str;
// Cancel the event and stop bubbling
evt.preventDefault();
evt.stopPropagation();
// Set the actual typed data into the hidden field
hdn.value += evt.key;
// Just for testing:
console.clear();
console.log("Actual data is: " + hdn.value);
});
<input type="text" id="txtMask" autocomplete="false">
<input type="hidden" id="pass">
Use type="password"
Like this:
<input type="password" id="TxtBox" runat="server" autocomplete="off" onkeypress="">
You can also do one of these:
input { -webkit-text-security: none; }
input { -webkit-text-security: circle; }
input { -webkit-text-security: square; }
input { -webkit-text-security: disc; /* Default */ }
You can use those without having a type="password"

on('submit' works when clicking the <button> but not when pressing enter on an input field

I'm using on('submit') to detect when the form was submitted, but it only works when the user clicks on the submit button.
I use a <button> tag so I can put an image inside the button. I know I could use an input with type="submit" and use CSS it with the image, but I'd like to know the alternative jQuery way.
I was thinking doing an or comparison, for example on('submit') OR when user presses enter on any of the input field, but how should I do that?
$('#form').on('submit', function (e) {
e.preventDefault();
var email = $('#email').val();
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
});
<form id="form">
<input id="email" maxlength="64" name="EmailEDIT" type="text" width="100">
<button id="submitBtn"><img height="30" src="images/fx_demo_button.png" width="74"></button>
</form>
If the user presses enter in one of the field, the form will submit. It will trigger the same event as the button does. If this does not occur, something's up in your code.
You commented that your code doesnt work, but it does: http://jsfiddle.net/B5pZ4/
All I've added was alert(1); the rest is your code from this topic
You define your function in the eventhandler, might be better to seperate that, just in case you want to use that function again (or alter it a bit and use it in two situations).
If you seperate it in your code, it'll make more sense, I also think this is the problem you're having:
http://jsfiddle.net/B5pZ4/1/
You can actually make your code work with just one line. You create the function in your eventhandler (which, in this case, should be considered bad practice!), but you never call it. Either remove the function declaration, or add this under the function:
return validateEmail( email ); // THIS IS BAD PRACTICE AS FIX!
A tip: if you're working in html5, you can use this and the browser will do validating for you:
<input type="email" />
You need to insert an invisible input type submit for this to work.

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Problem displaying error on the webpage using js

I have created a webpage, in which i have a few input box and a submit button in a
<form action="" method="post" name="password">
On the click of the submit button, it calls a js function, which checks if the passwords are same, and if not it displays the error
if (passwrd1!=passwrd2)
{
document.getElementById("response").innerHTML="<font color='red'>Passwords do not match</font>";
}
It displays the error in:
<div id="response" align="center">Response from js</div>
But the problem is, it displays the function and then the same "Response from js" comes back.
What should i do to solve this porblem??
Best
Zeeshan
Do you also return false from submit button's click function to prevent it from actually posting back the form?
if (passwrd1 != passwrd2)
{
document.getElementById("response").innerHTML = "Passwords don't match";
return false;
}
Because from the small amount of code you've given us it looks like, your form gets posted back anyway.
You need a return false; in your if-statement, as the form will get posted even if the statement is hit. The return false will stop the form from being posted and will display the message.
Even though it's not part of the question, I will recommend you don't use the <font>-element, as it is deprecated and not exactly a good way of just displaying some red text. You can either output the error message in a span with the text color set to red like this:
document.getElementById("response").innerHTML = "<span style=\"color: red;\">Message</span>";
Not much difference, but following the standards of the web is always a good thing.
To give an example of what was said in the comments, you're probably even better off defining a class and styling it with CSS.
.errormsg { color: red; }
document.getElementById("response").innerHTML = "<span class=\"errormsg\">Message</span>";
The result is the same, but as said in the comments; it's easier to maintain, and thus a better solution.

Categories