Javascript object is null or not object in IE - javascript

I have a form to which a checkbox is added by javascript, when the form is submitted it checks if the checkbox has been ticked or not. This works fine in Firefox or Chrome, but in IE7 or 8 it causes an error document.myform.mycheckbox.checked is null or not an object.
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "mycheckbox";
checkbox.value= 291;
var div = document.getElementById("addcb");
div.appendChild(checkbox);
checkbox.checked = false;
In the form tag I have onSubmit="return CheckForm();", which works ok in Firefox or Chrome, but in IE7 or 8 it submits the form without checking the form or other form objects.
if (document.myform.mycheckbox.checked == false){
errorMsg += "\n\tAgree \t- Please Click I Agree Checkbox";
}
//If there is aproblem with the form then display an error
if ((errorMsg != "") || (errorMsgLong != "")){
msg = "_______________________________________________________________\n\n";
msg += "The form has not been submitted because there are problem(s) with the form.\n";
msg += "Please correct the problem(s) and re-submit the form.\n";
msg += "_______________________________________________________________\n\n";
msg += "The following field(s) need to be corrected: -\n";
errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
return false;
}
return true;
I used the Developer tools to create a Brakpoint which reports the error:
document.myform.mycheckbox.checked is null or not an object

While creating it, give it an ID as well
checkbox.id = "mycheckbox";
and then to find it do a
if (document.getElementById("mycheckbox").checked == false)

Related

interactive PDF Form-Validation Javascript

I'm trying to validate my interactive PDF. So if i click on a button (for validating) there's following code behind it:
var isBlank = false;
var blank = "Please fill following fields:";
var isNotValid = false;
var notValid = "Please check input data in following fields:";
var message = "";
var t = ['Division', 'Oragnisationseinheit', 'Name', 'KZZ', 'Privataddresse'];
var i;
for(var i=0; i<t.length;i++){
//validation text fields needs to be filled in
if (this.getField(t[i]).value == "") {
blank = blank + "\n" + this.getField(t[i]).name;
isBlank = true;
}
//validation text field must contain only lower case letters
if (/^[a-z]*$/.test(this.getField(t[i]).value) == false) {
notValid = notValid + "\n" + this.getField(t[i]).name;
isNotValid = true;
}
//generate message
if (isBlank == true) {
message = blank + "\n" + "\n";
}
if (isNotValid == true) {
message = message + notValid;
}
}
//check all conditions
if ((isBlank == true) || (isNotValid == true)) {
//show message
app.alert({ cMsg: message, cTitle: "Input data error" });
}
The problem is now, if I press the button there's no reaction. --> the var message wont being displayed. Where is the issue?
Thanks for all ideas.
You might try instead to add a custom validation script that would first check to be sure the field isn't blank and if not, simply change the input to lower case so the user doesn't need to modify the field themselves.
Add the following code to the custom field validate script. This should work for any text field.
if (event.value.length == 0) {
app.alert({ cMsg: event.target.name + " cannot be blank.", cTitle: "Input data error" });
}
else {
event.value = event.value.toLowerCase();
}

if statement in jQuery not working in Chrome or Safari

I have the following code that is working in IE 8 but not in Chrome or Safari:
$(document).ready(function(){
$('.goRedIMG').on('click',function(event){
var ischecked = false;
var isOKtoSubmit = true;
var alertMessage = 'No tools have been selected';
var statusvar = '';
var transferstatusvar = '';
var action = $('#uTransaction option:selected').html();
$('.chkaction').each(function() { //loop through each checkbox
statusvar = $(this).closest('tr').children('.recordStatus').html();
transferstatusvar = $(this).closest('tr').children('.transferstat').html()
if($(this).prop('checked')) {
ischecked = true;
//alert(action);
// alert(statusvar);
// alert(transferstatusvar);
if (action == 'Recover'){
if (statusvar != 'OOS'){
// alert(statusvar);
isOKtoSubmit = false;
alertMessage = 'One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK';
}
}
if(isOKtoSubmit && ischecked !== false && action !== '--Select One--'){
$('#toolActions').submit();
}else {
alert(alertMessage);
}
});
If a user chooses Recover and chooses a record that has a status that is in 'OOS' they are getting the alert message in Chrome that the record does not have the correct status. In IE if you choose the same record the alert message does not appear and that would be correct.
When I use your code like this:
var action = 'Recover';
var statusvar = 'OOS';
if (action == 'Recover') {
if (statusvar != 'OOS') {
alert('One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK');
}
}
in both browsers it runs correctly. I think you have problem with your data.
In your original code try to use
alert(statusvar + ' - length:' + statusvar.length)
And check the character lenght of the variable. This way you can see if there is any funny character in your statusvar variable.

Basic Form Validation with JavaScript/HTML

I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.
First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.
You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer
The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}

Validation does not work in Firefox, works fine in IE

I have an email validation code on client side. It works fine/as expected in IE but somehow doesnot show error messages in Firefox.
Below is the code:
<asp:ImageButton ID="btnLink" runat="server" AlternateText="ClickHere" OnClientClick="return onCClick();" OnClick="btnLink_Click"/>
<div id="errorEmail" runat="server"></div>
//function to validate
function onCClick() {
//clear error message
document.getElementById('<%=errorEmail.ClientID%>').innerText = "";
//if validation fails
if (validateEmail() != true) {
//show error message
document.getElementById('<%=errorEmail.ClientID%>').innerText = "Invalid Email Address.";
return false;
}
}
function validateEmail() {
var emailId = document.getElementById('<%=txtEmail.ClientID%>').value;
var emailPattern = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
return emailPattern.test(emailId);
}
Is there something which i should have taken care of ? My error message div is set to blank but not invisible anywhere(in that case javascript also would not have worked)
innerText is not cross browser, firefox uses textContent
You can use a function like this:
function changeText(elem, changeVal) {
if ((elem.textContent) && (typeof (elem.textContent) != "undefined")) {
elem.textContent = changeVal;
} else {
elem.innerText = changeVal;
}
}
or just use innerHTML.
Better you try innerHTML.. it will work..
document.getElementById('errorEmailAddress').innerHTML = "Error Message";

replace span text (error) after retyping vars jquery javascript

Whats the best approach for jquery realtime validation checking?
Onsubmit the span with each label gets changed to for example:
enter your email | submit | email is not correct
but when you change the value again you have to submit again to remove the email is not correct message.
So im searching for a "realtime" error handling or something. What is the best approach to do this considering my code?
<script type="text/javascript">
$(document).ready(function()
{
$('form #status').hide();
$('#submit').click(function(e) {
e.preventDefault();
var valid = '';
var required = 'is required';
var name = $('form #name').val();
var subject = $('form #subject').val();
var email = $('form #email').val();
var message = $('form #message').val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//error checking
if (name == '' || name.length <= 2)
{
valid = '<p>your name' + required + '</p>';
$('form #nameInfo').text('Name can not contain 2 characters or less!');
}
if(!filter.test(email)){
valid += '<p>Your email'+ required +'</p>';
$('form #emailInfo').text('Email addres is not valid');
}
if (message == '' || message.length <= 5)
{
valid += '<p>A message' + required +'</p>';
$('form #messageInfo').text('Message must be over 20 chars');
}
if (valid != '')
{
$('form #status').removeClass().addClass('error')
.html('<strong>Please correct errors belown </strong>' + valid).fadeIn('fast')
}
else
{
$('form #status').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
</script>
I'm not 100% sure I understand the question. Do you want to reset #emailInfo text when user corrects the input? If so, you can use either onchange, onkeypres or on focus events:
$("#email").change(function(){
$("#nameInfo").text("Enter your email");
});
Better yet, you can do your validation on corresponding field change rather than on form submit.
The following example will validate email field on each key pressed:
$("#email").keypress(function(){
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email = $('#email').val();
if(!filter.test(email)){
$('#emailInfo').text('Email addres is not valid');
} else {
$('#emailInfo').text('');
}
});
You can validate other fields in a similar way. Or you can use jQuery Validation plugin.

Categories

Resources