首页 > 解决方案 > 如何在回调时使用 AJAX 请求选择单选按钮值和文本输入?

问题描述

表单数据正确填写在所有输入文本字段中。但是对于单选按钮,除了元素的值发生变化外,什么都没有发生,但没有视觉效果。我知道它是因为基于类名,它会改变值。但是我如何区分现场输入和无线电输入?谢谢!

$(function() {
   $(".task-listing").click(function() {
  $.ajax({
      type: 'POST',
      url: 'http://localhost:8090/HELPERSITE/src/php/listing-info-get.php',
      dataType: 'json',
      data: 'pid=' + $(this).attr("id"),
      success: function(response) {
        console.log(response);

        Object.keys(response[0]).map(function(k) {
            var el = $('.' + k);
            if (el.prop('type') == 'radio') {
              el.filter(function(i, button) {
                return button.value == response[0][k];
              }).prop('checked', true);
            } else {
              $('.' + k).val(response[0][k]);
            }
        })
      }
  });
});
});

标签: javascriptjqueryhtmlmysqlajax

解决方案


如果类型为 ,则需要设置checked相应按钮的属性radio

$(function() {
  $(".task-listing").click(function() {
      $.ajax({
          type: 'POST',
          url: 'http://localhost:8090/HELPERSITE/src/php/listing-info-get.php',
          dataType: 'json',
          data: 'pid=' + $(this).attr("id"),
          success: function(response) {
            console.log(response);

            Object.keys(response[0]).map(function(k) {
                var el = $('.' + k);
                if (el.prop('type') == 'radio') {
                  el.filter(function(i, button) {
                    return button.value == response[0][k];
                  }).prop('checked', true);
                } else {
                  $('.' + k).val(response[0][k]);
                }
                if (response.negotiate == 'approve') {});
            }
          })
      });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="task-title-reg" name="task-title-reg" value="">
<textarea class="task-description-reg" name="task-description-reg" rows="4" cols="50" value=""></textarea>

<label for="local-reg">Local</label>
<input type="radio" name="task-location-reg" value="Local">
<label for="remote-reg">Remote</label>
<input type="radio" class="task-location-reg" name="task-location-reg" value="Remote">

<label for="approve-reg">Approve</label>
<input type="radio" class="task-negotiations-reg" name="negotiate" value="Approve">
<label for="deny-reg">Deny</label>
<input type="radio" class="task-negotiations-reg" name="negotiate" value="Deny">


推荐阅读