Home > Net >  Problem passing arguments to function using .submit in JQuery
Problem passing arguments to function using .submit in JQuery

Time:04-06

I cannot for the life of me understand why this doesn't work.

function test(event) {
  alert(event.data.fieldone);
};

$('form').submit({fieldone: $('#field').val()}, test);

I just end up with a blank alert. If I hardcode a string and pass that instead it works fine and if I declare a variable within the function and fetch the data that way it also works. What gives?

CodePudding user response:

It will not process the input field , because the form submit line will be executed only ONCE at the beginning, when the input field is blank.

If you wish to make it able to alert with the text inside the input field, you need to add event listener. For example, I add a button that will trigger the alert that prints the text inside the input field in the snippet below.

function test(event) {
  event.preventDefault();
  console.log(event.data);
  alert(event.data.fieldone);
};

$('#submit').click(function() {
  var data = $('#field').val();
  $('form').submit({'fieldone': data}, test);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" name="field" id="field">
  <button id="submit" type="submit">submit</button>
</form>

CodePudding user response:

In this version the data argument contains a reference to the #field input element and the .value property is then read at submit time and not at the time the submit event was attached to the form:

function test(event) {
  event.preventDefault();
  console.log(event.data.value);
};

$('form').submit($("#field")[0], test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" name="field" id="field">
  <button>submit</button>
</form>

  • Related