我有一个简单的表单,我想在所有输入都填充且不为空时播放HTML 5视频。
问题:
如果是真正的播放视频,请检查所有表单输入是否都不为空,否则请执行其他操作。
这是我的解决方法
HTML:
<video id="videoPlayer" playsinline controls muted>
</video>
<form action="/action_page.php" class="form">
Enter your name:
<input name="firstname" type="text">
<input name="lastname" type="text">
<br><br>
<input type="submit">
</form>
Js
<script>
var movieSendData ="https://www.w3schools.com/html/mov_bbb.mp4"
var myVideo = document.getElementById('videoPlayer);
function playVideo(){
myVideo.play();
}
(function() {
var isValid = true;
$('.form').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
playVideo(movieSendData);
})();
</script>
不幸的是,我的解决方案无法按预期工作,我需要更改以获得我想要的东西吗?任何帮助将不胜感激
答案 0 :(得分:3)
您需要在视频上设置src,还需要进行if
检查,还需要遍历不在表单上的输入。
<script>
var movieSendData ="https://www.w3schools.com/html/mov_bbb.mp4"
var myVideo = document.getElementById('videoPlayer);
function playVideo(src) {
myVideo.src = src;
myVideo.play();
}
(function() {
var isValid = true;
$('.form input, .form textarea, .form select').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
if (isValid) {
playVideo(movieSendData);
}
})();
</script>
这将在init上运行(如果该表单不在script标记之前,则它将不起作用,它将找不到.form
),如果要在提交时运行,则需要:
$('.form').submit(function() {
var isValid = true;
$('.form input, .form textarea, .form select').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
if (isValid) {
playVideo(movieSendData);
}
return false;
});
如果出现错误,您可以将src值设置为null,则表示找不到视频标签,则需要将整个代码包装在$(function() { /* your code */ });
编辑:工作堆栈摘要
$(function() {
var movieSendData ="https://www.w3schools.com/html/mov_bbb.mp4"
var myVideo = document.getElementById('videoPlayer');
function playVideo(src) {
myVideo.src = src;
myVideo.play();
}
$('.form').submit(function(e) {
e.preventDefault();
var isValid = true;
$('.form input, .form textarea, .form select').each(function() {
if ( $(this).val() === '' )
isValid = false;
});
if (isValid) {
playVideo(movieSendData);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="videoPlayer" playsinline controls muted>
</video>
<form class="form">
Enter your name:
<input name="firstname" type="text">
<input name="lastname" type="text">
<br><br>
<!-- the input need to have a value or it can be a button -->
<input type="submit" value="submit">
</form>