javascript - 在下拉选择和验证时显示文本框

标签 javascript jquery html validation

我有一个隐藏的 div,它有一个文本框,当从下拉列表中选择“other”时,它会变得可见。

我要做的是验证它。 When other is selected it should validate the textbox field and not let the form submit.

我已经尝试过,但不允许提交表单,当文本框被隐藏时。

function validateForm()
{
var x=document.forms["form1"]["textbox"].value;
if (x==null || x=="")
{
alert("Text box be filled out");
return false;
}
}

只有在选择other 时才验证文本框字段,而在未选择other 且隐藏文本框时不验证

这是我的代码

<head>
<script src="../Library/jqueryLatest.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form action="index.cfm" method="post" name="form1"> 
<select name="description" id="description">
<option value="Type 1">Type 1</option>
<option value="Type 2">Type 2</option>
<option value="Type 3">Type 3</option>
<option value="Other">Other</option>
</select>
<div id="Other" class="showother" style="display:none">Hello <input name="textbox" id="textbox" type="text">
</div>
<input name="submit" value="SUBMIT" type="submit">   
</form>

</body> 
<script type="text/javascript"> 

$(function () {
$('#description').change(function () {
    $('.showother').hide();
    $('#' + $(this).val()).show();
});
});

</script>

最佳答案

已更新

function validateForm(){
   var x= $("form input#textbox").val();
   if ($('.showother').is(":visible")) {
    if (x==null || x=="")
    {
     alert("Text box be filled out");
     return false;
    }
   }
}
$(document).ready(function(){
 $('#description').change(function () {

    if ($(this).val() == "Other") {
       $('.showother').show();
    } else {
      $('.showother').hide();
    }

 });
});

演示 http://jsfiddle.net/27Syr/643/

关于javascript - 在下拉选择和验证时显示文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21288019/

相关文章:

html - 输入提交控件的样式与 @html.ActionLink 相同

javascript - 通过 COM 从 MATLAB 向 Google Earth 插件提供数据

jquery - [Vue警告] : Error in nextTick: "TypeError: this.method is not a function" - Error shows only on my console but working as expected on browser

javascript - 是否有非可视化的 HTML 标签?

html - 如果相邻单元格通过 CSS 为空,则让表格单元格跨越多列

jquery - 列表悬停显示图像 jquery

javascript - 火存储 : Couldn't Serialize object of type 'ArrayUnionTransform'

javascript - JS 中 new Date() 的问题

php - native 表单提交后的 ajax $.post 函数

javascript - jquery如何获取点击了哪个链接