0

I have a form like below:

<form onsubmit="doSomething(this.form);">
    <input type="text" name="groupName" />
    <input type="text" name="groupColour" />
</form>

Now this doesn't have a submit button, I know. Instead, when the user hits the enter key I want it to trigger a function. In this example doSomething.

Now in the function I will performing an AJAX request to insert a record to the database, however I'm not sure how to access the value that was entered in the text fields in my AJAX function doSomething.

How do I pass to my function the values of the form when submitted?

Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
Matthew Smart
  • 1,301
  • 4
  • 21
  • 37
  • depends if you are using jquery or not, but query the textboxes you want to pull the data from, then either use pure javascript has method .value or jquery has .val() for getting the input value – Georgette Pincin Sep 05 '15 at 13:32

4 Answers4

1

HTML & JQuery fiddle

Because you're using jquery and you want to use ajax request, you can use keypress function instead of form and submit :

HTML :

<input type="text" id="groupName" />
<input type="text" id="groupColour" />

JS :

$(document).keypress(function(e) {
    if(e.which == 13) { //When you pressed enter!
        var name = $('#groupName').val();
        var color = $('#groupColour').val();

        $.post('insert.php',{name: name, color: color});
    }
});

PHP (insert.php) :

$name = $_POST['name'];  //Get name
$color = $_POST['color'];  //Get color

//Now you can use $name & $color in insert Query here 

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Try this it works.. Do this tricky :-)

<form onsubmit="doSomething();">

    <input type="text" name="groupName" />

    <input type="text" name="groupColour" />

   <input type="submit" 
   style="position: absolute; left: -9999px; width: 1px; height: 1px;"
   tabindex="-1" />

</form>
Community
  • 1
  • 1
Aravinthan K
  • 1,763
  • 2
  • 19
  • 22
1

Don't use onsubmit attribute. Divide your HTML and javascript and handle form submission using jQuery.

$("form").on('keypress', function(event){
    // if the key is "enter":
    if(event.which == 13) {
        // trigger AJAX:
        $.ajax({
            url     : 'post-page.php',
            type    : 'post',
            // serialize the form (all the form fields will be posted to PHP):
            data    : $(this).serialize(),
            success : function(response){
                // handle server response...
            }
        });
    }
});
Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
1

Heres a easy way..

document.onkeypress =function (e) {
    if (e.keyCode == 13) {
       alert(document.forms['myform'].elements['myinput'].value);
    }
};
  
<body>
  <form name="myform">
    <input name="myinput" type="text" value="awesome">
    </form>
  </body>
kurt
  • 1,146
  • 1
  • 8
  • 18