I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.
The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?
FORM:
<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name"/>
<input type="button" value="get" onclick="get();"/>
</form>
<div id="age"></div>
</p>
</body>
</html>
SCRIPT:
function get() {
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
}
Cheers.
You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.
If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:
$('form[name=form]').submit(function(e) {
e.preventDefault();
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
});
$(document).ready(function(){
$('form').submit(function(){
return false;
});
});
This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.
A found some tuts and solved the issue.
I just put this in before my Jquery code to disable the enter button.
$(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});
Related
I have question regarding inserting and updating a MySQL database from a form which is loaded in a div via ajax. I have taken various examples from different websites to check if it was an error on my part but they all work when the page is loaded independently and insert or amended to the database. When the form is loaded into the div, the inputs are completed and submitted it then redirects to the home page as defined in the script file but no information is inserted into the database:
(ajax_url.length < 1) {
ajax_url = 'app/pages/home.php';
}
As I said the form works and inserts if I load the form page directly. For that reason I have also tried the following while giving the form an id of "dataforms" and the submit button an id of "sub":
$("#sub").click( function() {
$.post( $("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
Is there something basic I am completely missing?
This is an example I was trying to get to work:
<?php
include_once('/config.php');
$task_name = $_POST['task_name'];
if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
<span id="result"></span>
<form id="dataforms" action="" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
I have also attempted to define the php in a separate file and call it on action and I end up with what looks like the post values not being carried across as I get an error showing $task_name is not defined.
The js script file is referenced in the footer and have no issues with datatables displaying and selecting data from the database so I guess it has something to do with how the form is being submitted and reloading. Do I need to treat form submissions differently when ajax is involved? I have used various insert and update scripts to test and all behave the same way.
First Page — can be .html or .php, doesn't matter:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#sub").click( function() {
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
Second page — insert-task.php:
<?php
//include_once('/config.php');
$task_name = $_POST['task_name'];
//if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
// echo $task_name; die;
if(true)
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
The two pages do work in tandem. Though there are a couple of things to note, please:
The database operations aren't yet a part of the executable code.
However, if // echo $task_name; die; was uncommented, then the <span> in the first page would be populated with whatever value was keyed in the input field, which would establish that the form data is relayed properly to the backend.
EDIT:
To deal with the required fields, following change is required in the first page:
Get rid of the click function for $("#sub")
Prevent the default submit action when dataforms is submitted
So, in effect, the updated code would look like follows:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name" required><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#dataforms").submit( function(e) {
e.preventDefault();
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
}
);
clearInput();
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
This would still show up Please fill out this field message if no data was entered in the input field and, at the same time, prevent the unexpected pop-up as a consequence of clearing the field after a successful submit.
I know this has been asked some time, but the solutions before did not help, and I do not understand if I am missing something
I have simple php/hmtl page with an index.php where I include the different content php pages with a simple GET check:
if (isset($_GET['section'], $section[$_GET['section']])) {
include $section[$_GET['section']];
} else {
include $section['home'];
}
Now one of these sections contains a form which I want to do some magical ajax/jquery action with.
In my javascript file which is loaded at the bottom of the index.php I have following jquery ajax stuff
//ajax load domain search script
$(document).ready(function(){
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
searchVal = $('#domain').val();
topLevel = $('.custom_select').val();
domain = searchVal + '.' + topLevel;
$.ajax({
type: 'GET',
url: 'script_domain.php',
data: 'domain=' + domain,
dataType: 'html',
beforeSend: function() {
$('#result').html('<img style="margin-left: 80px;margin-top: 30px;" src="_assets/img/loader.gif" alt="loading..." />');
if (!searchVal[0]) {
$('#result').html('<p>Syötä domain nimi.</p>');
return false;
}
},
success: function(response) {
$('#result').html(response);
},
error: function(response) {
$('#result').html('<p>Haussa virheitä.</p>');
}
});
});
});
I thought it would be enough to use
$(document).ready(function(){
and the live method (i have jquery 1.7.1 so live should be working?)
$('#lookup_domain').live("click", function() {
but unfortunatedly this is not working, the form just sends it to itself and loads the page again.
Here is the form:
<?php
if(!defined('indexcalled')){die('Direct access not premitted');}
?>
<div id="domain_search">
<h5>hae verkkotunnusta</h5>
<form action="#" method="get" class="domain_form">
<input type="text" name="domain" class="domain_input" />
<div class="select_wrap">
<select class="custom_select">
<option value="fi">.FI</option>
<option value="com">.COM</option>
<option value="net">.NET</option>
<option value="me">.ME</option>
<option value="info">.INFO</option>
</select>
</div><!--/select wrap-->
<input type="submit" value="Syötä" class="domain_submit_btn" id="lookup_domain"/>
</form>
<div class="clear"></div>
</div><!--/domain search-->
What am I missing here? Is there any good documentation about how to use jquery with this kind of dynamical page setup?
EDIT
My original question was, how to handle these kind of elements properly with jquery, because they are included later on.
I found that I should be working with on() instead of live because its deprecated in 1.7 too. So I edited the code like this:
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
$(document.body).on("click", '#domain', function(event){
alert($(this).text());
});
But the alert does not work, it does nothing. What am I missing here?
You're calling e.preventDefault(), which should keep the form from submitting, however you are not passing the event object into your click handler. Update it to this and it should work:
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
...
});
Because you are using a submit button for your live click you need to disable the form submission.
There are two solutions:
1, Return false on the click event:
$('#lookup_domain').live("click", function() {
// all of your code
return false;
})
2, add an onsubmit attribute to your form:
<form action="#" method="get" class="domain_form" onsubmit="return false;">
</form>
Thanks for all guys who helped me in the chat, the correct method is to first have the document ready, then use .on() with click method with body to access the element created afterwards. Then just with normal .val() to get the values, like this:
$(document).ready(function(){
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
searchVal = $('#domain').val();
i have a php page "formpage.php", in there is an form like this:
<div id='hiddenform' style='display:hidden'>
<form name="testform" action="formpage.php" method="post">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
</div>
this form displayed with jquery and simple modal (example):
$(".show_hide").click(function(){
$('#hiddenform').modal({overlayClose:true});
});
all works fine, the box open with SimpleModal and the form is displayed, but i cant submit the form, when i press the submit button nothing happens. what should i do? the form and the submit works fine without SimpleModal.
i want submit the form (open with SimpleModal) to formpage.phhp (self) and then i use the posted variables further in the script.
thank you for your help!
Does this work? If it does something in your js is preventing the default behaviour of the form(might be simplemodal might be something else):
$(".show_hide").click(function(){
$('#hiddenform').modal({
overlayClose:true,
onShow: function() {
$('.simplemodal-data input[type=submit]').click(function() {
$.post('the_url_where_you_want_to_send_your_data_to', $(this).closest('form').serialize(), function(data) { alert('we have a response and form has been sent!'); })
}
}
});
});
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.
I am getting the form on click from a file called test.php which contains the following:
<form method="post" class="adminTM">
<input type="hidden" name="execID" value="<?=$_POST['exec']?>" />
<input type="hidden" name="fromTM" value="<?=$_POST['TM']?>" />
<input type="text" name="toTM" value="<?=$_POST['TM']?>" />
<input type="hidden" name="symbol" value="<?=$_POST['symbol']?>" />
<button class="submitTM">SUBMIT</button>
</form>
The javascript looks like so:
$(function(){
$('.adminTMClick').live('click', function(e){
$(this).data('TM', this.innerHTML);
$.post('test.php', $(this).data(), function(data){
$(data).dialog({
modal: true,
beforeClose: function(){
$(this).remove();
}
});
console.log($('.adminTM'));
console.log($('.submitTM'));
});
});
$('.submitTM').live('click', function(e){
//originally had .adminTM with submit which failed
e.preventdefault();
alert('i am here');
return false;
});
});
How do i make it so that the form DOES NOT do the default submit action when the submit button is clicked?
Here is a fiddle that demonstrates basically what I am doing (i had to change it a bit because of the way jsfiddle works): http://jsfiddle.net/maniator/tQVnV/show/
You should use the submit() event on the form instead of the click() on the submit, since pressing enter will still submit the form (bypassing the submit button).
This should properly prevent the form from doing the default submit:
$('.adminTM').live('submit', function(e) {
// execute custom code
console.log("submit event fired");
// prevent default submit
return false;
});
jsFiddle: http://jsfiddle.net/bjorn/tQVnV/11/