javascriptjqueryhtmlsearch-form

Dynamic search form using jquery


I am trying to create a search form using jquery for following tasks to do:

  1. A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
  2. The user can clone this form number of times but not more than max options of the 1st drop-down menu.
  3. The user can remove form < max options from the 1st drop-down menu.

But problems are:

  1. Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?

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>

Can anybody help me to fix these problems? thank you


Solution

  • Issues with our current code:

    I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.

    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>