Check if first 2 Letters Equal Certain Characters in Input Field


I am having trouble with some javascript code that checks the first 2 letters of what the user inputs and whether it equals a certain set of characters.

If the user for instance types in ‘TT’ in an input field, then i want the holding div to disappear, if anything else is typed in then this action wont happen. My code is below:

<script type="text/javascript">
function checkCode() {
	var x=document.forms["myform"]["code"].value.substring(0, 2);
	if (x == 'TT')
		document.getElementById('main').style.display = 'none';

<div id="main">
<form name="myform" action="check-form.php" method="post">
    <table id="table" cellpadding="0" cellspacing="0">
        <td><input id="code" type="text" name="code" onkeyup="checkCode()" onchange="checkCode()" /></td><td><input type="submit" value="SEND"/></td>

I believe the problem lies in the javascript line: “if (x == ‘TT’)”, as the rest of the script responds but it just doesnt recognise whether ‘x’ starts with ‘TT’

Any help would be greatly appreciated

substring(0,2) gets the first 3 characters- you want substring (0,1), or iust see if x.indexOf(‘TT’) ===0.

But that doesn’t explain why it doesn’t work…

maybe try getting the input with document.getElementById(‘code’).value

There’s a scripting error that’s preventing the script from working.
The error is that the if statement is missing an opening brace.

Additionally, the current form name technique that you are using is similar to this:

<a name="mylink" ...>

and that is a technique from the past century. Only use names for elements within a form. Use unique identifiers instead to uniquely identify an element that you want to work with.

<form id="myform" ...>

Then you can use this from the script:

var form = document.getElementById('myform');
var x = form.elements.code.value.substring(0, 2);

Other problems are the inline event attributes that you’re using. Get rid of them and use scripting to assign the event, and you won’t even need to explicitly reference the form. You can get it implicitly from the this keyword that the scripting event runs under instead.

That then leaves your HTML code much less cluttered.

<input name="code" />

Put your script at the bottom, just before the </body> tag as you should do to help speed up your web page, which also allows you to directly work with page elements:

var form = document.getElementById('myform');
form.elements.code.onkeyup = checkCode;
form.elements.code.onchange = checkCode;

and then your checkCode function can get the element just with the this keyword. If you need the form, you can also use this.form

var x = this.value.substring(0, 2);

Thanks for that Paul, the bracket was obvious once you mentioned it.

Thanks also for the help in cleaning up the code, much appreciated!