user2093601
user2093601

Reputation: 402

send form data to function on submit

I have an html page which has around six different forms with different somewhat unrelated fields in each form. What I'm trying to do is create a single jquery or javascript function to handle all the Fetch() on form submit without knowing the form ID (which is most of what I found in tutorials online). Right now I'm just trying to get the form data to display in an alert, but the alert is always blank (no form data being passed?).

My code for what I think should capture any form submit and display the form data:

<script>
  $(document).ready(function() {
    $("form").on("submit", function(e) {
      console.log("CCCCCCC in script CCCCCCCCCc")
      e.preventDefault();
      var dataString = $(this).serialize();
      alert(dataString);
      return false;
    });
  });
</script>

I have a couple of these type of forms (took out bootstrap class info for ease of reading:
<form>
  <div>
    <div>
      <label for="thing1">Choose:</label>
      <select id="thing1" name="thing1">
        <option value="XXX">XXX</option>
        <option value="YYY">YYY</option>
      </select>
    </div>
    <div>
      <label for="inputtext">Command</label>
      <input type="text" id="inputtext" name="thing2">
    </div>
    <div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

How can I get any of the form data into the alert box? Ideally later I will use fetch() after I massage the input string.

Upvotes: 1

Views: 663

Answers (2)

AbsoluteBeginner
AbsoluteBeginner

Reputation: 2255

As @Quentin suggested, you need to give a name to select and input elements, in order to get their values.

For instance:

$('form').submit(function(e) {
  e.preventDefault();
  var el_1 = this.thing1;
  var el_2 = this.inputtext;
  alert(el_1.value + ', ' + el_2.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<form>
  <div>
    <div>
      <label for="thing1">Choose:</label>
      <select id="thing1" name="thing1">
        <option value="XXX">XXX</option>
        <option value="YYY">YYY</option>
      </select>
    </div>
    <div>
      <label for="inputtext">Command</label>
      <input type="text" id="inputtext" name="inputtext">
    </div>
    <div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

Upvotes: 1

Quentin
Quentin

Reputation: 943527

The form doesn't have any serializable data.

A form control's data comes from a combination of its name and value but none of your form controls have name attributes.

Upvotes: 3

Related Questions