猿问

如果输入值等于javascript中的给定值,则执行表单操作?

以下是我的表单HTML代码,我在表单外部使用了表单按钮,它对我来说工作正常。我的字段的值是从Mysql获取的,就像状态是主动的,被动的或死的,我正在寻找的是,只有当获取输入值等于被动或死完全不知道该怎么办时,我的表单才会执行。


<input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" />

<form action="/student/create" method="get" id="nameform">

  <div class="row">

    <div class="col-sm-4">

      <div class="form-group" style="display:none;">

        <label>Current Status</label>

        <input type="text" value="<?php echo $enquiry_data['status']; ?>" name="status" class="form-control">

      </div>

    </div>

</form>


繁星淼淼
浏览 122回答 4
4回答

呼唤远方

尝试此操作,在窗体上使用以验证输入字段。onsubmit="return validateForm()"function validateForm() {&nbsp; var current_status = document.forms["nameform"]["status"].value;&nbsp; var default_value = ['passive', 'dead'];&nbsp; if (!default_value.includes(current_status)) {&nbsp; &nbsp; alert("You are not allowed to continue");&nbsp; &nbsp; return false;&nbsp; }}<input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" /><form action="/student/create" method="get" id="nameform" onsubmit="return validateForm()">&nbsp; <div class="row">&nbsp; &nbsp; <div class="col-sm-4">&nbsp; &nbsp; &nbsp; <div class="form-group" >&nbsp; &nbsp; &nbsp; &nbsp; <label>Current Status</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" value="" name="status" class="form-control">&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></form>

HUWWW

如果我正确地回答了你的问题,你可能必须通过javascript在事件上设置/获取该值。我假设您要做的是:在检索值的那一刻自动执行操作(如果它符合您的条件),而不是在用户操作(例如按钮单击)上执行操作。将数据提取到 javascript 代码中。以下问题答案可能会有所帮助&nbsp;如何将变量和数据从PHP传递到JavaScript?。从那时起,将这些值输入到表单字段中。这个问题的答案包含有关如何执行此操作的信息。如果您获得所需的值,则触发要触发的任何操作。如果要在表单提交时(当用户单击按钮或其他内容时)执行操作,mplungjan的答案应该有效。作为旁注:如果您确切地阐明您希望实现的目标(例如:当页面加载时,它是否应该自动执行,或者您只需要验证一个值),您可能会得到更具体的答案 - 甚至可能是您问题的更好解决方案。如果您只需要验证,那么我的解决方案在这一点上是过度的。

胡说叔叔

有很多方法可以做到这一点,最好的方法是,不要通过表单发送表单请求,使用Javascript在单击按钮时进行验证,然后发送表单数据,就像这种最简单的方法一样。var request = new XMLHttpRequest();request.open("POST", "http://example.com/submitform.php");request.send(formData);

精慕HU

像这样的东西?$("#nameform").on("submit",function(e) {&nbsp; const val = $("[name=status]").val().trim();&nbsp; console.log(val)&nbsp; if (val==="" || "Active" === val) e.preventDefault();})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="submit" form="nameform" value="Admit Student" style="margin-right: 16px" name="admit" /><form action="/student/create" method="get" id="nameform">&nbsp; <div class="row">&nbsp; &nbsp; <div class="col-sm-4">&nbsp; &nbsp; &nbsp; <div class="form-group" style="display:none;">&nbsp; &nbsp; &nbsp; &nbsp; <label>Current Status</label>&nbsp; &nbsp; &nbsp; &nbsp; <input type="text" value="Active" name="status" class="form-control" />&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; </div>&nbsp;&nbsp;</form>
随时随地看视频慕课网APP
我要回答