使用 jquery 的动态搜索表单

Dynamic search form using jquery

我正在尝试使用 jquery 创建搜索表单以完成以下任务:

  1. 用户可以上传文件或将文本输入文本区域或下拉菜单中的 select 选项,但这些选项将根据第一个下拉菜单的 selection 显示.
  2. 用户可以复制此表单的次数,但不能超过第一个下拉菜单的最大选项。
  3. 用户可以从第一个下拉菜单中删除 form < max options。

但问题是:

  1. 任务 1 仅在原始表格上工作,而不是在克隆表格上工作 one.I 认为由于标签 ID,它只完成原始表格的任务,那么我如何在多个场合执行此任务?

var max_fields      = 3; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var addButton      = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
    if ($("#alarm_action").val() == "listofcompany") {
        $('#filefield').show();
        $("#myTextarea").hide();
        $("#showForProg").hide();

    } else if ($("#alarm_action").val() == "runprogram") {
        $('#filefield').hide();
        $("#myTextarea").hide();
        $("#showForProg").show();
    } else {
        $('#filefield').hide();
        $("#myTextarea").show();
        $("#showForProg").hide();
    }
});

  $(addButton).click(function(e){ //on add input button click
      e.preventDefault();
      if(x < max_fields){ //max input box allowed
          x++; //text box increment
          $(wrapper).append('<div class="form-field">\
                            <select class="removeDuplication" name="searchtype" id="alarm_action" required>\
                            <option value="cityname">City Name</option>\
                            <option value="listofcompany">Company</option>\
                            <option value="runprogram">Run Program</option></select>\
                            <body  onload="setProg();">\
                              <select name="searchtermorg" id="showForProg" style="display: none;"></select>\
                            </body>\
                            <input id="filefield" type="file" name="foofile" style="display: none;"/>\
                            <textarea id="myTextarea" name="something" ></textarea>\
                            <a href="#" class="remove_field">Remove</a>\
                          </div>'); //add input box
      } else {
        alert("Sorry, you have reached maximum add options.");
    }
  });

          $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
              e.preventDefault();
              $(this).parent('div').remove();
              x--;
          });

          $(document).on('change','select.removeDuplication',function(e) {
              e.preventDefault();
              var cI = $(this);
              var others=$('select.removeDuplication').not(cI);
              $.each(others,function(){
                  if($(cI).val()==$(this).val() && $(cI).val()!="") {
                      $(cI).val('');
                      alert($(this).find('option:selected').text()+' already selected.');
                  }
              });
          });
          form.on('submit', function(e) {
              e.preventDefault()
              var queries = [];
              var slectedall=true;
              var fillupfield=true;
              form.find('.form-field').each(function(index, field) {
                  var query = {};
                  query.type = $(field).find('select').val();

                  console.log(query.type);
                  if (query.type !=""){
                      if (query.type == "listofcompany") {
                        query.value =$(field).find('#filefield').val();
                      } else if (query.type == "runprogram") {
                        query.value =$(field).find('#showForProg').val();
                      } else {
                        query.value =$(field).find('textarea').val().replace(/\n/g, '\n');
                      }
                      queries.push(query);
                  } else{
                      slectedall=false;
                  }
              });
              var url = window.location.href;
              url+="/search/advanced/";
              for (i = 0; i < queries.length; i += 1) {
                  var query = queries[i];
                  var ampOrQ = (i === 0) ? "?" : "&";
                  if (query.value.trim() ===""){
                      fillupfield=false;
                  } else {
                    url += ampOrQ + query.type + "=" + query.value;
                  }
              };
              if (slectedall===false){
                  alert('Please select option.');
              } else {
                  if (fillupfield===false){
                      alert('Input can not be left blank');
                  } else {
                    //alert(url);
                      window.location.href = url;
                  }
                  
              }
              
          });
          
      var progarray = ['Python','Java','R'];
      function setProg() {
        var newOptions=progarray;
        var newValues=progarray;
        selectField = document.getElementById("showForProg");
        selectField.options.length = 0;
        for (i=0; i<newOptions.length; i++) 
        {
        selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
        }
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
  <div class="input_fields_wrap">
    <div class="form-field">
      <select class="removeDuplication" name='searchtype' id="alarm_action"  required>
          <option value="cityname">City Name</option>
          <option value="listofcompany">Company</option>
          <option value="runprogram">Run Program</option></select>
          <body  onload="setProg();">
            <select name="searchtermorg" id="showForProg" style="display: none;"></select>
          </body>
          <input id="filefield" type="file" name="foofile" style="display: none;"/>
          <textarea id="myTextarea" name="something"></textarea>
      </div>
    </div>
      
      <input class="btn btn-secondary" type="button" value="Add" id="form-add">
      <input class="btn btn-primary" type="submit" value="Submit">
</form>

谁能帮我解决这些问题?谢谢

我们当前代码的问题:

  • 在有效的 HTML 中,id 元素应该是唯一的。但是在这里,每次克隆元素时都会重复元素 id。使用 class 而不是 id.
  • 使用$.on将事件绑定到动态添加的元素(例如,下拉更改事件)
  • 不可维护的意大利面条代码 - 我已经尝试清理了一下。但是清理的余地很大。

我已经通过修复 above-mentioned 点解决了您提到的问题。但正如我所说,在将其用于项目之前,还有很多 clean-up 要做。

var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];

wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));

$(document).on('change', '.alarm_action', function(e) {
  var $container = $(this).parents('.form-field');
  if ($(this).val() == "listofcompany") {
    $('.filefield', $container).show();
    $(".myTextarea", $container).hide();
    $(".showForProg", $container).hide();

  } else if ($(this).val() == "runprogram") {
    $('.filefield', $container).hide();
    $(".myTextarea", $container).hide();
    $(".showForProg", $container).show();
  } else {
    $('.filefield', $container).hide();
    $(".myTextarea", $container).show();
    $(".showForProg", $container).hide();
  }
});

$(addButton).click(function(e) { //on add input button click
  e.preventDefault();
  if (x < max_fields) { //max input box allowed
    x++; //text box increment
    wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
  } else {
    alert("Sorry, you have reached maximum add options.");
  }
});

$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
  e.preventDefault();
  $(this).parent('div').remove();
  x--;
});

$(document).on('change', 'select.removeDuplication', function(e) {
  e.preventDefault();
  var cI = $(this);
  var others = $('select.removeDuplication').not(cI);
  $.each(others, function() {
    if ($(cI).val() == $(this).val() && $(cI).val() != "") {
      $(cI).val('');
      alert($(this).find('option:selected').text() + ' already selected.');
    }
  });
});
form.on('submit', function(e) {
  e.preventDefault()
  var queries = [];
  var slectedall = true;
  var fillupfield = true;
  form.find('.form-field').each(function(index, field) {
    var query = {};
    query.type = $(field).find('select').val();

    console.log(query.type);
    if (query.type != "") {
      if (query.type == "listofcompany") {
        query.value = $(field).find(',filefield').val();
      } else if (query.type == "runprogram") {
        query.value = $(field).find(',showForProg').val();
      } else {
        query.value = $(field).find('textarea').val().replace(/\n/g, '\n');
      }
      queries.push(query);
    } else {
      slectedall = false;
    }
  });
  var url = window.location.href;
  url += "/search/advanced/";
  for (i = 0; i < queries.length; i += 1) {
    var query = queries[i];
    var ampOrQ = (i === 0) ? "?" : "&";
    if (query.value.trim() === "") {
      fillupfield = false;
    } else {
      url += ampOrQ + query.type + "=" + query.value;
    }
  };
  if (slectedall === false) {
    alert('Please select option.');
  } else {
    if (fillupfield === false) {
      alert('Input can not be left blank');
    } else {
      //alert(url);
      window.location.href = url;
    }

  }

});



function setProg($programDropdown) {
  $.each(progarray , function(key, value) {
    $programDropdown
     .append($("<option></option>")
     .attr("value",value)
     .text(value));
   });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
  
</div>
  <input class="btn btn-secondary" type="button" value="Add" id="form-add">
  <input class="btn btn-primary" type="submit" value="Submit">
</form>

<script type="text/template" id="content-template">
<div class="repeat-container">
    <div class="form-field">
      <select class="alarm_action removeDuplication" name='searchtype' required>
              <option value="cityname">City Name</option>
              <option value="listofcompany">Company</option>
              <option value="runprogram">Run Program</option></select>

      <body>
        <select name="searchtermorg" class="showForProg" style="display: none;"></select>
      </body>
      <input class="filefield" type="file" name="foofile" style="display: none;" />
      <textarea class="myTextarea" name="something"></textarea>
    </div>
  </div>
</script>