选择输入中需要值

时间:2018-04-05 08:10:59

标签: php html html5

我有代码

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php">
<select required>
  <option value=1>Volvo</option>
  <option value=2>Saab</option>
  <option value=3>Mercedes</option>
  <option value=4>Audi</option>
  <option value=5 selected>None</option>
</select>
<input type="submit">
</form>

</body>
</html>

none是使用值5选择的默认值,当用户选择无时,是否仍然存在必需的消息?如何解决这个问题,谢谢

2 个答案:

答案 0 :(得分:0)

这是一个显示警告的php选项。

<?php

if(isset($_POST['check']) && $_POST){

  if($_POST['car'] == 5){

    echo 'You must select a value.';

  }

}

?>

<!DOCTYPE html>
<html>
<body>

<form action="" method="post" enctype="multipart/form-data">
<select id="car" name="car" required>
  <option value=1>Volvo</option>
  <option value=2>Saab</option>
  <option value=3>Mercedes</option>
  <option value=4>Audi</option>
  <option value=5 selected>None</option>
</select>
<input type="submit" name="check" value="Submit">
</form>

</body>
</html>

这是许多可能的js解决方案之一:

<script>

    function checkSelect(){

        if(document.getElementById('car').value == 5){

          alert('You must select a car.');

        }

    }


</script>

<!DOCTYPE html>
<html>
<body>


<form action="" method="post" enctype="multipart/form-data" onsubmit="checkSelect()">
<select id="car" name="car" required>
  <option value=1>Volvo</option>
  <option value=2>Saab</option>
  <option value=3>Mercedes</option>
  <option value=4>Audi</option>
  <option value=5 selected>None</option>
</select>

<input type="submit" name="check" value="Submit" onSubmit>
</form>

</body>
</html>

我还会考虑使用像jQuery Validation插件这样的表格验证器。使事情变得更容易。 https://jqueryvalidation.org/

答案 1 :(得分:0)

你可以将空值留空无选项如下:

&#13;
&#13;
<!DOCTYPE html>
<html>
<body>

<form action="" method="post">
<select id="select" required>
<option value="">None</option> 
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
<input type="submit" name="check" value="Submit">
</form>

</body>
</html>
&#13;
&#13;
&#13;