2

I am trying to create add/remove form fields dynamically with jQuery where the user can submit multiple queries based on the dropdown selections. At the end, it should generate URL with a combination of selection.So far I have managed to create add/remove form fields with the option of multiple queries.

For example, if the user submits input for a car then it will generate URL like:

exmaple.com/?car=xxx

and which is working.

If a user submits input for car and bike then it should generate:

exmaple.com/?car=xxx&bike=yyy

but it is generating like:

exmaple.com/?car=xxx&car=yyy

So how can I solve this issue? Thank you in advance.

$(function() {
  $.fn.addmore = function(options) {
    var moreElement = this,
      singlePreSelectedValue = '',
      selectedValue = [],
      defaultOption = {
        addText: 'add more',
        removeText: 'Remote',
        selectBoxDuplicate: true,
        avoidDuplicationSelection: function(e) {
          var o = e;
          if ($.inArray($(o).val(), selectedValue) != -1) {
            $(o).val(singlePreSelectedValue);
            alert('Value already selected.');
          } else {
            var hasSelectValue = true;
            $.each($('.removeDuplication'), function(i, v) {
              if ($(this).val() == 'select') {
                hasSelectValue = false;
                return false;
              }

            });

          }
        },
        prevSelectedValue: function(e) {
          var o = e;
          selectedValue = [];
          $.each($('.removeDuplication'), function(i, v) {
            if ($(this).val() != 'select') {
              selectedValue.push($(this).val());
            }
          });
          singlePreSelectedValue = $(o).val();
        }
      }
    defaultOption = $.extend(true, defaultOption, options);

    /*        $(this).find('select').prepend('<option value="select" selected>Select</option>');*/
    $(moreElement).after('<a href="javascript:void(0)" data-id="more">' + defaultOption.addText + '</a>');
    $('[data-id="more"]').click(function() {
      var dataMore = this,
        removeDuplication = [];
      $(dataMore).before($(moreElement).clone().find('input').not('input[type="submit"]').val('').end().end().find('select.removeDuplication').focus(function() {
        if (!defaultOption.selectBoxDuplicate) {
          defaultOption.prevSelectedValue(this);
        }
      }).change(function() {
        if (!defaultOption.selectBoxDuplicate) {
          defaultOption.avoidDuplicationSelection(this);
        }
      }).end().append(function() {
        return $('<a href="javascript:void(0)" class="circular deleteCons icon icon-functional button" data-id="remove"><i class="fa fa-trash"></i> ' + +'</a>').click(function() {
          $(this).parent().remove();
        });
      }));
      if (!defaultOption.selectBoxDuplicate) {
        $.each($('.removeDuplication'), function(i, v) {
          if ($(this).val() != 'select') {
            removeDuplication.push($(this).val());
          }
        });
        $.each(removeDuplication, function(i, v) {
          $('.removeDuplication').last().find('option[value="' + removeDuplication[i] + '"]').remove();
        });
      }
    });
    $('.removeDuplication').focus(function(e) {
      defaultOption.prevSelectedValue(this);
    }).change(function() {
      defaultOption.avoidDuplicationSelection(this);
    });
    return this;
  }

  $('dl').addmore({
    addText: 'Add',
    removeText: 'Remove',
    selectBoxDuplicate: false
  });
});




$(document).ready(function() {
  $("select").change(function() {
    var str = $(this).val();
    $("#searchtermid").attr("name", str);

  });
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form class="navbar-form" action="" method="get" action="demo_form.asp">
  <dl>
    <select class="removeDuplication">
			<option value="car">Car</option>
			<option value="bike">Bike</option>
			<option value="plane">Plane</option>
		</select>
    <textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></textarea>
  </dl>
  <input class="btn btn-primary" type="submit" value="Submit">
</form>

After getting input from Standard Quality, I have modified my scripts and html. https://jsfiddle.net/paul85/wjhqszmg/

But still is not letting the user submit input form. Most important, when user will submit from it should redirect to a page for correctly generated URL. If user submit input for car and bike then redirecting page address or URL will be:

exmaple.com/?car=xxx&bike=yyy

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="/results.html" method="get">
  <div class="input_fields_wrap">
      <div class="form-field">
        <select class="removeDuplication">
          <option value="car" >Car</option>
          <option value="bike">Bike</option>
          <option value="plane">Plane</option>
        </select>
        <textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></textarea>
      </div>
  </div>
  <button class="add_field_button">Add More Fields</button>
  <input class ="btn btn-primary" type="submit" value="Submit" >
</form>

JAVASCRIPT

$(document).ready(function() {
    var max_fields      = 3; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    var form = $('#main-form');
    var x = 1; //initlal text box count
    $(add_button).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">\
                                    <option value=""></option>\
                                    <option value="car">Car</option>\
                                    <option value="bike">Bike</option>\
                                    <option value="plane">Plane</option>\
                                </select>\
                                <textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none"></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).val()+' already selected.');
            }
        });
    });
  /*$(form).submit(function(e){*/
    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();
            query.value = $(field).find('textarea').val();
            if (query.type !=""){
                queries.push(query);
            } else{
                slectedall=false;
            }
        });

        for (i = 0; i < queries.length; i += 1) {
            var query = queries[i];
            if (query.value.trim() ===""){
                fillupfield=false;
            }       
        };
        if (slectedall===false){
            alert('Please select option.');
        } else {
            if (fillupfield===false){
                alert('Please insert your searchterm.');
            } else {
          $("form").submit();
            }

        }

    });
});
0

1 Answer 1

1

It looks like you're extending jQuery, which isn't necessary for this, and is contributing to making the code much less legible. To be honest, I haven't even dug through it to find the problem -- instead, I wrote something from scratch. StackOverflow snippets don't allow forms, so here's a working JSBin: http://jsbin.com/gokodaluna/edit?html,js,output

(Note that I've changed your HTML markup a little bit)

HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form id="main-form" class="navbar-form" action="" method="get" action="demo_form.asp">
  <div class="fields">
    <div class="form-field">
      <select class="removeDuplication">
        <option value="car">Car</option>
        <option value="bike">Bike</option>
        <option value="plane">Plane</option>
      </select>
      <textarea class="form-control custom-control" name="car" id="searchtermid" placeholder="Search term" data-toggle="tooltip" data-placement="bottom" rows="3" style="resize:none" required></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>

<h2 id="final-url"></h2>

</body>
</html>

Javascript:

/* Save your initial variables */
var form = $('#main-form');
var formFields = form.find('.fields')
var addButton = $('#form-add');
var emptyInput = $('.form-field').clone(); // clone this at initialization so we always have an empty field
var finalUrl = $("#final-url");

addButton.on('click', function() {
  emptyInput.clone().appendTo(formFields);
  /* clone this again so our initial field is always empty and available */
})

form.on('submit', function(e) {
  e.preventDefault()
  var queries = [];
  form.find('.form-field').each(function(index, field) {
    var query = {};
    query.type = $(field).find('select').val();
    query.value = $(field).find('textarea').val();
    queries.push(query);
  });
  var url = window.location.href;
  for (i = 0; i < queries.length; i += 1) {
    var query = queries[i];
    var ampOrQ = (i === 0) ? "?" : "&";
    url += ampOrQ + query.type + "=" + query.value;
  }

  /* print the URL into the dom if you want to see it working */
  finalUrl.text(url);

  /* or forward users to the new URL you've generated */
  window.location.href = url;

})

Edit: in the revised code in your question, you're calling $("form").submit() in that if-else statement. When you trigger this, the larger function is still catching the submit event, so it's immediately running e.preventDefault() again. If you need to simply forward the user to the new URL, just set it with window.location.href =. See the last few lines of my (edited) code above.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your code and feedback. But still it didn't solve my problem. I have updated my problem again with your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.