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 value of <select> tags is based off the value of its <option>s, not the text. In other words:
Change b == "No song selected" to b == "".
Or
Change <option value="">No song selected</option> to <option value="No song selected">No song selected</option>.