Javascript简单验证问题

时间:2013-04-30 16:07:11

标签: javascript html forms

我是新手在Javascript中,这是我的学习过程。

好吧,我有一个html表单,我试图用Javascript验证它。以下是我的一些验证码:

var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}

var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");

if (x==null || x=="")
{
alert("Emaill address require");
return false;
}

在这种形式中,我有2个下拉字段,如果两个字段都为空,我想要验证它,并使用以下代码:

var x=document.forms["myForm"]["pf_social_plan"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");

var p=document.forms["myForm"]["pf_combo_offer_details"].value;
var atpos=p.indexOf("@");
var dotpos=p.lastIndexOf(".");


if (x==null || x=="" && p==null || p=="")
{
alert("Select only one drop down field");
return false;
}

但它不起作用。我知道我的代码中存在问题。你们能帮助我吗? 谢谢。

更新HTML代码:

<tr>
<td>Social Combo Packages Combo A-C= tweets / pin / likes & Youtube page 1 service 
</td>
<td valign="top">
<select id="pf_social_plan" name="pf_social_plan">
<option value="" selected="selected">--Select--</option>
<option value="Social Combo Package A = $25.00">Social Combo Package A = 
$25.00</option>
<option value="Social Combo Package B = $42.00">Social Combo Package B = 
$42.00</option> 
</select>
</td>
</tr>

<tr>
<td valign="top">social Combo offer details</td>
<td valign="top"><textarea id="pf_combo_offer_details" name="pf_combo_offer_details" 
rows="5" cols="75" placeholder="Please provide social Combo offer details"><?php 
if(isset($_POST['pf_combo_offer_details'])) echo $_POST['pf_combo_offer_details']; 
?></textarea>   </td>
</tr>

2 个答案:

答案 0 :(得分:0)

要获取下拉列表的值,请执行以下操作:

var x=document.forms["myForm"]["pf_social_plan"];
var value = x.options[x.selectedIndex].value;

答案 1 :(得分:0)

要验证选择(下拉列表),请执行以下操作:

 var xSelectedValue=document.forms["myForm"]["pf_social_plan"].value;

 var pSelectedValue=document.forms["myForm"]["pf_combo_offer_details"].value;



 if ((xSelectValue != null || xSelectValue != '') && (pSelectValue != null || pSelectValue != ''))
 {
       alert("Select only one drop down field");
       return false;
 }

 return true;