Issue
I'm new to JavaScript and am trying to use it to validate a form before it is submitted. The first function, "validateYouTube" works and successfully checks if the YouTube code has been input, but the second function "validateSongandTitle" I am having issues with.
In order for the second function, validateSongandTitle, to be valid, I have the following condition:
- If the user doesn't select a song (as in they leave the drop-down as "No song selected", they will need to then input a "title" for it to be valid.
Here's what I have:
<form action="add-video.php" method="post" onsubmit="return validateForm(event)" id="AddVid">
<select name="songid">
<option value="">No song selected</option>
<option value="1">Dr Jones</option>
<option value="2">Spaceship</option>
<option value="3">Fantasy</option>
</select>
<input type="text" id="ytcode" name="ytcode" />
<div id="formyoutubecode"></div>
<input type="text" name="title" size="50" />
<div id="formtitle"></div>
<script>
function validateForm(event) {
event.preventDefault();
var YouTubeValid = validateYouTube();
var SongandTitleValid = validateSongandTitle();
if (!YouTubeValid || !SongandTitleValid) {
return;
}
event.target.submit();
}
function validateYouTube() {
var a = document.forms["AddVid"]["ytcode"].value;
if (a == null || a == "") {
document.getElementById('formyoutubecode').innerHTML = "<small><font color='red'>YouTube Code Required</font></small>";
return false;
}
return true;
}
function validateSongandTitle() {
var b = document.forms["AddVid"]["songid"].value;
var c = document.forms["AddVid"]["title"].value;
if ((b == "No song selected" && c == "")) {
document.getElementById('formtitle').innerHTML = "<small><font color='red'>Video title *Required</font></small>";
return false;
}
return true;
}
</script>
Please let me know why it won't work? Thanks in advance.
Solution
The main issue in your code is because your check to see if the select
has a valid option chosen is using the text of the option
element, not its value
. If you change b == "No song selected"
to b == ''
then the code will work.
That being said there's a few things which you could amend to improve the code quality:
- Use descriptive variable names.
a
andb
for example aren't very helpful to someone trying to understand your code. Usetitle
orcode
instead. - Don't attach your event handlers in HTML, it's no longer good practice. Bind them in your JS code using
addEventListener()
. - 'Cache' your Elements in variables which you can re-use where required instead of repeatedly selecting them from the DOM, which is a relatively slow operation.
- Avoid placing HTML in to the JS code as much as possible. With this in mind you can have the error messages within the DOM when the page loads and simply show/hide them with a CSS class that you toggle based on the validity of the input.
- The
<font>
element was deprecated a very long time ago and should never be used. Use CSS to style the font as you need.
Here's a working version with the above changes made:
const form = document.querySelector('#addvid');
const ytcodeField = document.querySelector('#ytcode');
const titleField = document.querySelector('#title');
const songidField = document.querySelector('#songid');
const formyoutubecode = document.querySelector('#formyoutubecode');
const formtitle = document.querySelector('#formtitle');
form.addEventListener('submit', e => {
const youTubeValid = validateYouTube();
const songAndTitleValid = validateSongAndTitle();
if (!youTubeValid || !songAndTitleValid) {
e.preventDefault(); // fields are invalid, prevent submission
}
});
function validateYouTube() {
const ytcode = ytcodeField.value.trim();
const isValid = ytcode !== '';
formyoutubecode.classList.toggle('hidden', isValid);
return isValid;
}
function validateSongAndTitle() {
const songid = songidField.value;
const title = titleField.value.trim();
const isValid = songid === '' || (songid !== '' && title !== '');
formtitle.classList.toggle('hidden', isValid);
return isValid;
}
.hidden {
display: none;
}
.error-message {
color: #F00;
}
<form action="add-video.php" method="post" id="addvid">
<select name="songid" id="songid">
<option value="">No song selected</option>
<option value="1">Dr Jones</option>
<option value="2">Spaceship</option>
<option value="3">Fantasy</option>
</select>
<input type="text" id="ytcode" name="ytcode" />
<div id="formyoutubecode" class="hidden error-message">
<small>YouTube Code Required</small>
</div>
<br />
<input type="text" id="title" name="title" size="50" />
<div id="formtitle" class="hidden error-message">
<small>Video title *Required</small>
</div>
<br />
<button>Submit</button>
</form>
Answered By - Rory McCrossan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.