javascript - 单击单选按钮时必须输入文本框

标签 javascript c# jquery asp.net-mvc asp.net-mvc-5

我有一个 View ,其中添加到电子有 2 个单选按钮是和否。还有一个提交按钮。当单击"is"单选按钮时。数量文本框不应为空。但如果没有单击单选按钮,它可以为空。当单击“提交”按钮并选择"is"单选按钮时,此功能应该起作用。有什么想法吗? 我的观点:

 <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/> 
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>

我是 mvc 和 javascript 新手,也可以帮助我使用 javascript 代码。以及我应该将其与我的 View 链接起来的方式。 JavaScript:

    function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

最佳答案

$(function() {
  $("#radio").submit(function() {
    if ($('#yes').is(':checked') && !$.trim($('#quantity').val())) {
      alert("Please input the quantity.");
      return false;
    }
  });
});
    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        </head>
        <body>
            <form id=radio>
                Add to electronic <input type="radio" name="yes" id="yes" />Yes<input type="radio" name="yes" id="no" />No<br />
                <label>Quantity</label><input type="text" size="25" name="quantity" id="quantity" />
                <button type=submit name=insert>insert</button>
            </form>
        </body>
    </html>

关于javascript - 单击单选按钮时必须输入文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44938986/

相关文章:

javascript - 我如何告诉 jQuery 忽略空的服务器响应?

c# - 调用派生类的构造函数先于基类的构造函数执行

c# - 使用 ScrollViewer.ScrollToEnd() 执行 AutoScroll 仅在调试时有效,事件处理程序太简单

javascript - 跟踪用户更改网页的时间

javascript - jQuery 如何更改 img src 路径 onclick?

javascript - 尝试权限请求通知错误 Javascript

JavaScript,数组到字符串格式

javascript - 如何使用浏览器滚动来实现内部 div 的 x 溢出?

c# - 从文件名 c# 订购字符串 [] 路径

jquery - 有效性插件jquery问题?