【问题标题】:PHP Echo into textbox based on dropdown valuePHP Echo 基于下拉值进入文本框
【发布时间】:2016-04-17 15:19:18
【问题描述】:

我正在开发一个遵循基本 MVC 模式的小型 Web 应用程序。目前我已经将数据从数据库中提取到一个数组中,并将该值回显到一个文本框中(目前)

<input type="text" name="txtGasConRes" id="gasConRes" value="<?php echo $typical; ?>" disabled/>

$typical 值正在从我的模型类中检索到我的控制器类中,然后回显到气体的文本框中。我有一个非常相似的 Electricity 文本框。

我的下拉菜单如下:

 <select name="heatingType" id="heatingType" required>
          <option value="" disabled selected>Select Your Option</option>
          <option value = "Gas">Gas</option>
          <option value = "Electricity">Electricity</option>
          <option value = "Other">Other</option>          
        </select>

我想知道是否有办法确定在哪里回显$typical 值。例如,如果用户选择 Gas 作为他们的加热类型,那么一旦提交表单,该值就会出现在 Gas 文本框中。如果用户从下拉列表中选择 Electricity,则该值将回显到 Electricity 文本框中。

任何信息将不胜感激。 谢谢!

【问题讨论】:

    标签: php model-view-controller pdo


    【解决方案1】:

    如果您愿意,这绝对是 JavaScript 或 jQuery 的工作。您需要设置一个处理程序来检测选择输入上的更改事件。一旦用户选择了一个值,您就可以根据用户选择的内容使用文本更新文本字段。

    未经测试,但类似这样的东西应该可以工作。

    var select = document.getElementById('heatingType');
    
    function updateTextField(selectedValue) {
        switch(selectedValue){
           case 'Gas':
           return 'some text that you want in the text field';
           break;
           // etc.
        }
    }
    
    select.addEventListener('change', function(){
        var selectedValue = this.value,
        textField = document.getElementById('gasConRes');
    
        textField.value = updateTextField(selectedValue);
    });
    

    【讨论】:

    • 感谢您的回复。我对 JavaScript 和 jQuery 都很陌生。你能指出我正确的方向吗?谢谢
    • 刚刚更新了答案以包含代码。未经测试,但应该可以使用或几乎可以使用。
    • 感谢您的回复。我有点理解该代码,但据我所知,这不会仅在 gasConRes 文本框中显示值吗?
    • 如果您不知道如何修改我为您编写的内容以放入另一个文本框中,那么您应该聘请开发人员为您完成。 Stack Overflow 不是“我们免费为您编写脚本”的服务。
    【解决方案2】:

    创建javascript函数并将函数放入选择框onchange事件中。(以下代码有效)

     <script>
    
      function heatingType(obj){
        alert(obj.options[obj.selectedIndex].value); //if you want to show in alart
        //or put in a variable 
        $x=obj.options[obj.selectedIndex].value;
    
      }
    
    </script>
    
     <select name="heatingType" id="heatingType"  onChange="heatingType(this)" required>
              <option value="" disabled selected>Select Your Option</option>
              <option value = "Gas">Gas</option>
              <option value = "Electricity">Electricity</option>
              <option value = "Other">Other</option>          
            </select>
    

    【讨论】:

    • 感谢您的回复,但这并不能满足我的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多