SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Netherlands
    Posts
    672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    prevent input submit on enter ?

    Is there any good way to do this.. i want to run my own function instead of the form being submitted on one input field.
    Go visit my site :-D you know you want to ;-)
    www.mech7.net

  2. #2
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,255
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)

    submit function

    It is easy enough to have a function process form input, like validation scripts do. But remember that if a user does not have javascript enabled, the form will be useless unless it submit()s as well. It is best to only enhance the form's behaviour using javascript and keep all critical processing server-side. That said, try something like
    HTML Code:
    <input type="submit" onclick="my_function(); return false;" value="submit"/>
    If javascript is enabled you can have your function do it's thing and then submit() the form if everything's OK. If it isn't enabled, the form will submit to the "action" where the important stuff should be handled.

  3. #3
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Netherlands
    Posts
    672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Isn't there a way to only disable one input text box to submit on enter?
    Go visit my site :-D you know you want to ;-)
    www.mech7.net

  4. #4
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,255
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)

    disabled input

    Sorry, I'm a bit confused. Yes, you can disable form inputs with script. Please give a more detailed example of what you want to do.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Only form elements with a name attribute will be submitted.

    So the simple answer is, if you don't want an input element to be submitted, don't give it a name attribute.

  6. #6
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Netherlands
    Posts
    672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by pmw57 View Post
    Only form elements with a name attribute will be submitted.

    So the simple answer is, if you don't want an input element to be submitted, don't give it a name attribute.
    Offcourse i want it to be submitted only not on a enter.
    Go visit my site :-D you know you want to ;-)
    www.mech7.net

  7. #7
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think this would work a little better.

    <form onsubmit="return false">
    ...

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Well as we haven't been told what you're wanting to use this for, I'll have to guess.

    You could have a separate button that performs the special function on the special input field. This ensures that graceful degredation will occur should it be needed.

    Then, you can use a separate onchange event as a progressive enhancement that performs the same task as the button. It could even simulate a click on the button for that special input, for the greatest level of compatibility.

    Of course, this is all plucked from thin air and may or may not work for you, depending on the demands of your intended usage.
    Last edited by paul_wilkins; Dec 30, 2007 at 05:51.

  9. #9
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,255
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)

    more detail please

    Please provide more detail. Something like. "This is my form code"
    HTML Code:
    <form name="my_form" ...
    <input name="special_input" ...
    "and I want 'special_input' to be like 'this' unless the user does 'something' in which case I want it to do 'that'" - or - "If 'special_input' is 'whatever', I want 'my_form' to not submit, but ...."
    You don't need to post all of the code but having a little more information would be helpful.

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Mittineague View Post
    Please provide more detail. Something like. "This is my form code"
    HTML Code:
    <form name="my_form" ...
    <input name="special_input" ...
    "and I want 'special_input' to be like 'this' unless the user does 'something' in which case I want it to do 'that'" - or - "If 'special_input' is 'whatever', I want 'my_form' to not submit, but ...."
    Here is some base html to work from.

    Code HTML4Strict:
    <form name="my_form" action="form.php">
    	<label for="name">Name</label>
    	<input type="text" name="Name" value="Paul" /><br />
    	<label for="special_input">Special Input</label>	
    	<input type="text" name="special_input" value="this" />
    	<input type="submit" name="something" value="Something" /><br />
    	<input type="submit" name="submit" value="submit" />
    </form>

    Notice that there is no javascript being used here, for now.

    When the form is submitted, the php script can check for 'whatever' and create the form again with an appropriate warning, and can also check for theSomething button being hit and work with that too.

    Code PHP:
    $form['special_input'] = 'this';
    $form['something'] = '';
    $form['submit'] = '';
    if ($_GET) {
        $form['special_input'] = $_GET['special_input'];
        $form['something'] = $_GET['something'];
        $form['submit'] = $_GET['submit'];
    }
     
    if ($form['special_input'] == 'whatever') {
        $form['warning']['special_input'] = 'The value for Special Input is not allowed. Please correct and try again.';
    }
    if ($form['submit'] && !$form['warning']) {
        process_form($form);
    } else {
        if ($form['something']) {
            $form['special_input'] = 'that';
        }
        start_page();
        create_form($form);
        end_page();
    }

    We check for any warning situations and process the form if there are no warnings, and according to your requirements, when something is done it does that. If the form isn't processed it gets shown again. This is how it works without using javascript.

    I know, this is a javascript forum and I'm talking about not using javascript. It's a very zen-like concept, where you don't do it even though you know how it's done, which doesn't need to be delved in to right now.

    So the form processing works fine whether javascript is enabled or not.

    Now we can use javascript to override these default behaviours and duplicate the server-side behaviour on the client-side.

  11. #11
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,255
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)

    js form validation

    Yes, having javascript check the input values before an actual HTTP request is a good idea (faster for the honest user to know something is wrong).
    As I posted before, you can have the submit inputs call the javascript function. If the function does something like this it should work
    HTML Code:
    var sp_input = document.getElementById('special_input');
    var si_val = sp_input.value;
    if (si_val == 'whatever'){
    var err_div = document.getElementById('err_msg_display');
    err_div.innerHTML = "<span class="warning">Warning Message</span>";
    sp_input.focus();
    return FALSE;
    } else {
    /* not sure which would be better */
    var the_form = document.getElementById('my_form');
    the_form.submit();
    /* or ?? */
    return TRUE;
    }

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    I've run up a working example that goes as follows.

    The form runs a validation script before submitting. If it returns false the form won't be submitted. Likewise with the button that does Something - the script for when you click that can always return false to disable the default submit action (the submit being important when the client has disabled javscript).

    Code HTML4Strict:
    <form name="my_form" action="form.php" onsubmit="return validate()">
    	<p><label for="name">Name</label>
    	<input type="text" name="Name" value="<?php echo $form['name']?>" /></p>
    <?php
        if ($form['warning'] && $form['warning']['special_input']) {
            echo '<p class="warning">' . $form['warning']['special_input'] . '</p>';
        }
    ?>
    	<p id="special"><label for="special_input">Special Input</label>	
    	<input type="text" id="special_input" name="special_input" value="<?php echo $form['special_input']?>" />
    	<input type="submit" name="something" value="Something" onclick="return doSomething()" /></p>
    	<p><input type="submit" name="submit" value="submit" /></p>
    </form>

    The scripts can be kept very simple.

    Code JavaScript:
    function validate() {
        if (!validateSpecialInput()) {
            return false; // cancel submit event
        }
    }
    function doSomething() {
        document.getElementById('special_input').value = 'that';
        validateSpecialInput();
        return false; // cancel submit event
    }

    The actual validation isn't that difficult either.

    Code JavaScript:
    function validateSpecialInput() {
        if (document.getElementById('special_input').value === 'whatever') {
            addWarning('special');
            return false;
        }
        removeWarning('special');
        return true;
    }

    The only slightly tricky parts were the customised warnings, but even they aren't that bad.

    Code JavaScript:
    function addWarning(id) {
        if (!document.getElementById(id + '_warning')) {
            var el = document.getElementById(id);
            var warning = document.createElement('p');
            warning.setAttribute('id', id + '_warning');
            warning.setAttribute('class', 'warning');
            warning.appendChild(document.createTextNode('The following value is not allowed. Please correct and try again.'));
            el.parentNode.insertBefore(warning, el);
        }
    }
    function removeWarning(id) {
        if (document.getElementById(id + '_warning')) {
            var warning = document.getElementById(id + '_warning');
            warning.parentNode.removeChild(warning);
        }
    }

    And there you have it. I've contained all the code inside the one php file so that it can all be posted up here. In practice the javascript would be contained in a separate file instead.

    Here is the full code for this example.

    Code PHP:
    <?php
    $form['name'] = 'Paul';
    $form['special_input'] = 'this';
    $form['something'] = '';
    $form['submit'] = '';
    if ($_GET) {
        $form['name'] = $_GET['name'];
        $form['special_input'] = $_GET['special_input'];
        $form['something'] = $_GET['something'];
        $form['submit'] = $_GET['submit'];
    }
     
    if ($form['special_input'] == 'whatever') {
        $form['warning']['special_input'] = 'The value for Special Input is not allowed. Please correct and try again.';
    }
    if ($form['submit'] && !$form['warning']) {
        process_form($form);
    } else {
        if ($form['something']) {
            $form['special_input'] = 'that';
        }
        start_page();
        create_form($form);
        end_page();
    }
     
    function start_page() {
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>My Form</title>
    <style type="text/css">
    .warning {
        color: red;
    }
    </style>
    </head>
     
    <body>
    <p><var>special_input</var> to be like <kbd>this</kbd> unless the user does <var>something</var> in which case I want it to do <kbd>that</kbd></p>
    <p>or - If <var>special_input</var> is <kbd>whatever</kbd>, I want <kbd>my_form</kbd> to not submit</p>
    <?php
    }
     
    function create_form($form = null) {
    ?>
    <form name="my_form" action="form.php" onsubmit="return validate()">
        <p><label for="name">Name</label>
        <input type="text" name="Name" value="<?php echo $form['name']?>" /></p>
    <?php
        if ($form['warning'] && $form['warning']['special_input']) {
            echo '<p class="warning">' . $form['warning']['special_input'] . '</p>';
        }
    ?>
        <p id="special"><label for="special_input">Special Input</label>    
        <input type="text" id="special_input" name="special_input" value="<?php echo $form['special_input']?>" />
        <input type="submit" name="something" value="Something" onclick="return doSomething()" /></p>
        <p><input type="submit" name="submit" value="submit" /></p>
    </form>
    <?php
    }
     
    function end_page() {
    ?>
    <script type="text/javascript">
    function addWarning(id) {
        if (!document.getElementById(id + '_warning')) {
            var el = document.getElementById(id);
            var warning = document.createElement('p');
            warning.setAttribute('id', id + '_warning');
            warning.setAttribute('class', 'warning');
            warning.appendChild(document.createTextNode('The following value is not allowed. Please correct and try again.'));
            el.parentNode.insertBefore(warning, el);
        }
    }
    function removeWarning(id) {
        if (document.getElementById(id + '_warning')) {
            var warning = document.getElementById(id + '_warning');
            warning.parentNode.removeChild(warning);
        }
    }
    function validateSpecialInput() {
        if (document.getElementById('special_input').value === 'whatever') {
            addWarning('special');
            return false;
        }
        removeWarning('special');
        return true;
    }
    function validate() {
        if (!validateSpecialInput()) {
            return false; // cancel submit event
        }
    }
    function doSomething() {
        document.getElementById('special_input').value = 'that';
        validateSpecialInput();
        return false; // cancel submit event
    }
    </script>
    </body>
    </html>
    <?php
    }
     
    function process_form($form) {
        echo '<pre>';
        var_dump($form);
        echo '</pre>';
    }
    ?>

  13. #13
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Netherlands
    Posts
    672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok here is the entire problem.. i use an auto suggest on a tag field, when you select an existing tag it writes a hidden input with the id, but when the value does not exists yet i want when you press an enter, not to submit the entire form to the controller yet. But instead that it writes a hidden input with the new tag so i can save that first in the table, and then set the relations..

    The thing is the tag form is inside the form, that is why it should not submit the entire thing on a enter button, but write the new tag value as a hidden form.

    So it is not intended for validation, only to stop it submitting the form.

    This is the form:

    HTML Code:
    <form id="ArticleAddForm" method="post" action="/mech7_v2/admin/articles/add"><input type="hidden" name="_method" value="POST" /><div class="articlePanel">
        <h1>Add Post</h1>    
        <label for="published" style="margin-bottom:10px;">
            <input id="published" name="data[Article][published]" type="checkbox" value="yes" /> <a href="javascript:;" rel="Checking this box will publish the article on the frontend.">Publish</a>
        </label>
        <label for="frontpage" style="margin-bottom:10px;">
            <input id="frontpage" name="data[Article][frontpage]" type="checkbox" value="yes" /> <a href="javascript:;" rel="Checking this box will publish the article on the frontpage.">Frontpage</a>
        </label>
        <div class="input required"><label for="ArticleTitle">Title</label><input name="data[Article][title]" type="text" maxlength="255" value="" id="ArticleTitle" /></div>    <div class="input required">
        <label for="article">Article <a href="javascript:toggleEditor('articleTextarea');">(wysiwyg)</a></label>    
        <textarea name="data[Article][article]" rows="10" cols="20" id="articleTextarea" ></textarea>        </div>
        <label for="category">Category</label>
        <select name="data[Category][id][]" multiple="multiple" id="CategoryId">
    <option value="1">News</option>
    <option value="5">-Software</option>
    <option value="6">--3d applications</option>
    <option value="7">---test</option>
    <option value="10">----test</option>
    <option value="8">---test</option>
    <option value="9">----</option>
    <option value="2">Tutorials</option>
    <option value="3">-PHP</option>
    <option value="4">-Photoshop</option>
    <option value="11"></option>
    <option value="12"></option>
    <option value="13">testing</option>
    <option value="14"></option>
    </select>    <input type="submit" value="Save Article" />    
    </div>
    <div class="tagPanel">    
        <div id="vertical_container" >
            <h2 class="accordion_toggle">Tags</h2>
            <div class="accordion_content">
                <p>Fill in related tags to the content</p>
                    <input name="data[Tag][tag]" type="text" size="40" id="TagTag" autocomplete="off" />
                    <div id="TagTag_autoComplete" class="auto_complete"></div>
                    <script type="text/javascript">new Ajax.Autocompleter('TagTag', 
                        'TagTag_autoComplete',
                        '/mech7_v2//articles/autocompleteTags',
                        {afterUpdateElement:addExistingTags, indicator:'spinner'});
                    </script> 
                    <span id="spinner" style="display: none;">
                        <img src="/mech7_v2//img/spinner.gif" alt="Working..." />
                    </span>
                <div id="groupTags" style="border: 1px dashed #000; padding: 5px;"></div>
            </div>        
            <h2 class="accordion_toggle">Publish dates</h2>
            <div class="accordion_content">
                <label>Publish on date</label>
                <input type="text" id="date-from" name="date-from" style="width:180px" />
                <label>End publishing on date</label>
                <input type="text" id="date-till" name="date-till" style="width:180px" />
                <script type="text/javascript">
                /*<[CDATA[*/
                 var dateFrom = new DatePicker({
                  relative            :     'date-from',
                  language            :     'nl',
                  topOffset            :     '-80',
                  keepFieldEmpty     : true,
                  disableFutureDate : false
                  });
                  var dateTill = new DatePicker({
                  relative            :     'date-till',
                  language            :     'nl',
                  topOffset            :     '-80',
                  keepFieldEmpty     : true,
                  disableFutureDate : false
                  });
                /*]]>*/
                </script>
            </div>
            <h2 class="accordion_toggle">Meta description</h2>
            <div class="accordion_content">
                <p>Enter description of 100 characters</p>
                <textarea name="data[Article][description]" rows="5" cols="20" id="ArticleDescription" ></textarea>    
            </div>
            <h2 class="accordion_toggle">Meta keywords</h2>
            <div class="accordion_content">
                <p>Enter keywords seperated by a comma ,</p>
                <textarea name="data[Article][keywords]" rows="5" cols="20" id="ArticleKeywords" ></textarea>                
            </div>        
        </div>        
    </div>
    </form>
    Attachment is how it looks..
    Attached Images Attached Images
    • File Type: jpg 1.jpg (65.7 KB, 3 views)
    Go visit my site :-D you know you want to ;-)
    www.mech7.net

  14. #14
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,255
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)

    tags

    Instead of doing the tag stuff onsubmit(), maybe do it onchange()?
    HTML Code:
          <script type="text/javascript">
          function write_to_hidden() {
            var entered_tag = document.getElementById('TagTag').value;
            if (entered_tag == "OK to go"){
              /* do stuff */
              return;
            }
          }
          </script>
          <input name="data[Tag][tag]" type="text" size="40" id="TagTag"
     autocomplete="off" onchange="write_to_hidden();"/>
          <div id="TagTag_autoComplete" class="auto_complete"></div>

  15. #15
    SitePoint Guru
    Join Date
    Jul 2004
    Location
    Netherlands
    Posts
    672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    With onchange it will write a tag with every new key right? The behvious should be that if you write a tag that is not on the list (auto suggest works allready) and then you press a enter key that it then writes the new tag in.

    Quote Originally Posted by Mittineague View Post
    Instead of doing the tag stuff onsubmit(), maybe do it onchange()?
    HTML Code:
          <script type="text/javascript">
          function write_to_hidden() {
            var entered_tag = document.getElementById('TagTag').value;
            if (entered_tag == "OK to go"){
              /* do stuff */
              return;
            }
          }
          </script>
          <input name="data[Tag][tag]" type="text" size="40" id="TagTag"
     autocomplete="off" onchange="write_to_hidden();"/>
          <div id="TagTag_autoComplete" class="auto_complete"></div>
    Go visit my site :-D you know you want to ;-)
    www.mech7.net


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •