基于If Else语句实现数量输入联动货车类型文本框自动填充的技术咨询
实现数量输入与货车类型文本框的联动填充
嘿,我来帮你搞定这个联动功能!这里给你两种常用方案:一种是前端实时联动(用户输入时立刻更新结果),另一种是后端PHP处理(表单提交后显示对应内容),你可以根据实际需求选~
方案一:前端JavaScript实时联动(推荐)
这种方案能让用户输入数量时,货车类型框立刻显示对应内容,体验更流畅。我们需要给输入框加个监听事件,用if-else判断输入值:
<tr> <th><center>Quantity:</center></th> <td><input type="text" name="quantity" id="quantityInput" /></td> </tr> <tr> <th><center>Type of Lorry:</center></th> <!-- 加readonly防止用户手动修改 --> <td><input type="text" name="barcode" id="lorryTypeInput" readonly /></td> </tr> <script> // 获取两个输入框元素 const quantityInput = document.getElementById('quantityInput'); const lorryTypeInput = document.getElementById('lorryTypeInput'); // 监听数量输入框的输入事件 quantityInput.addEventListener('input', function() { // 把输入值转成数字,处理非数字情况 const quantity = parseInt(this.value); if (isNaN(quantity)) { lorryTypeInput.value = "请输入有效的数字数量"; return; } // 核心if-else判断逻辑 if (quantity === 50) { lorryTypeInput.value = "Do load into 3 ton lorry"; } else if (quantity > 40) { // 保留你原代码里的>40判断,可根据需求调整 lorryTypeInput.value = "Do load into 3 ton lorry"; } else { // 这里替换成你需要的其他数值对应的文本 lorryTypeInput.value = "Do load into smaller lorry"; } }); </script>
这段代码的关键点:
- 给输入框加了
id,方便JS精准获取元素 - 给货车类型输入框加了
readonly,避免用户手动修改结果 - 处理了非数字输入的情况,防止逻辑出错
- 实时监听输入变化,用户每输入一个字符就触发判断
方案二:后端PHP处理(表单提交后生效)
如果你的场景是需要用户提交表单后再显示结果,可以用PHP的if-else来处理:
<!-- 包裹在表单里,提交后后端处理 --> <form method="post"> <tr> <th><center>Quantity:</center></th> <!-- 回显用户之前输入的数量 --> <td><input type="text" name="quantity" value="<?php echo isset($_POST['quantity']) ? $_POST['quantity'] : ''; ?>" /></td> </tr> <tr> <th><center>Type of Lorry:</center></th> <td> <input type="text" name="barcode" readonly value="<?php // 表单提交后才执行判断 if (isset($_POST['quantity'])) { $quantity = intval($_POST['quantity']); // 核心判断逻辑 if ($quantity === 50 || $quantity > 40) { echo "Do load into 3 ton lorry"; } else { echo "Do load into smaller lorry"; // 替换成其他情况的文本 } } ?>" /> </td> </tr> <tr> <td colspan="2"><center><button type="submit">Submit</button></center></td> </tr> </form>
这段代码的关键点:
- 用
form标签包裹,通过POST方法提交数据 - 回显用户输入的数量,提升体验
- 提交后用PHP的
intval()转换输入值为数字,避免字符串干扰判断 - 用
isset()判断是否有提交数据,防止报错
额外提示
你可以根据实际需求调整if-else的条件,比如增加更多区间判断:
// 举个例子,多区间判断 if (quantity >= 50) { lorryTypeInput.value = "Do load into 3 ton lorry"; } else if (quantity >= 20 && quantity < 50) { lorryTypeInput.value = "Do load into 2 ton lorry"; } else { lorryTypeInput.value = "Do load into 1 ton lorry"; }
内容的提问来源于stack exchange,提问作者user9555914
相关产品推荐
相关产品推荐

