0

I have the following simple HTML code and want to add a condition, like if fname <> a then display a comment "Wrong first name". I have the following code and am unsure where to put the conditional code. Please help as I am new to HTML!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" `enter code 
    here`"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<body>
<!DOCTYPE html>
<h2>HTML Forms</h2>
<form action="">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value=""><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value=""><br><br>
<input type="submit" value="Submit">
</form> 
    If fname <> a Then //This is where I go wrong!
    alert("Condition met")
    end If
</body>
</html>
marius
  • 1
  • 2

2 Answers2

0

You can try below code.

<form action="" onsubmit="myFunction()">
    <label for="fname">First name:</label><br>
    <input type="text" id="fname" name="fname" value=""><br>
    <label for="lname">Last name:</label><br>
    <input type="text" id="lname" name="lname" value=""><br><br>
    <input type="submit" value="Submit">
</form> 
<script type="text/javascript">
   function myFunction(){
     var fname = document.getElementById("fname").value;
     if(fname == '<>')
        alert("Condition met")
   }
</script>
0

HTML Inputs have some basic validation that you can implement with their input attributes, like the maxlength, minlength, size, or the pattern attribute that takes a regular expression (if you are familiar with them).

<input type="text" pattern="a" name="fname" id="fname" />

This will force the user to submit exactly the letter "a" as name (just an example of course! You should write a more useful regex). In case of invalid input, the browser will display an error message.

If you want to go further, and have full control over the (client-side) validation, then you need JavaScript.

<script>
    const nameInput = document.getElementById('fname');

    if (nameInput.value !== 'the_value_to_check_against') {
        alert('Incorrect name');
    }
</script>

Learn more here.

PS: This may not work if you are not using HTML5. If it is your code, I suggest you use HTML5 by replacing the first line (. Remove the xmlns attribute in the and also remove the two other .

Prince Dorcis
  • 955
  • 7
  • 7