Get the form data on load submit - javascript

I want the form data that was submitted on page load via POST method
Here is my code
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>
What I want is to get the form data when ever this page is loaded
What I tried
document.getElementsByTagName('form')[0].onsubmit = function () {
var status, date;var str = '';
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
else if (date != null) {
str += date.value;
}
}//func close

Why are you submitting the form while user has not even filled the form body onload !
If you are allowed to use Jquery it will do your task easy
document.getElementsByTagName('form')[0].onsubmit = function () {
$(this).serializeArray();
}//func close
Please have a look at this link for details
Here is a small demonstration
$(document).ready(
function() {
$("#Form1").on('submit', function() {
var data = $(this).serializeArray()
console.log(data);
for (var i = 0; i < data.length; i++) {
document.body.innerHTML += 'Key: '+data[i].name +' and Value: '+ data[i].value + '</br>';
}
return false;
});
$("#Form1").submit();
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>

You need to write your code inside window.onload evnet.
Try this
window.onload = function() {
var str = '';
var status, date;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
if (date != null) {
str += date.value;
}
alert(str);
};
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>

Related

JS class not applying on datapicker

Good morning,
I've got some javascript to check if inputs are empty before printing and if so, cancel the print.
I have added jquery datepicker to one of the fields as a class and now it only applies one class or the other. (I have tried the datepicker as an ID instead) but doesn't work.
Javascript:
function checkForm(thisForm) {
var len = thisForm.elements.length ;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
if (elem.className == "formFieldRequired") {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
Input:
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
Any ideas on why this is happening and any fixes? - I may be missing something completely obvious!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/jquery.datetimepicker.js"></script>
<form id="myform">
<input name="Effective Date" type="text" style="width:12%;" class="formFieldRequired datepicker" placeholder="DD/MM/YYYY" onkeyup="javascript:return mask(this.value,this,'2,5','/');" maxlength="10">
</form>
<script>
function checkForm(thisForm) {
var len = thisForm.elements.length;
var cnt = 0 ;
for ( var i=0; i < len; i++) {
var elem = thisForm.elements[i] ;
console.log(elem.className)
if (elem.className.indexOf("formFieldRequired") != -1) {
if ((elem.value == "" || elem.value == -1)) {
alert("WARNING:\n You must supply information for the " + elem.name + " field");
elem.focus();
return false;
}
}
}
window.print();return true;
}
checkForm(document.getElementById("myform"));
</script>

Javascript: submit button is not active when enter data to the form

I've picked up this code and it does not seem to work. The problem is the 'submit' button is not active when i try to click after i entered all the data to the form. Any help on where i am lacking? please
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="ourForm">
<label>First Name</label><input type="text" /><br />
<label>Last Name</label><input type="text" /><br />
<label>Email</label><input type="text" /><br />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function addEvent(to, type, fn){
if(document.addEventListener){
to.addEventListener(type, fn, false);
} else if(document.attachEvent){
to.attachEvent('on'+type, fn);
} else {
to['on'+type] = fn;
}
};
var Form = {
validClass : 'valid',
fname : {
minLength : 1,
maxLength : 15,
fieldName : 'First Name'
},
lname : {
minLength : 1,
maxLength : 25,
fieldName : 'Last Name'
},
validateLength : function(formEl, type){
if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
} else {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
}
},
validateEmail : function(formEl){
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(formEl.value);
if (emailTest) {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
} else {
formEl.className = formEl.className.replace(' '+Form.validClass, '');
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;
}
};
addEvent(window, 'load', function(){
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.validateEmail(inputs[2])){
submit_button.disabled = false;
return true;
}
}
}
submit_button.disabled = 'disabled';
return false;
};
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
</script>
</body>
</html>
I copied the code and tried the same code. It works. It might be that you filled all the three inputs but you did not put correct EMAIL that fulfills the EMAIL format(regex) in the code.
For example try to fill inputs with these three inputs someone, someone, someone#gmail.com; Submit is enabled

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

Multiple Checkbox validation at javascript

i have multiple checkbox, and all of it must be checked.
i write down the code but it doesnt work.
this is the code
html sample::
<form name="pembres" id="pembres" method="POST" onSubmit="return validateform()" style="margin:0;">
<input type="checkbox" name="lanjut[]" value="setuju2" />
<input type="checkbox" name="lanjut[]" value="setuju3" />
<input type="checkbox" name="lanjut[]" value="setuju4" />
<input type="checkbox" name="lanjut[]" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
</form>
1st script at head tag
<script type="text/javascript">
function validateform(){
var success = false;
for (i = 0; i < document.pembres.elements['lanjut[]'].length; i++){
if (document.pembres.elements['lanjut[]'][i].checked){
success = true;
}
}
return success;
}
</script>
2nd script before /body
<script type="text/javascript">
var form = document.getElementById('pembres');
form.onsubmit = validateForm;
function validateForm() {
var isValid = false,
form = this,
els = form.elements['lanjut[]'];
i;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
return isValid;
}
</script>
You are setting isValid to true if any checkbox is checked, what you should do is return false if any checkbox is not checked.
function validateForm() {
var form = this,
els = form.elements['lanjut[]'], i;
for (i = 0; i < els.length; i += 1) {
if (!els[i].checked) {
return false;
}
}
return true;
}

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