简体   繁体   English

当用户选择False Hit单选按钮时,如果文本字段为空,如何确保无法提交表单?

[英]How to make sure form cannot be submitted if text field is empty when user selects False Hit radio button?

I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits. 我正在做一些事情,以防止用户提交HTML表单而不会留下他们对False Hits的评论。

Conditions: 条件:

  • Only if False Hit radio button is selected 仅当选择False Hit单选按钮时
  • The remarks text field cannot be empty (Compulsory) 备注文本字段不能为空(必填)

Currently, I have used JavaScript to check if the text field (Remarks) is empty. 当前,我已经使用JavaScript来检查文本字段(备注)是否为空。

function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
    alert("Please enter remarks for false hits selected.");
    return false;
};

I am also able to check which radio button is selected with JavaScript. 我还可以检查使用JavaScript选择了哪个单选按钮。

<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />

if(document.getElementById('falsehit').checked) {
  //False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
  //True Hit radio button is checked
}

However, I am quite stuck at linking both conditions together. 但是,我非常想将两个条件联系在一起。 Is there a simpler method to this? 有没有更简单的方法呢? Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thank you in advance. 先感谢您。

This is how my Form looks like. 这就是我的表格的样子。

    <body bgcolor="#FFFFFF">
    <br />

 <div align="center" class="h1">
 <h1>Entity Search</h1><br />   
 </div>

 </html>
 <br />

 <?php  
    include("db_connect.php"); //connect to database
    @$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture 
the user's LanID as the UserID
    if($loginid == "")
    {
        $userID = $_SESSION['loginid'];
    }
    else
    {
        $_SESSION['loginid'] = $loginid;
        $userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];

//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');

$userID = $_SESSION['loginid'];
$loginid = "";

$entityfromform = $_GET["entity"];
?>

<br />

<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);

//to retrieve the department name from the user database and insert 
department name of the user into the records
    $namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE 
   LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);

while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
    $nameontop = iconv("gb2312","UTF-8",$row['Name']);
    $admincheck = iconv("gb2312","UTF-8",$row["Role"]);
    $deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}

$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />"; 
//variable to insert into the table as result

//search for keyword from form in the Entity Table List where Name = 
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE 
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);

//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{           
    $name[$i] = $row["Name"];
    $brn[$i] = $row["Business_Registration_Number"];
    $address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}   
      if(@$name != NULL) //Positive Result
    {
        echo "<input type='button' name=uncheck' value='Uncheck All' 
class='uncheck' onClick='window.location.reload()'>"; //uncheck all 
function where it clears all changes
        echo "<h2><div align='center'>Results found for: 
$entityfromform</div></h2><br />";
         //table to display the data
             echo "<div align='center'>
            <table> 
            <tr>
            <th>Name</th>
            <th>Business Registration Number</th>
            <th>Registered Address</th>
            <th>Applicable Limb of Related Party Group</th>
            <th>True Hit</th>
            <th>False Hit</th>
            <th>Unable To Ascertain</th>
            <th>Remarks, for false hit</th>
        </tr>
    </div>";
    echo "<strong><div class='wording'>Positive Hit: </div></strong>";
    echo "<br /><br />";
    $x=0;
    ?>
    <!--The form data is sent for processing to action_handler.php by HTTP POST method-->
    <form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
    <?php
    //data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
    for($x=0;$x<$i;$x++)
    {
        echo "<tr>
        <td>" . $name[$x] . "</td>
        <td>". $brn[$x] . "</td>
        <td>". $address[$x] . "</td>
        <td>". $group[$x] . "</td>

        <td>
        <label class='container'>
        <input type='radio'   id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
        <span class='checkmark'></span>
        </label>
        </td>

        <td>
        <label class='container'>
        <input type='radio'  id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
        <span class='checkmark'></span>
        </label>
        </td>

        <td>
        <label class='container'>
        <input type='radio'  id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
        <span class='checkmark'></span>
        </label>
        </td>

        <td>
        <label><input type='text' name='".$text[$x]."'> 
        </label>
        </td>

        </tr>" ;
    }
    echo "</table>"; //table closed
    echo "<br /><br /><br />";
    echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
    ?>
    </form>
    <?php
    //sessions to be used in others
    $_SESSION['num'] = $x;
    $_SESSION['entityfromform'] = $entityfromform;
}
else 
{
    echo "<div align='center'><h2>Results found for: $entityfromform</h2> 
   <br />";
        echo "<div class='wording' align='center'>$negative</div><br><br> 
   <br>";

        }
    ?>

</table>
</body>

这就是它的样子。我已经模糊了私人和机密数据

检查元素

your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; 如果文本框具有值,那么您的empty()函数将不返回任何值,因此对于该条件,该值是未定义的; you can create a function for your requirement like: 您可以根据自己的需求创建一个函数,例如:

function doSubmit() 
{
   if(document.getElementById('falsehit').checked)
   {
      if(document.getElementById("roll-input").value == '')
      {
         alert("Please enter remarks for false hits selected.");
         return false;
      }
   }
return true;
}

and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false . 并调用此方法进行验证,因此,如果checked falsehitremarks具有值,则它将返回truefalse

Hope this helps; 希望这可以帮助; let me know if I'm missing to understand your problem here.. 如果想念您的问题,请告诉我。

Happy coding... 祝您编程愉快...

You can use a set of if statements like below. 您可以使用一组if语句,如下所示。 This basically checks if the falsehit radio button is checked. 这基本上检查是否选中了falsehit单选按钮。 If it is, then it checks if the text is empty. 如果是,则检查文本是否为空。 If the text is empty, it alerts what you wanted it to. 如果文本为空,则会提示您想要的内容。 If the text isn't empty, it submit's the form. 如果文本不为空,则提交表单。

Also, if falsehit is not checked, it automatically submit's the form. 另外,如果未选中falsehit ,它将自动提交表单。

As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. 按照注释中的要求:现在,我得到每个单选按钮,并循环浏览它们以检查是否已选中它们。 If they aren't, you get an alert message saying Please select all accordingly . 如果不是,您会收到一条警告消息,提示您Please select all accordingly Otherwise, it just works the same as before. 否则,它的工作原理与以前相同。

 function empty() { var text; var groups = document.querySelectorAll("[id^=group]"); var selected = {}; var radioButtons; var submitForm = true; groups.forEach(e1 => { radioButtons = e1.querySelectorAll("input[type=radio]"); radioButtons.forEach(e2 => { if (e2.checked) { selected[e1.id] = true; } }); if (selected[e1.id] == undefined) { selected[e1.id] = false; } }); groups.forEach(e => { text = e.children[0].value; for (var i = 0; i < e.children.length; i++) { if (e.children[i].id == "falsehit") { if (e.children[i].checked) { if (text.length == 0) { alert("Please enter remarks for false hits selected."); submitForm = false; } } else if (selected[e.id]) { //Don't need to do anything. Just need to prevent the next else from accessing these values } else { alert("Please select all accordingly."); submitForm = false; } } } }); if (submitForm) { document.getElementById("form").submit(); } } 
 <form id="form"> <fieldset id="group1"> <input type="text" id="roll-input" /> <input type="radio" name="group1" id="truehit" value="true" /> <input type="radio" name="group1" id="falsehit" value="false" /> </fieldset> <fieldset id="group2"> <input type="text" id="roll-input" /> <input type="radio" name="group2" id="truehit" value="true" /> <input type="radio" name="group2" id="falsehit" value="false" /> </fieldset> <input type="button" value="Submit" onclick="empty()" /> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当用户选择单选按钮时如何显示不同的内容? - How to display different content when a user selects a radio button? 如何确保只有一个文本字段不为空? - How to make sure only one text field is not empty? 当表单中的特定输入字段不为空时如何更改单选按钮选择 - How to change a radio button selection when a specfic input field in the form is not empty 提交单选按钮选项时无法为用户创建警报消息 - Javascript/HTML - Cannot Create Alert Message for User When Radio Button Option is Submitted - Javascript/HTML 我如何使用 localstorage 来确保用户不能多次点击? - How can I use localstorage to make sure a user cannot hit like more than once? 如何检查以确保已选中单选按钮 - How to check to make sure a radio button is selected 用户选择广播时,将属性插入输入字段 - Insert an attribute to input field when user selects a radio 在单选按钮自定义版本中,表单在提交时返回 id。 如何获取表单中的值而不是 id? - In Radio button custom version, the form returns the id when it is submitted. How to get the Value in the form instead of id? 选中分配给它的单选按钮时,如何使输入/文本字段为必填字段? - How do I make an input/text field mandatory when the radio button assigned to it is checked? Javascript:当选中/选中分配给它的单选按钮时,如何使输入/文本字段为必需字段? - Javascript: How do I make an input/text field mandatory(required) when the radio button assigned to it is checked/selected?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM