Null error is coming document.getElementByid("dthchannel" + [i] is null) - javascript

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;

You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Related

Disable/Enable HTML Button based on Existing Functions

I have a function running onclick from HTML button and need to add disabling the button on success but NOT on return = false.
I've tried toggling, disabling directly in the HTML and inserting changing the HTML attribute within my current function.
var amtCount = 0;
function addToLineItem()
{
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Message");
return false;
}
if($("#aprDate").val() == "")
{
alert("Please date.");
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please .");
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("total amount does not match.");
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice');
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}
function onQuerySucceeded()
{
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}
function onQueryFailed(sender, args)
{
alert('not inserted');
}
This runs fine but if the HTML Button is clicked quickly, the function runs and creates duplicate data.
You should disable the button while you are acting on the click. Then the user cannot queue up another update until the first one finishes. Set an internal variable saying that the work is in progress, disable the button, and then clear the flag when you get the result (success or fail).
For instance:
$("#btnSubmit").click(function() {
$("#btnSubmit").prop("disabled", true);
// do your work here, waiting for success or failure
$('#btnSubmit').prop("disabled", false);
})
or:
$("button").click(function(e) {
$(e.currentTarget).prop('disabled', true);
window.setTimeout(function() {
$(e.currentTarget).prop('disabled', false);
}, 5000);
})
I found what I needed and with some experimentation with where to put the "disabled", false lines was able to get to the solution. I got the simple code from Palash
https://stackoverflow.com/users/1823841/palaѕн
All versions of jQuery after 1.6
Disabling and enabling a html input button
Thank you all for helping... New Code....
var amtCount = 0;
function addToLineItem()
{
**$("#IApprove").attr("disabled", true);**
var totalAmount = 0.0;
var valid = true;
var difference = [];
$.each($(".tbodys tr"),function(index,vs)
{
for(var tdcnt = 0; tdcnt < vs.children.length - 1; tdcnt++)
{
if(tdcnt != 5)
if(vs.children[tdcnt].firstElementChild.value == "" || vs.children[tdcnt].firstElementChild.value == undefined)
valid = false;
}
if(vs.children[9].firstChild.value != "" && vs.children[9].firstChild.value != undefined)
{
RMID.push(vs.children[9].firstChild.value);
}
});
if(CodingListItem.length > 0)
{
difference = arr_diff(CodingListItem,RMID);
}
if(valid == false)
{
alert("Please add Line Items with Required Information. GL coding missing.");
**$("#IApprove").attr("disabled", false);**
return false;
}
if($("#aprDate").val() == "")
{
alert("Please add approver date.");
**$("#IApprove").attr("disabled", false);**
return false;
}
$.each($(".tbodys tr .nine"),function(index,vs){
totalAmount += parseFloat(vs.firstElementChild.value.replace(/,/g, ""));
});
if($("#Total")[0].innerText == "")
{
alert("Please add Line items.");
**$("#IApprove").attr("disabled", false);**
return false;
}
//if(parseFloat($("#invTotal").val().replace(/,/g, "")) != totalAmount)
if(parseFloat($("#invTotal").val().replace(/,/g, "")) != parseFloat($("#Total")[0].innerText.replace(/,/g, "")))
{
alert("Line item's total amount does not match with total invoice amount.");
**$("#IApprove").attr("disabled", false);**
return false;
}
SP.SOD.executeFunc("sp.js", 'SP.ClientContext', function()
{
try
{
var clientContext = SP.ClientContext.get_current();
var web = clientContext.get_web();
var oList = clientContext.get_web().get_lists().getByTitle('Invoice Approval and Coding');
///////////// Delete Items //////////////////
if(difference.length > 0)
{
$.each(difference, function( index, value )
{
deleteListItem(parseInt(value));
});
}
$.each($(".tbodys tr"),function(i,v)
{
if(v.children[9].firstChild.value != "" && v.children[9].firstChild.value != undefined)
{
var itemType1 = GetItemTypeForListName("InvoiceLineItem");
var item1 = {
"__metadata": { "type": itemType1 },
"Title": v.children[0].firstChild.value,
"InvoiceIDId": parseInt(INV),
"Entity": v.children[1].firstChild.value,
"MS": v.children[2].firstChild.value,
"LocationId": parseInt(v.children[3].firstChild.value),
"DepartmentId": parseInt(v.children[4].firstChild.value),
"Account": v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text,
"SubAccount": v.children[6].firstChild.value,
"GLCode": v.children[7].firstChild.value,
"Amount": v.children[8].firstChild.value
};
updateListItem(parseInt(v.children[9].firstChild.value), "Invoice Approval and Coding", _spPageContextInfo.webAbsoluteUrl, item1, function () {
amtCount = amtCount + 1;
updatePendingInvoice(amtCount);
}, function () { errorMsg = true; });
}
else
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', v.children[0].firstChild.value); //Line Description
oListItem.set_item('InvoiceID', INV);
oListItem.set_item('Entity', v.children[1].firstChild.value);
oListItem.set_item('MS', v.children[2].firstChild.value);
oListItem.set_item('Location', v.children[3].firstChild.value);
oListItem.set_item('Department', v.children[4].firstChild.value);
oListItem.set_item('Account', v.children[5].children[1].options[v.children[5].children[1].selectedIndex].text);
oListItem.set_item('SubAccount', v.children[6].firstChild.value);
oListItem.set_item('GLCode', v.children[7].firstChild.value);
oListItem.set_item('Amount', v.children[8].firstChild.value);
oListItem.set_item('Date', $("#aprDate").val());
oListItem.set_item('Comment', $("#cmt").val());
oListItem.update();
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}
});
}
catch(err)
{
alert(err.message);
}
});
}

Javascript condition not working as expected

I have a JS code which works fine when
checkQueryString != "M"
but When the value becomes checkQueryString == "M" it doesn't goes inside the loop
Here is my code.
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
if(checkQueryString == "M")
{
alert('Value is M now');
}
else {
alert('Kindly select the stage');
}
}
}
So my question is, why it doesn't goes inside if when it matches to M
Because
if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
Has inside if (checkQueryString == "M")
So try this
function GridExpInfo_ClientAdd(record) {
var checkQueryString = '<%= Request.QueryString["Mode"] %>';
if (checkQueryString != "M") {
if ($('input:checked').length > 0) {
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefNo").disabled = true;
document.getElementById("GridExpInfo_tplRowEdit3_ctl00_txtExpRefDt").disabled = true;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').value = "";
var last_value = 0;
var last_text;
var checkboxlist = document.getElementById('ddlStatus');
var checkOptions = checkboxlist.getElementsByTagName('input');
var listSelected = checkboxlist.getElementsByTagName('label');
for (i = 0; i < checkOptions.length; i++) {
if (checkOptions[i].checked == true) {
last_text = listSelected[i].innerText;
last_value = checkOptions[i].value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').innerHTML = "";
var ObjPriOptionExp = document.createElement("OPTION");
ObjPriOptionExp.text = last_text;
ObjPriOptionExp.value = last_value;
document.getElementById('GridExpInfo_tplRowEdit3_ctl00_ddlStageType').add(ObjPriOptionExp);
}
}
}
} else if (checkQueryString == "M") {
alert('Value is M now');
} else {
alert('Kindly select the stage');
}
}

How can I customize a MadMimi embedded email form?

I'm using MadMimi to collect emails on a pre-launch website (http://www.saashopper.com), and need to change the embedded form so it doesn't open a new tab when confirming the email signup. I want it to just confirm underneath the input field that the signup was successful (or not, and why). How should I go about doing this?
Here's the embed code MadMimi provided:
<form accept-charset="UTF-8" action="https://madmimi.com/signups/subscribe/114920" id="mad_mimi_signup_form" method="post" target="_blank">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓"/>
<input name="authenticity_token" type="hidden" value="5twZyvvQepHt/3X9lhtT+Z3Zeb1OFVeAPFMLBjbukwA="/>
</div>
<div class="mimi_field required">
<label for="signup_email">Email*</label>
<br/>
<input id="signup_email" name="signup[email]" type="text" data-required-field="This field is required" placeholder="you#example.com"/>
</div>
<div>
<input type="submit" class="submit" value="Subscribe" id="webform_submit_button" data-default-text="Subscribe" data-submitting-text="Sending..." data-invalid-text="↑ You forgot some required fields" data-choose-list="↑ Choose a list">
</input>
</div>
</form>
<script type="text/javascript">
(function() {
var form = document.getElementById('mad_mimi_signup_form'),
submit = document.getElementById('webform_submit_button'),
validEmail = /.+#.+\..+/,
isValid;
form.onsubmit = function(event) {
validate();
if(!isValid) {
revalidateOnChange();
return false;
}
};
function validate() {
isValid = true;
emailValidation();
fieldAndListValidation();
updateFormAfterValidation();
}
function emailValidation() {
var email = document.getElementById('signup_email');
if(!validEmail.test(email.value)) {
textFieldError(email);
isValid = false;
} else {
removeTextFieldError(email);
}
}
function fieldAndListValidation() {
var fields = form.querySelectorAll('.mimi_field.required');
for(var i = 0; i < fields.length; ++i) {
var field = fields[i],
type = fieldType(field);
if(type == 'checkboxes' || type == 'radio_buttons') {
checkboxAndRadioValidation(field);
} else {
textAndDropdownValidation(field, type);
}
}
}
function fieldType(field) {
var type = field.querySelectorAll('.field_type');
if(type.length > 0) {
return type[0].getAttribute('data-field-type');
} else if(field.className.indexOf('checkgroup') >= 0) {
return 'checkboxes';
} else {
return 'text_field';
}
}
function checkboxAndRadioValidation(field) {
var inputs = field.getElementsByTagName('input'),
selected = false;
for(var i = 0; i < inputs.length; ++i) {
var input = inputs[i];
if((input.type == 'checkbox' || input.type == 'radio') && input.checked) selected = true;
}
if(selected) {
field.className = field.className.replace(/ invalid/g, '');
} else {
if(field.className.indexOf('invalid') == -1) field.className += ' invalid';
isValid = false;
}
}
function textAndDropdownValidation(field, type) {
var inputs = field.getElementsByTagName('input');
for(var i = 0; i < inputs.length; ++i) {
var input = inputs[i];
if(input.name.indexOf('signup') >= 0) {
if(type == 'text_field') {
textValidation(input);
} else {
dropdownValidation(field, input);
}
}
}
htmlEmbedDropdownValidation(field);
}
function textValidation(input) {
if(input.id == 'signup_email') return;
var val = input.value;
if(val == '') {
textFieldError(input);
isValid = false;
return;
} else {
removeTextFieldError(input)
}
}
function dropdownValidation(field, input) {
var val = input.value;
if(val == '') {
if(field.className.indexOf('invalid') == -1) field.className += ' invalid';
onSelectCallback(input);
isValid = false;
return;
} else {
field.className = field.className.replace(/ invalid/g, '');
}
}
function htmlEmbedDropdownValidation(field) {
var dropdowns = field.querySelectorAll('.mimi_html_dropdown');
for(var i = 0; i < dropdowns.length; ++i) {
var dropdown = dropdowns[i],
val = dropdown.value;
if(val == '') {
if(field.className.indexOf('invalid') == -1) field.className += ' invalid';
isValid = false;
dropdown.onchange = validate;
return;
} else {
field.className = field.className.replace(/ invalid/g, '');
}
}
}
function textFieldError(input) {
input.className = 'required invalid';
input.placeholder = input.getAttribute('data-required-field');
}
function removeTextFieldError(input) {
input.className = 'required';
input.placeholder = '';
}
function onSelectCallback(input) {
if(typeof Widget != 'undefined' && Widget.BasicDropdown != undefined) {
var dropdownEl = input.parentNode,
instances = Widget.BasicDropdown.instances;
for(var i = 0; i < instances.length; ++i) {
var instance = instances[i];
if(instance.wrapperEl == dropdownEl) {
instance.onSelect = validate;
}
}
}
}
function updateFormAfterValidation() {
form.className = setFormClassName();
submit.value = submitButtonText();
submit.disabled = !isValid;
submit.className = isValid ? 'submit' : 'disabled';
}
function setFormClassName() {
var name = form.className;
if(isValid) {
return name.replace(/\s?mimi_invalid/, '');
} else {
if(name.indexOf('mimi_invalid') == -1) {
return name += ' mimi_invalid';
} else {
return name;
}
}
}
function submitButtonText() {
var invalidFields = document.querySelectorAll('.invalid'),
text;
if(isValid || invalidFields == undefined) {
text = submit.getAttribute('data-default-text');
} else {
if(invalidFields.length > 1 || invalidFields[0].className.indexOf('checkgroup') == -1) {
text = submit.getAttribute('data-invalid-text');
} else {
text = submit.getAttribute('data-choose-list');
}
}
return text;
}
function revalidateOnChange() {
var fields = form.querySelectorAll(".mimi_field.required");
for(var i = 0; i < fields.length; ++i) {
var inputs = fields[i].getElementsByTagName('input');
for(var j = 0; j < inputs.length; ++j) {
inputs[j].onchange = validate;
}
}
}
})();
</script>
You can add and iframe under the input field like this:
<iframe name="myFrame">
<p>Your browser does not support iframes.</p>
</iframe>
And then change the target attribute of the form and give it the iframe name:
<form accept-charset="UTF-8" action="https://madmimi.com/signups/subscribe/114920" id="mad_mimi_signup_form" method="post" target="myFrame">
Thus the result will be shown in the iframe window in the same page.

Could someone explain why my functions are not working?

So I'm very new to JavaScript and I'm trying a very simple enter text and check it. It doesn't seem to work the way I want it to. I want all of the inputs to go through the checkInputs. After All of them are 100% I want it to check if hoursWorked and horlyRate are numbers above 0. It seems to just move on to the checkNumberValidation without checking if all inputs are filled.
I got:
function checkNumbersValidation(field){
if( isNaN(field) ) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
var test = false;
do{
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
}else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}else {
tests = true;
}
}while (test = false)
}
function handelCalcButtonClicked (e) {
var passFirstTests = false;
var textFields = ["fullName", "hoursWorked", "hourlyRate"];
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
checkInputs(field);
}
if( **something** ) {
var numberFields = ["hoursWorked", "hourlyRate"]
for ( var i = 0; i < numberFields.length; i++ ) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
clearly I don't know what I'm doing. In the function handelCalcButtonClicked I'm not sure how to move on the the next part (the part Saying something). Any help would be nice!
Inside checkNumbersValidation you need to do the isNan call on field.value, not field:
if( isNaN(field.value) )
If you want to know if all of your fields have gone through checkInputs and have passed, you will need checkInputs to return whether or not each field has passed:
function checkInputs(field) {
if ( field.value === null || field.value.trim() === "" ) {
field.value = "Input needed";
//set focus
field.focus("");
return false;
} else if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return false;
}
return true;
}
This will allow you to know if all fields have passed the check:
var passedAllChecks = true;
for( var i = 0; i < textFields.length; i ++ ) {
var field = document.getElementById(textFields[i]);
passedAllChecks = checkInputs(field) && passedAllChecks;
}
if(passedAllChecks) {
/* do number validation stuff */
}
What about this:
function checkNumbersValidation(field) {
if (isNaN(field)) {
field.value = "Must be a number";
field.focus("");
}
}
function checkInputs(field) {
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
return;
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
var textFields = ["fullName", "hoursWorked", "hourlyRate"],
numberFields = [ "hoursWorked", "hourlyRate"],
i,
field;
for (i = 0; i < textFields.length; i++) {
field = document.getElementById(textFields[i]);
checkInputs(field);
}
for (i = 0; i < numberFields.length; i++) {
field = document.getElementById(numberFields[i]);
checkNumbersValidation(field);
}
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});
or:
function checkInput(field, isnumber) {
if (!field) return;
if (isnumber === true && isNaN(field)) {
field.value = "Must be a number";
field.focus("");
return;
}
if (field.value === "0") {
field.value = "Can't be zero";
field.focus("");
return;
}
if (!field.value || !field.value.trim()) {
field.value = "Input needed";
field.focus("");
}
}
function handelCalcButtonClicked (e) {
checkInput(document.getElementById('fullName');
checkInput(document.getElementById('hoursWorked', true);
checkInput(document.getElementById('hourlyRate', true);
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("calcButton").addEventListener("click", handelCalcButtonClicked, false);
});

Javascript showing alert without refreshing the page

when I click submit button it shows the validation right but after that alert message the page is being refreshed and i loos all other datas from the fields :S, how can i make it to still remain the others field filled.
I tried to remove the window.location.reload() after submit event is called but still not working :S. ANYONE any suggestion?
this is the code:
function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload()
return true;
}
}
Two problems...
Missing return
onSubmit="return formValidation();"
Missing return true;
if (validsex(umsex, ufsex)) { return true; }

Categories

Resources