Member Avatar for feoperro

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!

AH,

In what form is your "particular text" before it is handled by JavaScript?

Airshow

Member Avatar for feoperro

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.