javascript - Merging checkboxes into one field in form - javascript

I would like to ask for help with function that merge checkboxes into one field. In question Combine checkbox values into string before submitting form I have found one but I would like it to start onsubmit with another function that checks if the form was filled correctlty.
Form:
<form id="formularz_wspolpraca" name="Zapis na poradnik" method="post" target="_top" onsubmit="return SprawdzFormularz(this) && mergeFunction(this)">
<input type="text" id="email" name="email"/>
<input type="text" id="imie" name="imie"/>
<input type="text" id="nazwisko" name="nazwisko"/>
<input type="text" maxlength="12" size="12" id="pole_1" name="pole_1"/>
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3a" value="polecajacy">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3b" value="projektant">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3c" value="instalator">
<input class="checkbox_wspolpraca" type="Checkbox" name="pole_3d" value="ekspert">
<input type="hidden" name="pole_3" id="pole_3">
<input id="pp" type="checkbox" name="pp" checked=""/>
<input type="submit" value="Wyƛlij">
</form>
Merge function:
function mergeFuntion(event) {
event.preventDefault();
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}
Check function:
function SprawdzFormularz(f) {
if (f.email.value == "") {
alert("Nie poda\u0142e\u015b/a\u015b adresu e-mail.");
return false;
}
if (((f.email.value.indexOf("#", 1)) == -1) || (f.email.value.indexOf(".", 1)) == -1) {
alert("Poda\u0142e\u015b/a\u015b b\u0142\u0119dny adres e-mail.");
return false;
}
if (f.imie.value == "") {
alert("Wype\u0142nij pole Imi\u0119. ");
return false;
}
if (f.nazwisko.value == "") {
alert("Wype\u0142nij pole Nazwisko. ");
return false;
}
if (f.pole_1.value == "") {
alert("Wype\u0142nij pole Nr telefonu. ");
return false;
}
if ((f.pole_3a.checked == false) && (f.pole_3b.checked == false) && (f.pole_3c.checked == false) && (f.pole_3d.checked == false)) {
alert("Wybierz zakres wsp\u00f3\u0142pracy");
return false;
}
if (f.pp.checked == false) {
alert("Musisz zgodzi\u0107 si\u0119 z Polityk\u0105 Prywatno\u015bci.");
return false;
}
return true;
}
Check function is working without a problem but i can't get merge one to work as well. Can someone point out what am I doing wrong with merge function? I'm quite new to javascript so that could be some rookie mistake. Thanks in advance.

In onsubmit you are running SprawdzFormularz first and it returns true if all the checks pass. This means that it will submit the form, before the merge function is run.
You need to run the merge function inside the check function before returning true so that the form does not submit before you have combined the string and set the necessary value.
function SprawdzFormularz(f) {
// ....
var boxes = document.getElementsByClassName('checkbox_wspolpraca');
var checked = [];
for (var i = 0; boxes[i]; ++i) {
if (boxes[i].checked) {
checked.push(boxes[i].value);
}
}
var checkedStr = checked.join(' ');
document.getElementById('pole_3').value = checkedStr;
return true;
}

Related

How to do proper validation for this and set focus and then form has to submitted

Here I am facing problem in if condition it validates for subject and unable to set focus and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I need to proper code to validate these two fields. At least in subject column any one should be selected likewise in regional field also any should be selected. I tried has much what I can do. But I could not completed the work.
what I needed is:
Atleast any one should be selected in subject field.if its null alert +focus
like wise for medium field also.
<script type="text/javascript">
function check() {
var a1 = false;
b1 = false;
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var reg1 = reg.length;
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
a1 = true;
}
}
}
if (!chk[i].checked) {
chk[i].focus();
}
if (len) {
for (i = 0; i < len; i++) {
if (reg1[i].checked) {
return true;
} else {
alert('please select the medium');
b1 = true;
}
}
}
if (a1 == true && b1 == true) {
return true;
}
}
</script>
Myform is:
<form name="f1" action="s.php" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Like this
Instead of onclick use onsubmit and assign the function onload
window.onload=function() {
document.getElementsByName("f1")[0].onsubmit=function() {
var chk = document.getElementsByName('subject[]'),chkOk=false;
for (var i = 0, n=chk.length; i < n; i++) {
if (chk[i].checked) {
chkOk = true;
break;
}
}
console.log(chkOk)
if (!chkOk) {
alert('please select the subject');
chk[0].focus(); // focus the first
return false;
}
var reg = document.getElementsByName('regional[]'),regOk=false;
for (var i = 0, n=reg.length; i < n; i++) {
if (reg[i].checked) {
regOk = true;
break;
}
}
if (!regOk) {
alert('please select the medium');
reg[0].focus(); // focus the first
return false;
}
return true; // allow submit
}
}
<form name="f1" action="s.php" method="post" onsubmit="return check()">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT">
</form>

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

change form action value based on hidden field values

When a user selects either 2 or 3 checkboxes, and submits the form, I am trying to change the value of the form action attribute based on the values from 2 or 3 hidden fields.
The hidden fields with a default value of 0 are given the value of 1 when a checkbox is checked.
However it does not work and I'm unsure where to go from here.
My Form:
<form id="f" name="f" method="post" onsubmit="return checkform()" action="scripts/false.php">
RSA:<input type="hidden" id="RSAsel" name="RSAsel" value="0" />
RSG:<input type="hidden" id="RSGsel" name="RSGsel" value="0" />
RSF:<input type="hidden" id="RSFsel" name="RSFsel" value="0" />
<input name="submit" type="button" class="bodytxt" id="button" onclick="javascript:doSubmit();" value="Enrol in these courses">
</form>
<script>
function doSubmit() {
var RSAsel = parseInt(document.getElementById("RSAsel").value);
var RSGsel = parseInt(document.getElementById("RSGsel").value);
var RSFsel = parseInt(document.getElementById("RSFsel").value);
var target1 = 'scripts/process-combined-3.php';
var target2 = 'scripts/process-combined-rsa-rsg.php';
var target3 = 'scripts/process-combined-rsa-rsf.php';
var target4 = 'scripts/process-combined-rsg-rsf.php';
var theForm=document.getElementById('f');
if (RSAsel === 1 && RSGsel === 1 && RSFsel === 1) {
theForm.action = target1;
theForm.submit();
return true;
}
else if (RSAsel === 1 && RSGsel === 1) {
theForm.action = target2;
theForm.submit();
return true;
}
else if (RSAsel === 1 && RSFsel === 1) {
theForm.action = target3;
theForm.submit();
return true;
}
else if (RSGsel === 1 && RSFsel === 1) {
theForm.action = target4;
theForm.submit();
return true;
}
}
</script>
you need to get value of hidden field before trying to use it, like:
function doSubmit() {
var RSAsel = document.getElementById("RSAsel").value;
var RSGsel = document.getElementById("RSGsel").value;
var RSFsel = document.getElementById("RSFsel").value;
//rest of your code
}
and there's no header( "Location: $errorurl" ); in javascript, you are confusing it with PHP

Form Validation with Javascript using window.onload

Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.
Is there someone who knows how to write the following javascript form validation?
I am sure that it is very simple, but I can not figure this one out to save my life.
Thank you for you sharing your knowledge.
I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file.
Validation Rules are as follow:
INPUT: Username; Required (yes); Validation (Must be 5-10 characters long).
INPUT: Email; Required (yes); Validation (Must have an # sign, must have a period).
INPUT: Street name; Required (no); Validation (Must start with a number).
INPUT: Year of birth; Required (yes); Validation (must be numeric).
My code looks as follow:
HTML:
<!DOCTYPE html>
<html>
<head>
<script defer="defer" type="text/javascript" src="form.js"></script>
</head>
<body>
<form action="fake.php">
Username*: <input type="text" class="required" name="u"/><br/>
Email*: <input type="text" class="required" name="p"/><br/>
Street address: <input type="text" class="numeric" name="s"/><br/>
Year of birth*: <input type="text" class="required numeric" name="b"/><br/>
<input type="submit"/><br/>
</form>
</body>
</html>
JS
document.forms[0].elements[0].focus();
document.forms[0].onsubmit=function(){
for(var i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if((el.className.indexOf("required") != -1) &&
(el.value == "")){
alert("missing required field");
el.focus();
el.style.backgroundColor="yellow";
return false;
}
if((el.className.indexOf("numeric") != -1) &&
(isNaN(el.value))){
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor="pink";
return false;
}
}
}
without changing much of your code ... updated your code for other validation like length (needs a class verifylength to validate length) and so on....
try this
HTML
<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>
JAVASCRIPT
document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var el = document.forms[0].elements[i];
if ((el.className.indexOf("required") != -1) && (el.value == "")) {
alert("missing required field");
el.focus();
el.style.backgroundColor = "yellow";
return false;
} else {
if (el.className.indexOf("verifylength") != -1) {
if (el.value.length < 5 || el.value.length > 10) {
alert("'" + el.value + "' must be 5-10 charater long");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
if (el.className.indexOf("email") != -1) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(el.value);
if (!emailTest) {
alert("email not valid");
el.focus();
el.style.backgroundColor = "yellow";
return false;
}
};
if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
working fiddle
something alongs the lines of...
//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;
//email needs # and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*#.*\./g')) return false;
//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;
i think the regex is off + untested :)
Here is your javascript validation object in work. Hope you can make some modification according to your need.
Style
<style>
.valid {border: #0C0 solid 1px;}
.invalid {border: #F00 solid 1px;}
</style>
HTML Form
<div>
<form id="ourForm">
<label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />
<label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />
<label>Username</label><input type="text" name="username" id="username" class="" /><br />
<label>Email</label><input type="text" name="email" id="email" class="" /><br />
<input type="submit" value="submit" class="" />
</form>
</div>
Call script before closing tag
<script src="form_validation_object.js"></script>
form_validation_object.js
/*
to: dom object
type: type of event
fn: function to run when the event is called
*/
function addEvent(to, type, fn) {
if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
to.addEventListener(type, fn, false);
} else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
to.attachEvent('on' + type, fn);
} else { // IE5
to['on' + type] = fn;
}
}
// Your window load event call
addEvent(window, 'load', function() {
/* form validation object */
var Form = {
validClass: 'valid',
inValidClass: 'invalid',
fname: {
minLength: 1,
maxLength: 8,
fieldName: 'First Name'
},
lname: {
minLength: 1,
maxLength: 12,
fieldName: 'Last Name'
},
username: {
minLength: 5,
maxLength: 10,
fieldName: 'Username'
},
validateLength: function(formElm, type) {
//console.log('string = ' + formElm.value);
//console.log('string length = ' + formElm.value.length);
//console.log('max length=' + type.maxLength);
//console.log(Form.validClass);
if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
//console.log('invalid');
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) == -1) {
if (formElm.className.indexOf(Form.validClass) != -1) {
formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
} else {
formElm.className = Form.inValidClass;
}
}
//alert(formElm.className);
return false;
} else {
//console.log('valid');
//alert(formElm.className.indexOf(Form.validClass));
if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only http://www.regular-expressions.info/wordboundaries.html
//formElm.className += ' ' + Form.validClass;
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) != -1)
formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
else
formElm.className = Form.validClass;
}
return true;
}
},
validateEmail: function(formElm) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formElm.value);
if (emailTest) {
if (formElm.className.indexOf(Form.validClass) == -1) {
formElm.className = Form.validClass;
}
return true;
} else {
formElm.className = Form.inValidClass;
return false;
}
},
getSubmit: function(formID) {
var inputs = document.getElementById(formID).getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'submit') {
return inputs[i];
}
}
return false;
}
}
/* call validation object */
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm() {
var inputs = ourForm.getElementsByTagName('input');
if (Form.validateLength(inputs[0], Form.fname)) {
if (Form.validateLength(inputs[1], Form.lname)) {
if (Form.validateLength(inputs[2], Form.username)) {
if (Form.validateEmail(inputs[3])) {
submit_button.disabled = false;
return true;
}
}
}
}
submit_button.disabled = 'disabled';
return false;
}
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
Working example at JSBin
http://jsbin.com/ezujog/1

Validating a single radio button is not working in available javascript validation script Part-2

I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>

Categories