Check form with onclick() function not working properly - javascript

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?

Related

Javascript validation breaks when submitting

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;
}
})

Allowing for multiple conditions if a checkbox=checked?

New to Javascript, teaching myself for fun. I have a basic function, and what I am attempting to do is make a checkbox (if checked) do more than one thing. In this example, I want to make a form become visible and also make the inputs required.
What I am noticing is that the first line works, I can make the form appear. However, the first input in that form does not become required.
Here is the Function.
When the checkbox is checked, the function does work. It makes the form "kForm2" become visible and hides it if not checked. But it seems it doesnt want to run the second line, where i require the first input of that form. There is also about 10 more inputs that I want to make required if that checkbox is checked. I know im writing this wrong, but I cant find the information online. Thanks
<input type="checkbox" id="k2Check" onclick="k2()">
<div id="kForm2" style="display:none">
<label for="kfirstname2">First Name:</label>
<input type="text" name="kfirstname2" id="kfirstname2"
minlength="3" maxlength="20">
</div>
<script>
function k2() {
var checkBox = document.getElementById("k2Check");
var kForm2 = document.getElementById("kForm2");
if (checkBox.checked == true){
kForm2.style.display = "block";
this.getField(kfirstname2).required=true;
}
else {
kForm2.style.display = "none";
this.getField(kfirstname2).required=false;
}
}
</script>
I was using the wrong code, after further research.
INCORRECT
this.getField(kfirstname2).required=true;
CORRECT
document.getElementById("kfirstname2").required = true;
This is working now thanks for your help guys.

javascript input value empty after assignment

very basic question; I bet it was already asked here but really couldn't find it.
okay so I have a little html form with a hidden input:
<input type='hidden' id='switchtonew' name='new' value='no'>
and a button that shall change the value of my hidden input to 'yes', via a function because its doing a couple more things, but these work...:
<button onclick='maneu()'>switch</button>
and the function:
function maneu(){
[...]
document.getElementById('switchtonew').value = 'yes';
}
and now if you click the button, the value of my hidden input just vanishes.
why?
I did try element.setAttribute('value', 'yes'); too.
Im really confused, please help :(
EDIT: changed function name to real, used one. still not working.
You are using a reserved word switch. By renaming the function, it should work.
You could use type="button" for the button to prevent submitting.
function switchValue() {
document.getElementById('switchtonew').value = 'yes';
}
<button onclick="switchValue()" type="button">switch</button>
<!-- type is text for displaying the value -->
<input type="text" id="switchtonew" name="new" value="no">
is the button submitting a form?
Probably the page is reloading and the inputs reset, if that is the case, use an <a> instead of a <button> or add an event.preventDefault() to button action
By default button type is submit, hence:
<button onclick='yourSwitch()'>switch</button>
will submit your form, and as result, you will see yes in URL (in case you use GET form method), like:
yourhost.com/index.html?new=yes
After reload, your page will come to initial state, which is:
<input type='hidden' id='switchtonew' name='new' value='no'>
Oh man, sorry for bothering.
As it's always, you ask something and find the solution immediately by yourself.
my function is emptying a couple of inputs by looping through them, and setting styling options.
thus, I set the value to yes and immediately afterwards it deletes all values of input tags.
sorry. Im stupid.
Something like this?
function maneu() {
var currentValue = document.getElementById('switchtonew').value;
if (currentValue === 'yes') {
document.getElementById('switchtonew').value = 'no';
} else if (currentValue === 'no') {
document.getElementById('switchtonew').value = 'yes';
}
console.log('value is now: ' + document.getElementById('switchtonew').value)
}
<button onclick='maneu()'>switch</button>
<input type='hidden' id='switchtonew' name='new' value='no'>

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.

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>
....

Categories