Why doesn't this javascript work?

Soldato
Joined
18 Oct 2002
Posts
18,306
Code:
function checkTitle() {
	var title = document.getElementById("title");
	
	if(title.value.length == 0) {
		alert("Your post must have a title.");
		return false;
	} else {
		return true;
	}
}

function checkLen() {
	var body = document.form1.bodytext.value.length;
	var maxlen = 10;
	if(body > maxlen) {
		alert('Message is too long.\nMax length: '+maxlen+'\nYour message length: '+body);
		return false;
	} else {
		return true;
	}
}

function validateForm() {
	var titleok = checkTitle();
	var lengthok = checkLen();
	
	if(titleok == true && lengthok == true) {
		return true;
	} else {
		return false;
	}
}

The validateForm function is called onclick of the submit button, doesn't work properly when called by onsubmit in the form tag either.

Basically, so long as I enter a title, it will accept a message in the bodytext textarea as long as you can type in.
However, if I type in a long message which exceeds the limit, but no title, hit submit it warns me that I have no title. I enter a title, hit submit again and now it tells me the message is too long.

Any ideas why it's giving this bizarre behaviour?
 
have it all in one function?

Code:
function validateform() {
    var title = document.getElementById("title");
    if(title.value.length == 0) {
        alert("Your post must have a title.");
	return false;
    }

    var body = document.form1.bodytext.value.length;
    var maxlen = 10;
    if(body > maxlen) {
        alert('Message is too long.\nMax length: '+maxlen+'\nYour message length: '+body);
	return false;
    }

    return true;
}

:)
 
hi, i think you must set var body = document.getElementById('bodytext'); before you can access its attributes ie. length. so after you have assigned body, you can do var bodyLength = body.value.length and compare this to your max length.
 
Last edited:
i think imay have put the syntax in wrong, maybe var bodyText = document.form1.getElementById('bodytext'); then var body = bodyText.value.length; i put this into a blank webpage in vs2005 and it worked with your code modified in this way. i didnt have a text box in form1 though so maybe thats why it wont work for you :( im assuming the id is set for the bodytext area as bodytext?
 
Back
Top Bottom