Search code examples
javascriptjqueryuser-input

Saving user input in jQuery?


$(document).ready(function () {
    var userSites = newArray();
    var max_fields = 100; //maximum input boxes allowed 
    var wrapper = $(".input_fields_wrap"); //fields wrapper
    var add_button = $(".add_field_button"); //Add button ID

    var x = 5; //initial text box count
    $(add_button).click(function (e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) {
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name ="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
    $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});

I have this code, because I want to have a lot of user inputs. However, once the user inputs this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet, is that possible as well?


Solution

  • However, now that the user has input this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet?

    When the form is submitted, the event handler, collectData gathers the text in each <input> and uses the push method to populate an array. This array is then stored in a hidden <input> and that data is then extracted by the form which then posts to the server.

    I don't know much about Java applets but I got you this far. I suggest you ask about Java in a new question. Your tags are of a JavaScript/jQuery nature.

    My demo actually functions with a test server so once submitted, the server will respond with the data that was posted to it.

    This works: http://plnkr.co/edit/seD0L3oI7dTnXQrrFZPl?p=preview

    Added Code

      form.addEventListener('submit', collectData, false);
    
      function collectData(e) {
        var userSites = [];
        var cache = document.getElementById('cache');
        var z = 0;
        while (z < max_fields) {
          z++;
          var data = inputs[z].val();
          userSites.push(data);
        }
    
        e.stopPropagation();
        cache.value = userSites;
      }
    
    });