I used to validate checkbox form with a code like this:
<div>
<form action="survey.php" method="post" name="survey">
<span class="form"><input type="checkbox" name="event1" onClick="return countMarketing()">Event1</span>
<span class"form"><input type="checkbox" name="event2" onClick="return countMarketing()">Event2</span>
<span class"form"><input type="checkbox" name="event3" onClick="return countMarketing()">Event2</span>
<!-- other forms -->
</form>
</div>
And a javascript validation that is something like this (to limit the count of checkboxes checked):
function countMarketing() {
var NewCountMarketing = 0
if (document.survey.event1.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (document.survey.event2.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (document.survey.event3.checked)
{NewCountMarketing = NewCountMarketing + 1}
if (NewCountMarketing == 3)
{
alert('Please choose only two')
document.survey; return false;
}
}
And validation like this works. But now, say im using php to for the submission, how do i check if in JS if the name of the form is something like this:
<input type="checkbox" name="events[]" id="event1" onClick="return countMarketing()">Event1
Ive tried to change the JS to:
if (document.survey.events[].checked)
{code here}
if (document.survey.getElementByName('events[]').checked)
{code here}
if (document.survey.getElementById('event1').checked)
{code here}
But it doesnt work.. any can shed some light on me about this? thank you very much :)
If you are in fact using jQuery you could do:
Make sure you are including jQuery in your document before you use this function & that the document is loaded before you try to run the function.
function countMarketing() {
if( $('input[name="events[]"]').filter(':checked').length > 2 ) {
alert('Please choose only two');
}
}
First remove the inline events declaration and move it to an external Javascript file or a script block
You can always use bracket Notation to access such attributes
document.survey["events[]"]
Code
var elems = document.survey,
checkboxNames = ["event1[]", "event2[]", "event3[]"];
for (var i = 0; i < checkboxNames.length; i++) {
bindClick(elems[checkboxNames[i]]);
}
function bindClick(elem) {
elem.addEventListener('click', countMarketing);
}
function countMarketing() {
var NewCountMarketing = 0
var latest;
for (var i = 0; i < checkboxNames.length; i++) {
if (elems[checkboxNames[i]].checked) {
latest = elems[checkboxNames[i]];
NewCountMarketing++;
}
}
if (NewCountMarketing == 3) {
latest.checked = false;
alert('Please choose only two')
document.survey;
return false;
}
}
Check Fiddle
Related
I have an input tag as follows as part of a form submission.
<input type=“checkbox” id=“allowcheatmode” name=allowCheatMode value=“NO” onchange=“allowCheatModes()”>
And allowCheatModes in a JS function
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElementById(“allowcheatmode”).value = “YES”
} else {
document.getElementById(“allowcheatmode”).value = “NO”
}
But this is not working when I am trying to print the allowcheatmode variable after form submission. What am I doing wrong here?
1) You have included an invalid character “ and ”. You should use " in both HTML and JS.
var x = document.getElementById(“allowcheatmode”).checked
2) There is no function named getElemenetById, instead use getElementById.
3) Add if-else code in the onChange function itself. So that it can trigger when checkbox value changes
NOTE I've added an extra label to just show the current state of the checkbox. You can skip that part.
function allowCheatModes() {
var x = document.getElementById("allowcheatmode").checked
if (x) {
document.querySelector("label").textContent = "YES"
document.getElementById("allowcheatmode").value = "YES"
} else {
document.querySelector("label").textContent = "NO"
document.getElementById("allowcheatmode").value = "NO"
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
<label for="allowcheatmode">NO</label>
Shouldn't it be this:
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElemenetById(“allowcheatmode”).value = “YES”
} else {
document.getElemenetById(“allowcheatmode”).value = “NO”
}
}
Try this
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
if (isChecked) {
document.getElementById("allowcheatmode").value = "YES";
} else {
document.getElementById("allowcheatmode").value = "NO";
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
The code above will be valid, because you had typo in getElemenetById (should be getElementById, not getElemeNETById). Anyway, you will see nothing in this case, because input with type="checkbox" have no view. You can improve your code adding some div element:
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
document.getElementById("allowcheatmode-view").innerHTML = isChecked ? "YES" : "NO";
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" onchange="allowCheatModes()">
<div id="allowcheatmode-view">NO</div>
P.S.: "condition ? ifTrue : ifFalse" is ternary operator, the short form of "if"
You did two things wrong
First thing
You put if outside the function, please put if inside the function
function allowCheatModes() {
...
}
Replace with
function allowCheatModes() {
...
if(x){
...
}
}
Second thing
The function name you are using is wrong, you should use getElementById, not getElemenetById
document.getElemenetById
Replace with
document.getElementById
Below is my adjusted snippet, you can refer to it.
Have a good day :)
function allowCheatModes(){
var x = document.getElementById("allowcheatmode").checked;
if (x) {
document.getElementById("allowcheatmode").value = "YES"
} else {
document.getElementById("allowcheatmode").value = "NO"
}
console.log(document.getElementById("allowcheatmode").value);
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
I'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked radios, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the radios and set valid = true if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'radio') {
//y[i].classList.remove('invalid');
//valid = true;
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Do I need to split the validation down into further functions to separate validating different field types?
I think that radio buttons are the way to go. Especially from a UI point of view. Why would you let the user pick more than one item only to tell them later they can't?
Having said that, you can do what you're trying to do with something like this:
function validateForm() {
var checkBoxHolders = document.querySelectorAll(".checkboxholder");
var valid = true;
for (var i = 0; i < checkBoxHolders.length; i++) {
var numChecked = checkBoxHolders[i].querySelectorAll("input[type='checkbox']:checked").length;
if (numChecked === 1) {
checkBoxHolders[i].classList.remove('invalid');
} else {
checkBoxHolders[i].classList.add('invalid');
}
valid = valid && numChecked === 1;
}
document.getElementById('valid').innerHTML = 'I am valid: ' + valid;
}
.invalid {
background-color: orange;
}
<input type="text" id='foo'>
<input type="text" id='bar'>
<div class='checkboxholder'>
First group
<input type="checkbox" id='check1'>
<input type="checkbox" id='check2'>
</div>
<div class='checkboxholder'>
Second group
<input type="checkbox" id='check3'>
<input type="checkbox" id='check4'>
</div>
<button type='button' onclick='validateForm()'>Validate me</button>
<div id='valid'>
</div>
With jQuery, it'd be something like:
if (jQuery('input[name=RadiosGroupName]:checked').length === 0) {
valid = false;
}
I did wrap this in a form with a submit button, but realized that this attempted to go to a new page without performing the logic. How can I pass the zip code to the onclick button event? If this is completely wrong, can you provide guidance onto how to perform this correctly.
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
}
</script>
You need to get the value of your input and you can do this with document.querySelector('[name="zip"]').value
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zip = document.querySelector('[name="zip"]').value;
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
})
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
Just use getElementById('ELEMENT_NAME_HERE').value like so:
Go!
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip){
console.log('Clicked');
var enteredZip = document.getElementById("zip").value;
console.log(enteredZip);
var zipCodes=[26505, 26501, 26507, 26506];
for(i=0; i<=zipCodes.length-1; i++){
if(zip == zipCodes[i]){
alert("YES");
break;
}}});
</script>
https://plnkr.co/edit/ptyUAItwyaSmZXsD81xK?p=preview
You can't pass it in.
basically if this myfunction() will return a false then the form would not be submitted;
Also this would only be performed at the time of submittion of the form
https://www.w3schools.com/jsref/event_onsubmit.asp
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input id='input-id' type="submit">
</form>
<script>
myfunction(){
if(/*some condition*/)
{
return false;
}
</script>
Also few things to consider since you seem new and people here are giving you very correct but specific solutions.
if you add a button to inside tag, that would submit the form on clicking it.
That is why many use a div which looks like a button by css. Mainly a clean solution to override the Button submit and also you can simply submit the form by Javascript.
I have a form:
<form id="f3" method="post" action="interface_add.php">
<fieldset>
<input onclick="this.value=''" class="te3" type="text" name="f3a" value="title"/>
<input onclick="this.value=''" class="te3" type="text" name="f3b" value="url"/>
<a id="f3c" class='but' href="javascript:void(0)" onclick="i3()">Add</a>
<a id="f3d" class='but' href="javascript:void(0)" onclick="i3a()">Delete</a>
</fieldset>
</form>
and I use some Javsascript to "serialize" the element names and values like this:
function is(a)
{
var b='';
var c=document.forms[a].elements;
for(i=0;i<c.length;i++)
{
if(c[i].type=='checkbox'&&c[i].checked==false)
{
b+=c[i].name+"=NULL&";
}
else
{
b+=c[i].name+"="+c[i].value+"&";
}
}
b=b.slice(0,-1);
return b;
}
which I call from here:
function i3()
{
var a='';
a=is('f3');
However the return value I get from is() inserted into 'a' is
"undefined=undefined&f3a=title&f3b=url"
Funny thing is I had a similar problem previously but this was because I was not intializing 'a' which is why I broke this up, mostly out of paranoia that 'a' was not initialized properly.
Probably something simple I overlooked - but why is there undefined=undefined appearing.
It is coming from the <fieldset> element.
Just add a test for a name property inside the loop.
for(i=0;i<c.length;i++) {
if( c[i].name ) {
// your code
}
}
You'd probably like to skip all unnamed elements, like fieldset.
function is(a)
{
var b='';
var c=document.forms[a].elements;
for(i=0;i<c.length;i++)
{
if (c[i].name == undefined) continue; // skip all unamed elements
if (c[i].type == 'checkbox' && c[i].checked == false)
{
b += c[i].name + "=NULL&";
}
else
{
b += c[i].name + "=" + c[i].value + "&";
}
}
b = b.slice(0,-1);
return b;
}
Rather than using name, you can just get the checkboxes:
if(c[i].type=='checkbox')
{
if (c[i].checked==false)
{
b+=c[i].name+"=NULL&";
}
else
{
b+=c[i].name+"="+c[i].value+"&";
}
}
}
Of course you could just use submit buttons instead of links and let the form submit itself:
<input name="add" type="submit" value="Add">
<input name="delete" type="submit" value="Delete">
If the user clicks the Add button, a value is sent as ...add=Add..., if they click on the Delete button, then ...delete=Delete... is sent instead.
I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />