Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Javascript to force submit when return pressed

Status
Not open for further replies.

squibs

Technical User
Sep 24, 2007
10
I found some javascript to force a submit action. It is invoked if the user completes a textbox in a form and hits the return key with the textbox in focus, rather than explicitly clicking the submit button.

I have an alert which proves that the javascript is running and hitting the block which checks for the return key. This block calls myfield.form.submit(); but the submit doesn't seem to go through.

The code is live on
Could somebody take a look please? The code looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "<html xmlns=" xml:lang="en" lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
<!--
function submitenter(myfield,e)
{
var keycode;

if (window.event) {
keycode = window.event.keyCode;
}
else if (e) {
keycode = e.which;
}
else {
return true;
}

if (keycode == 13)
{
alert ("Return pressed - submit form.");
myfield.form.submit();
return false;
}
else
return true;
}
//-->
</script>
<?php
function checkDomain($domain,$server,$findText){
// Open a socket connection to the whois server
$con = fsockopen($server, 43);
if (!$con) return false;

// Send the requested doman name
fputs($con, $domain."\r\n");

// Read and store the server response
$response = ' :';
while(!feof($con)) {
$response .= fgets($con,128);
// echo $response;
}

// Close the connection
fclose($con);

// Check the response stream whether the domain is available
if (strpos($response, $findText)){
return true;
}
else {
return false;
}
}

function showDomainResult($domain,$server,$findText){
if (checkDomain($domain,$server,$findText)){
echo "<tr><td>$domain</td><td>AVAILABLE</td></tr>";
}
else echo "<tr><td>$domain</td><td>TAKEN</td></tr>";
}
?>
<form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain">
<table>
<tr><td>Domain name:&nbsp;<input class="text" name="domainname" type="text" size="36" onkeypress="return submitenter(this,event)" /></td></tr>
<tr>
<td>
<input type="checkbox" name="all" checked="checked" />All
<input type="checkbox" name="com"/>.com

<input type="checkbox" name="net"/>.net
<input type="checkbox" name="org"/>.org
<input type="checkbox" name="info"/>.info
</td></tr>
<tr><td align="center"><br/><input class="text" type="submit" name="submitBtn" value="Check domain"/></td></tr>
</table>
</form>
<?php
if (isset($_POST['submitBtn'])){
$domainbase = (isset($_POST['domainname'])) ? $_POST['domainname'] : '';
$d_all = (isset($_POST['all'])) ? 'all' : '';
$d_com = (isset($_POST['com'])) ? 'com' : '';

$d_net = (isset($_POST['net'])) ? 'net' : '';
$d_org = (isset($_POST['org'])) ? 'org' : '';
$d_info = (isset($_POST['info'])) ? 'info' : '';

// Check domains only if the base name is big enough
if (strlen($domainbase)>2){
?>
<div>Result</div>
<hr/>
<p class="textbox">

<table width="100%">
<?php
if (($d_com != '') || ($d_all != '') ) showDomainResult($domainbase.".com",'whois.crsnic.net','No match for');

if (($d_net != '') || ($d_all != '') ) showDomainResult($domainbase.".net",'whois.crsnic.net','No match for');
if (($d_org != '') || ($d_all != '') ) showDomainResult($domainbase.".org",'whois.publicinterestregistry.net','NOT FOUND');
if (($d_info != '') || ($d_all != '') ) showDomainResult($domainbase.".info",'whois.afilias.net','NOT FOUND');
?>
</table>

</p>
<?php
}
}
?>

</body></html>
 
Insert this into your text box. This should work fine in all borwsers. Use a function to submit the form if you can. Just good coding practices. onkeypress="if(window.event.keyCode == 13||e.which == 13){submit form code here};
 
Thanks for your reply., but I guess it is the form submit code I am having problems with.

The current code is already processing the return key correctly. It is the myfield.form.submit() action which is the problem. The code is executed but the form does not seem to be submitted.

 
well the way i do it is like this...
Code:
document.FORMNAME.submit();

So you need to give your form a name
Code:
      <form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain" [b]name="domainform"[/b]>

and then use
Code:
document.domainform.submit();

also a form action is normally by default to submit on enter being pressed.

You also possibly need to return true, not false as you curently have it.




"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
Thanks 1DMF.

Okay - the form is now declared as follows:
Code:
      <form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain" name="domainform">

And my text field is like this:
Code:
Domain name:&nbsp;<input class="text" name="domainname" type="text" size="36" onkeypress="if(window.event.keyCode == 13||e.which == 13){alert('enter');document.domainform.submit();}" />

The alert triggers on the enter key, but the text field just clears after that, as it did when there was no javascript at all. That is to say the form is not submitted.

Clicking the submit button works correctly.
 
i'm a little confused on what you're trying to acheive.

Code:
<form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain" name="domainform">
Domain name:&nbsp;<input class="text" name="domainname" type="text" size="36" />
<input type="submit" value="submit">
</form>
if you just press enter the form should submit, it's a default action of a form.

if you are trying to validate the content PRIOR to submitting you need to use.
Code:
<form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain" name="domainform" [b]onsubmit="return myFunction();"[/b] >

so when the form submits it calls your function does the validation and you then return either true or false from the function call.

or am I not seing what your trying to do?


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
1DMF - thanks again for the help. You are not missing anything. I'm not yet concerned about validation.

I'm hitting enter after completing the text field, in the expectation that this will trigger a form submit, but that doesn't happen. It didn't happen without the javascript, so I added javascript to try to force a submit, but that isn't working either. Hitting enter just clears the form, as if I had reloaded the page. I know the javascript is being invoked because the alert I put in there triggers, but the code "document.domainform.submit()" is not forcing a submit.

Clicking the submit button works and calls my php routine. Can anybody think of a reason for whats happening?

The form has some other fields - here's the whole form as it stands now with javascript:
Code:
      <form style="width: 345px" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="domain" name="domainform">
        <table>
          <tr><td>Domain name:&nbsp;<input class="text" name="domainname" type="text" size="36" onkeypress="if(window.event.keyCode == 13||e.which == 13){alert('enter');document.domainform.submit();}" /></td></tr>
          <tr>
            <td>
                <input type="checkbox" name="all" checked="checked" />All
                <input type="checkbox" name="com"/>.com
                            
                <input type="checkbox" name="net"/>.net
                <input type="checkbox" name="org"/>.org
                <input type="checkbox" name="info"/>.info                        
            </td></tr>
            <tr><td align="center"><br/><input class="text" type="submit" name="submitBtn" value="Check domain"/></td></tr>
        </table>  
      </form>

 
what browser you using?

I've just set up a test page and it works fine
type in the box, press enter, the alert happens and the form is submitted?

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
IE7 and Firefox.

At this point I am going to just strip it down and build it back up again. You've proven the core is good - I must be screwing up somewhere else. Thanks for the advice.
 
no probs.

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
hi,

do you have a standard submit button? if so, your form should automatically submit when pressing the enter key within a field on your form (except for textareas and select boxes).

see my example:

Code:
<form name="f" action="[URL unfurl="true"]http://www.google.com"[/URL] method="get">
    <input type="text" name="t" value="t" /><br />
    <input type="radio" name="r" value="r" />radio<br />
    <input type="checkbox" name="c" value="c" />checkbox<br />
    <select name="s">
        <option value="s">s</option>
    </select>
    <input type="submit" />
</form>



*cLFlaVA
----------------------------
[tt]"quote goes here"[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
Turns out the problem is with the php component. If you use return key to submit a form
Code:
<input class="text" type="submit" name="submitBtn" value="Check domain"/>


then the php test
Code:
if (isset($_POST['submitBtn'])){
is false, but the test is true if you click the submit button. I fixed it by using a different test condition in the php code. Thanks again for the help.
 
I could have if I knew I needed to!

It seems to come as a surprise to anybody I've talked to so far that the submit button value doesn't get set on return press, only on clicking the submit button.
 
yes it is a bit of an odd one, when the action of pressing enter is to submit, but it's not the same as clicking submit.

why are you checking if it is set to a value? what are you checking for? (more curiosity than anything ;-) )

"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!
 
I was just checking that a value was set for the button - my usual way of testing in submit has been pressed. I'm now checking something else in the POST variables.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top