Javascript validation breaks when submitting - javascript

I've been working on a simple form that will have several (2-3) sets of questions that contain radio buttons as answers. Each radio button has a number value. I was able to work in a logic that shows or hides a text box when the user selects a certain radio button.
In the original code I found, the validation checks only one specific question, but I'm wanting to update the validation code in a way that if ANY of the questions have a text box visible, and its empty, the alert pop up should come up.
Here is a JSFiddle page with the code: https://jsfiddle.net/nxenxoo/92myvwc3/25/
At this moment, if on question #1 I click on radio buttons 1-3, and forget to fill in the text box, move onto the second question and hit radio button 10, for example, the validation works great. I get a pop up.
However, lets say I fill in the text box required for question #1 and leave the text box that appears for question #2, then I get a 404 error upon submit.
I was trying to work in a OR statement || below, I was hoping it would work, but unfortunately it does not.
function validateForm(){
var x= $("form input[type=text]").val();
if ($('.showother' || '.showother2').is(":visible")) {
if ( x==null || x=="")
{
alert("Please fill in all text boxes");
return false;
I am curious to figure out what could be the problem. I know very little of javascript, so I am sorry if this is a very basic queston!

HTML
<div id="Other" class="showother" style="display:none">Please specify <input name="textbox" id="textbox" type="text">
</div>
...
<div id="Other2" class="showother2" style="display:none">Please specify <input name="textbox" id="textbox2" type="text">
</div>
Javascript
var x= $("form input[type=text]").val();
...
"form input[type=text]" matches both text inputs, but only returns the value of the first match.
function validateForm(){
var x1= $("#textbox").val(); // first textbox, use id
var x2= $("#textbox2").val(); // second textbox, use id
if ($('.showother' || '.showother2').is(":visible")) {
// check if either are null or empty
if ( x1==null || x1=="" || x2==null || x2=="") {
alert("Please fill in all text boxes");
return false;
}
}
}
Alternatively, check all visible text inputs with one block of code:
$("form input[type=text]").each(function() {
if (
($(this).parent().is(":visible"))
&& ($(this).val()==null || $(this).val()=="")
) {
alert("Please fill in all text boxes");
return false;
}
})

Related

Check form with onclick() function not working properly

This is my third night working on the same code... can`t get it right after days of google and tutorials and I am so tired of it... I am beeing desperate right now...
On short, I have a form and I use a button type="button" to generate a second button type="submit".
Before the second button appears, I need to check all required inputs if empty and after completion, show the second button.
I created a mixed code which now verify if inputs are empty, and highlights them one by one, not all inputs empty at the same time as I wanted.
I wanted to show highlighted all empty inputs not one by one and if one input is filled it should remove highlight class.
My work so far can be found here: here
Most important of all, I have a calculator which is calculating from inputs values. This is the reason I am using first button type="button".
How to get this to an end? I am so tired of this. Thank you.
LE: Partially fixed it by removing some return false; code from function. It has some errors although. For example, if you complete the last three inputs without completing and the ones on top, will submit anyway.
You could use the required attribute. It won't have any effects as you're not submitting the form, but then you could select all required fields with document.querySelectorAll(":required") or with jQuery $(":required") and loop through all of them validating each one.
You are returning false when a value is empty, so it's stopping the function, that's why they highlight one by one.
You can look this basic validation using JS and get idea what to do
<script type="text/javascript">
function validateMe(){
var name = document.getElementById('name').value;
var phone = document.getElementById('phone').value;
if(name==""){
//do something
alert("name can not be null");
return false;
//this will not submit your form
}
else if(phone==""){
//do something
alert("phone can not be null");
return false;
//this will not submit your form
}
else{
return true;
//This will submit your form.
}
}
</script>
<form action="somewhere.php" method="post" onsubmit="return validateMe();" >
<input type="text" name="name" id="name" />
<input type="text" name="phone" id="phone" />
<input type="submit" value="check and submit" />
</form>
NOTE: This is very basic validation using Javascript. What you want is to click one button and if valid then show submit button. But why you want do that if you want only validation. Why two buttons one to check values and show submit button and another button is submit itself. Why?
I created another short loop function BUT after inputs are filled, newButton button does not show. All Inputs are turning green from empty red. Please see the positioning of the return false;
function validateForm() {
var elements = document.getElementsByClassName("form-calc");
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
elements[i].style.borderColor = "red";
} else {
elements[i].style.borderColor = "green";
return false; // IF PUT THIS HERE, ONLY ONE INPUT AT A TIME IS HIGHLIGHTED BUT IN THE END THE newButton WILL POP UP.
}
}
return false; // iF I PUT THIS HERE IT STOPS HERE, NO NEWBUTTON NEXT.
var newButton = "<input type='submit' name='submit' value='Trimite-mi oferta pe mail' class='buton-calc'/>";
document.getElementById("a").innerHTML= "<span style='margin-left: 17%;'>Oferta personalizată a fost generată</span>"+newButton;
//SOME CODES HERE
});
What am I missing?

Javascript Input type="color" validation for form

Beginner level with Javascript and have a question regarding the input type color.
I am trying to make the user choose the color black before proceeding with next page of the form. The default color is yellow.
Could someone please help me with this and explain where I have gone wrong or missing something?
And have done research to try figure it out myself but stuck, probably the simplest thing as per normal. Thanks
Here is a snippet:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.style.backgroundColor =='rgb(255, 153, 153)') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
}
function spamCheck() {
//alert("Spam Check Working.......");
var color = document.getElementById("color").value;
if (!color == "#000000") {
alert("Please enter the color black to proceed.");
color.focus;
return false;
}
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<button type="submit" onClick="validate(), spamCheck()">Continue → </button>
</span>
</form>
There a couple of things to be improved here as the logic does not really add up. Heres your code, amended and annotated with comments:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
// When using the `not equal` operator, use it _in the operator_.
// Putting a `!` in front of a variable will change the variable first
// before comparing. This can cause unexpected issues!
// Also added a type check as the button does not have a value of
// '#000000', so the alert would _always_ show. This prevents that.
if (element.type === 'color' && element.value !== '#000000') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
function spamCheck() {
// As you want to focus on this element later, store the element
// NOT the value.
var color = document.getElementById("color");
// This is the point where the placement of the `!` is changed
// Because if you invert the value of a string, you might get
// unexpected results!
if (color.value !== "#000000") {
alert("Please enter the color black to proceed.");
// Focus is a _method_ of an <input> node,
// not a property, so call it with ().
// Also, because you originally set color to the _value_,
// it is only a string and not the <node>
color.focus();
return false;
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<!-- To prevent submission, your onclick is changed -->
<button type="submit" onClick="return (validate() && spamCheck())">Continue → </button>
</span>
</form>
Please note that your validate() will always throw an alert as your button does not have a value of #000000, which is also considered an element. Therefor not all elements pass your test. However, I have amended this by checking if the elements type is that of color, and only then checking for that value and alerting.
But here's the main issue: how do you do this properly? Well, javascript uses event listeners for that, and it could greatly improve your code. I have added my suggestion to the snippet below. Keep in mind that attaching events to HTML elements using onSomething attributes on elements is considered bad practise. That's mostly because it makes your code too tightly coupled together, meaning that if you have to amend it later it will be a mix of JS, HTML and other elements thrown in and it will become confusing.
Event Listeners solve that issue for you, you can attach them to the element using only javascript, but that does mean that your form can be subm,itted without javascript. That's technically what you want - but keep in mind that SPAM bots usually disable javascript anyhow, so nothing of what you do has any affect unless you write your form using only javascript.
Now, onto an improved version of the provided code that is not as tightly coupled. I added some properties to your HTML (and removed other just to make it simpler but you can keep the spans, for example). These properties are not tightly coupled to JS. They are there for JS to read, but make no difference otherwise. It also means someone who only knows HTML can edit the messages.
The checkColor is now also rolled into your validation function, as is validation to anything. Now even better would be to check using regex patterns, but that's beyond the scope of this question.
var form = document.getElementById('myForm');
// Only run this function when a submit button is clicked and the form is
// considered to be submitted. Pass the function an event as well.
form.addEventListener('submit', function(event){
// Lets assume the form is valid
var isValid = true;
// Lets use a standard for loop, it's easier to read
for(var i = 0, element; element = form.elements[i]; i++){
// I;ve added two data-properties in your HTML, one that tells us what
// value your are looking for and another that provides the hint
// you want to show people
var match = element.getAttribute('data-match');
var hint = element.getAttribute('data-hint');
// If there is something to match and it does not match the value provided
// then set isValid to false and alert the hint (if there is one);
if(match && match !== element.value){
isValid = false;
if(hint) alert(hint);
}
}
// If one element has set the isValid to false, then we want to prevent
// the form from actually submitting. Heres were the event comes into play:
// event.preventDefault() will stop the form from actually submitting.
if(!isValid) event.preventDefault();
});
<form id="myForm">
<input name="color" id="color" data-hint="Enter the color black in HEX to proceed." data-match="#000000" type="color" placeholder="#000000" />
<input type="submit" value="Continue →" />
</form>
Just use change the if statement to look like this if (color !== "#000000")in the spamCheck functtion now we can check if the color is the correct value.
here is an example try to change the color to black and the alert will change.

Javascript validation bug

Please imagine this part of a web form. Two checkboxes (with the same name="myCheckbox") and two text inputs. If the first checkbox is checked, the first text input must not be empty. If the second checkbox is checked, the second text input must not be empty. To validate this I use the script below:
// huge validation code above
}else if (!document.myForm.myCheckbox[0].checked && !document.myForm.myCheckbox[1].checked){
jAlert ('Please select one of the two checkboxes!',function(){$(myForm.myCheckbox).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value=="") {
jAlert ('You have selected the first checkbox. Please make sure that the first text input is not empty!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[1].checked && myForm.mySecondTextInput.value=="") {
jAlert ('You have selected the second checkbox. Please make sure that the second text input is not empty!',function(){$(myForm.mySecondTextInput).focus();});
return false;
// huge validation code below
Everything works just fine. But now, I also want to check if in the first text input the user has entered at least 10 digits. I update my validation code, please see below:
// huge validation code above
}else if (!document.myForm.myCheckbox[0].checked && !document.myForm.myCheckbox[1].checked){
jAlert ('Please select one of the two checkboxes!',function(){$(myForm.myCheckbox).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value=="") {
jAlert ('You have selected the first checkbox. Please make sure that the first text input is not empty!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value!=="")
var x = document.getElementById("myFirstTextInput");
var y = x.value;
var totalNrOfDigits = 0;
for(var i = 0; i < y.length; i++){
if(/\d/.test(y[i])){
totalNrOfDigits++;
}
}
if(totalNrOfDigits < 10) {
jAlert ('Please make sure that the first text input contains at least 10 digits!',function(){$(myForm.myFirstTextInput).focus();});
return false;
}else if (myForm.myCheckbox[1].checked && myForm.mySecondTextInput.value=="") {
jAlert ('You have selected the second checkbox. Please make sure that the second text input is not empty!',function(){$(myForm.mySecondTextInput).focus();});
return false;
// huge validation code below
My problem: after I add the check for at least 10 digits, if the users clicks the SECOND check box, then "mySecondTextInput" is no longer validated and the form is submitted. I really don't get it why and already wasted most of may day...
Sorry because I have not added the whole code: It's really huge, it's a pretty complex web form.
In the second code example, you forgot the opening curly bracket on line 11, so only the first statement following the else if condition will be evaluated.
}else if (myForm.myCheckbox[0].checked && myForm.myFirstTextInput.value!=="")
^
|

Disable an input field if second input field is filled

totally a newbie...
I just want to know how to dynamically disable an input field when the second input field is filled
eg:
<td><input type="text" name="num-input1" id="dis_rm" value=""></input></td>
<td><input type="text" name="num-input2" id="dis_per" value="" ></input></td>
pls... any links and hints will do...
You simply need to give it a disabled property:
document.getElementById("dis_rm").disabled = true;
document.getElementById("dis_per").disabled = true;
you can use the on change event to see if one of them is filled:
var dis1 = document.getElementById("dis_rm");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("dis_per").disabled = true;
}
}
so if the first one is filled, the second one will be disabled
$('#dis_per').blur(function(){
if($(this).val().length != 0){
$('#dis_rm').attr('disabled', 'disabled');
}
});
http://jsfiddle.net/jasongennaro/D7p6U/
Explanation:
when the second input loses focus... .blur()
check to see if it has something inside it. Do this by making sure its length is not zero !=0
if it has something in it, add the attribute disabled and set it to disabled
$('#secondinput').live('blur',function(){
$('#firstinput').attr('disabled', true);
});
tihs works when you filled the second input field and click else where ..........
Just ad this to your 2nd text box:
onblur="document.getElementById('dis_rm').disabled = (''!=this.value);"
http://jsfiddle.net/vbKjx/
Set the disabled flag on the field you want to disable when the OnBlur event fires (for exiting the field) or when the OnChanged event fires (with, of course, validation on the change).
We can ommit some steps, refering to the form as object.
document.form1.num-input2.onchange = function() {
if ( this.value != "" || this.value.length > 0 ) {
document.form1.num-input1.disabled = true;
}
}
I like this answer, using Jquery:
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
I have a search bar that gives search results with every key press, if it returns no results then the user is presented with a form to ask for help. But if they fill out the "ask form" then type in the search bar again it will erase everything they entered in the ask form. So to solve this, I gave all the inputs in the ask form an id of "second div" and the search field id="firstdiv". Now, if they click or tab to one of the input fields of the ask form it will disable to search bar so their data will never be over written.
I will also add a button that will re-enable the search form if they change their mind.
And for the newbies - I put the code in the head of the document like this:
<html>
<head>
<script type="text/javascript">
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
</script>
</head>
<body>
....

How do I use JavaScript to create a text box mask?

I am very new to JavaScript. I want to add the same effect as that given in the text fields of this webpage in my own page... Can any one help me with how to do it or where to learn it from.
I want my text fields to show what have to be written there but it will change as soon as I write something in it..
Another thing is that a small popup block will appear when I click on a textbox which describes what and how to write in it... like password should be alpha numeric... or more than 6 character long ect.
If you want to do this in an accessible way (and you should):
If JS is available, position a transparent input over a label inside a container and toggle the transparency of the input based on its value at document load time and whenever the focus enters of leaves the element.
I've produced a minimal example.
As for the second part of the question. That's very similar. Just have another label beside the input, and toggle its visibility when the focus enters or leaves, ignoring the value of the input. I wouldn't bother with this though, advance notice of requirements is nice!
You might want to take a look at the WMD markdown editor:
http://wmd-editor.com/
This does exactly what you're looking for.
Look at jquery:
$('#textarea').onKeyup(
function(){
$('div#mydiv').innerHTML( $(this).val() );
}
);
Thats a start. :)
HTML Input field
<input type="text" name="name" id="name" value="" />
Javascript
function hint () {
var elem = document.getElementById('name'); // get element
elem.value = "Enter Name"; // fill element with value
elem.onfocus = function () { // if the user focuses
if (elem.value === "Enter Name") { // if there is default text
elem.value = ""; // clear it
}
}
elem.onblur = function () { // if user removes focus on field
if (elem.value === "") { // if the field is empty
elem.value= "Enter Name"; // fill in a default value
}
}
}
window.onload = hint; // call the function when the page has loaded

Categories