0

Hi,

I would like to assign the substring of particular text to a javascript variable so that I can use the variable in an if statement. Can anyone help me here?

Thanks!

2
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by Airshow
0

I'm retrieving it as follows:

formName.textArea.value

I would like something like this:

if ((formName.textArea.value).substring(1,2) != "AB") {
     alert("Sorry, you need to start your word with AB");
}

Thanks,
-Ash.

0

Ash,

You're 95% of the way there, but of course you can make these checks and their messages as fancy as you like.

For example :

checkForm = function(f){
	var element, label = '', val, msg = '';
	//Check txt1:
	element = f.txt1;
	label = element.previousSibling.innerText;
	val = element.value;
	if(val == ''){ msg = "You must enter some text"; }
	else if(val.substr(0,2) != "AB") { msg = "Sorry, you need to start your word with AB"; }

	//Check txt2:
	if(msg == ''){
		element = f.txt2;
		label = element.previousSibling.innerText;
		val = element.value;
		if(val == ''){ msg = "You must enter a value"; }
		else if(val.substr(0,2).toUpperCase() != "YZ") { msg = "Sorry, you need to start your word with YZ or yz"; }
	}	
	
	if(msg) {
		alert(label + msg);
		return false;
	}
	return true;
}
<form name="myForm" action="" method="get" onsubmit="return checkForm(this);">
	<span>Text Area 1 : </span><textarea name="txt1"></textarea>
	<br/><br/>
	<span>Value 2 : </span><input name="txt2" />
	<br/><br/>
	<input type="submit" value="Submit">
</form>

I'm sure you will spot the pattern and be able to extend it.

The neat thing here is picking up the fields' labels and pre-pending them to the alert message. If you deliver your labels/form elements in a table (for good layout) then label = element.previousSibling.innerText; needs modifying but nothing too heavy.

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.