【问题标题】:How to make HTML form fields automatically change when an option selected on a select field当在选择字段上选择选项时如何使 HTML 表单字段自动更改
【发布时间】:2015-07-30 10:11:07
【问题描述】:

假设我的 CodeIgniter 项目中有一个这样的表单。

<?php echo form_open(); ?>
    <select>
        <?php foreach($status_list as $status): ?>
        <option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
        <?php endforeach; ?>
    </select>
    <!-- Show this only if status type is, let's say "E" -->
    <input type="text" name="E_happened">
    <!-- Show this only if status type is, let's say "S" -->
    <input type="text" name="S_happened">
<?php echo form_close(); ?>

我想要做的是,如果用户选择一个状态,根据它的类型,显示一个文本字段以获取输入。

我已经找到了一种获取状态类型的方法,如下所示:http://localhost/myapp/index.php/status/type/{status_id},用户可以在其中传递状态 ID,它会“回显”状态类型。

我想通过 JavaScript 方法将它接收回 HTML 页面并显示那些文本输入字段。我该怎么做?

谢谢。 :)

【问题讨论】:

  • 如果您在选项属性中分配状态类型会更好,因为您为什么要向服务器发出额外的请求?有必要吗?

标签: javascript php jquery html


【解决方案1】:

因为你有jQuery 标签,所以我建议你这样做:

$('select').change(function(){
    var inp = this.value.trim();
    $(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});

【讨论】:

    【解决方案2】:

    我已经按照您的要求发布了示例流程。希望这对您有所帮助。

    PHP:

    <?php echo form_open(); ?>
        <select>
            <?php foreach($status_list as $status): ?>
            <option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
            <?php endforeach; ?>
        </select>
        <!-- Show this only if status type is, let's say "E" -->
        <input type="text" id="E_happened" name="E_happened">
        <!-- Show this only if status type is, let's say "S" -->
        <input type="text" id="S_happened" name="S_happened">
    <?php echo form_close(); ?>  
    

    JAVASCRIPT

      $('select').change(function(){
         var statusId = $(this).val();
         var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
         if(statusType == 'E')
         {
           $('#E_happened').value("what do you want here");
         }
         if(statusType == 'S')
         {
            $('#S_happened').value("what do you want here");
          }
       });
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2018-11-07
      相关资源
      最近更新 更多