![](/img/trans.png)
[英]How to use javascript for html form validation to valid number only?
[英]How to use html form validation to display image
我創建了一個HTML表單,其中有許多不同的文本框。 我想要做的是創建一個javascript腳本,它將在沒有文本的框旁邊顯示小圖像。 這是我想要做的一個例子:
目前我已經創建了以下腳本來驗證我想要的表單,但是它只顯示一個彈出框,因為我不知道如何顯示圖像/文本。 這是我的代碼:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["email_form"]["name"].value;
if (x==null || x=="")
{
alert("Please enter your name in the box provided.");
return false;
}
var x=document.forms["email_form"]["email"].value;
if (x==null || x=="")
{
alert("Please enter your e-mail address in the box provided.");
return false;
}
var x=document.forms["message-title"]["name"].value;
if (x==null || x=="")
{
alert("Please enter a message title in the box provided.");
return false;
}
var x=document.forms["email_form"]["message"].value;
if (x==null || x=="")
{
alert("Please enter your message in the box provided.");
return false;
}
}
</script>
請有人指出我正確的方向嗎?
您可以在輸入元素旁邊放置錯誤圖像元素,但將display屬性隱藏在css中。 您可以為鏈接到其輸入元素的每個錯誤圖像設置一個id。 例如,對於電子郵件輸入,除了它之外還有img元素。 有一個這樣的初始CSS - >
#email_form img{
display: none;
}
然后在你的javascript中,只需顯示隱藏的圖像 -
var x=document.forms["email_form"]["email"].value;
if (x==null || x=="")
{
var error_image = document.getElementById('error_email');
error_image.style.display = 'inline';
alert("Please enter your e-mail address in the box provided.");
return false;
}
在你css中定義一個類
.validateimage
{
display:none;
}
並將該類分配給所有圖像標記,如
<img class="validateimage" id="image1">
.
.
.
然后
<script type="text/javascript">
function validateForm()
{
var x=document.forms["email_form"]["name"].value;
if (x==null || x=="")
{
document.getElementById('image1').style.display='block';
return false;
}
var x=document.forms["email_form"]["email"].value;
if (x==null || x=="")
{
document.getElementById('image2').style.display='block';
return false;
}
var x=document.forms["message-title"]["name"].value;
if (x==null || x=="")
{
document.getElementById('image3').style.display='block';
return false;
}
var x=document.forms["email_form"]["message"].value;
if (x==null || x=="")
{
document.getElementById('image4').style.display='block';
return false;
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.