Jump to content

Simulating a Button Click with the Enter Key


iwato

Recommended Posts

I did not suggest this code.

$("REFERENCE TO FORM").on("submit", function(e){
	// Stop the form from reloading the page
	e.preventDefault();

	// Do action "X" here:
	performActionX();
});

I implemented it.

It works great with the ENTER/RETURN key, but it silences the functionality of the <input type='submit'> form control.

I would like Item 3 below to read:  Click on either the Search button or ENTER/RETURN key.  For the moment I can have one or the other, but not both.

23 hours ago, iwato said:

Proceed to the Grammar Captive mainpage.

  1. Find the word Q&A under the heading Search Grammar Captive
  2. Enter the word Frage in the search box.
  3. Click on the Search button.

Watch what happens.  

 Roddy

Link to comment
Share on other sites

I would back out and start fresh, it sounds like you're copying and pasting a bunch of stuff around and then trying to debug after the fact.  You need to do progressive testing instead.

First, remove all Javascript handlers for any of those form elements, and make sure the form has the expected normal behavior, where either a button click or the enter button will submit the form.  Then, add a submit handler.  Don't have it do anything except an alert box (so that the browser pauses until you click OK), and verify that the submit handler is showing the alert box no matter how the form submits.  Add things piece by piece and test each time, that's progressive testing.  Test each small piece before moving on (hopefully you have a design in mind that you're starting with, so you have a goal).  

Link to comment
Share on other sites

So, are you of the opinion that this Ingolme's proposal will work?

$("REFERENCE TO FORM").on("submit", function(e){
	// Stop the form from reloading the page
	e.preventDefault();

	// Do action "X" here:
	performActionX();
});

Roddy

Link to comment
Share on other sites

I am of the opinion that the code will prevent the default submit behavior and then run another function.  Whether that fits your definition of "work" is another issue.  I'm not sure specifically what these additional actions are that you're referring to, but it's entirely possible you can put any of that in the other function.  I don't know if you always want to prevent the default submit, maybe only in certain situations.  The point is to do things one piece at a time and test after each piece to build what you want, instead of paste in a bunch of a code and then try to figure out why it doesn't work for you.

Link to comment
Share on other sites

Having established a consensus on Ingolme's proposed solution my dilemma is how to get the same function to work for both the now understood button and the ENTER/RETURN key.  It would appear to be a simple matter of reassigning the contents of Action X to the <input type='submit'> form control and the ENTER/RETURN key.   In other words, something of the following order:

$("REFERENCE TO FORM").on("submit", function(e){
	e.preventDefault();
});
function performActionX() {
	Do action X;	
}
$("REFERENCE TO FORM").on('click', performActionX);
$("REFERENCE TO ENTER/RETURN KEY").on('...', performActionX);

or alternatively,

$("REFERENCE TO FORM").on("submit", function(e){
	e.preventDefault();
	$(this).on('click', function() {
		Do Action X;
	});
	$("REFERENCE TO ENTER/RETURN KEY").on('...', function() {
		Do Action X;
	});
});

As I have never worked with a key before, I know neither how to assign a jQuery method to a key, nor how to identify a key-event.

I would not be concerned about the seemingly haphazard manner in which action X was put together.  Each piece of the code has been tested in several other places on two different Grammar Captive pages and in several contexts on each. It appears to be quite robust.

Roddy

Link to comment
Share on other sites

This has already been said, but here goes. Submission by  enter/return in text input or clicking input type="button" with event handler, that will trigger form submission will go through and will be picked up by form onsubmit event, therefore you don't require to determine if enter/return key was pressed. You would only require this if you had multiple fields that could by mistake trigger submission by pressing enter/return, where you can check if this has happened by checking keycode and prevent it from submitting if true.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0" />
        <title>Document Title</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script  src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

        <style type="text/css">

        </style>
    </head>
    <body>
        <div id="search_qa_div">
            <div id='qa_header'>
                <h1 style='padding-top: 2.9em;'>The Onsite<br />Grammar Captive<br />Question and Answer<br />Search Engine</h1>
                <form id='qa_searchform' style='margin-top:2em;' action="#ifYouSeeMeSubmissionHasTakenPlace">
                    <fieldset id='qa_field'>
                        <legend>Search and Find</legend>
                        <input id='qa_input' type="text" class='SearchInput' placeholder='Enter keywords and phrases here ...' name='search_qa_input' required>
                        <input id='qa_submit' type="button" class='SearchButton' value="Search">
                    </fieldset><!-- end fieldset#qa_field -->
                    <label id="qa_input_error" class="error" for="qa_input">Please enter what interests you. Else, there is nothing to search.</label>
                    <p class='Hint'><span class='InlineHeading'>search guide</span>: A phrase surrounded by <em>double</em>-quotation marks<br />returns only those question and answer pairs that contain the exact phrase.</p>
                </form>
            </div><!-- end div#qa_header -->
            <div id='qa_matches'>Your matches will display here ...</div><!-- end div#qa_matches -->
        </div><!-- end #search_qa_div -->
        <div id="functionprocess">

        </div>
        <script>
            $('#qa_searchform').on('submit', function(e) {

                e.preventDefault();
                var searchText = $('#qa_input').val();
                doSomething(searchText);

            });

            $('#qa_submit').on('click', function() {


                $('#qa_searchform').submit();


            });

            function doSomething(searchText) {
                //$('#functionprocess').empty();
                for (var i = 0; i < 5; i++)
                {
                    $('<p>Paragraph #' + (i + 1) + ' ' + searchText + ' </p>').appendTo('#functionprocess')

                }

            }


        </script>
    </body>
</html>

 

Link to comment
Share on other sites

Dsonesuk:  According to the proposed function the default behavior is first suppressed.  This means that in order to achieve the additional tasks with the default behavior, the default behavior must somehow be reinstated.  I do not understand your point.

Please ignore the above statement.  I was on my way out and too hasty to pass judgement.  I have since returned and have had more time to study.  I believe that I  understand.  You are allowing the <input type='submit'> form control behave as usual and focusing the change in default behavior on the  <form> element itself, as Ingolme suggested.

 This will have been the first time that I have employed the .submit( ) method.

i like, will give it a try, and return with the result.

Roddy

Edited by iwato
Link to comment
Share on other sites

Having established a consensus on Ingolme's proposed solution my dilemma is how to get the same function to work for both the now understood button and the ENTER/RETURN key.

Why are you still trying to run the function in 2 different events?  I thought the consensus that was agreed upon was that you would handle the submit event only and not worry about how the form got submitted.  It sounds like you want something to happen when the form gets submitted, so why are you worried about trying to individually handle every way the form can get submitted instead of only handling the actual submit event?

Link to comment
Share on other sites

As far i can make out, you want to prevent form submission to stop reloading of page, so you can carry out these other tasks to use ajax for instance.

IF you still want submission from a specific element, check if the event was from that element and then with if/else condition prevent preventDefault() being triggered or not! and do processing required within if/else condition.

Edited by dsonesuk
Link to comment
Share on other sites

As it did not work the first time, I simplified the procedure to the following:  

(function() {
   $('#qa_searchform').on('submit', function(event) {
        event.preventDefault();
        var search_qa_input = $("#qa_input").val();
        findAndDisplay_qa(search_qa_input);
    });
    $('#qa_submit').on('click', function() {
        $('#qa_searchform').submit();
    });
    findAndDisplay_qa(searchString) {
        var dataString = 'search_input=' + searchString;
        $.ajax({***});
    }
})();

No effect.  Whether I click the submit button or depress the ENTER/RETURN key, nothing happens.

Roddy

Edited by iwato
Link to comment
Share on other sites

The click event is bypassing your form submission event and reloading the page. I said it before, do not use any click events or any keyboard events. The only event listener you need is one single submit event listener.

This is all you need:

$('#qa_searchform').on('submit', function(event) {
  event.preventDefault();
  var dataString = 'search_input=' + $("#qa_input").val();
  $.ajax({***});
});

As long as you don't have any other code on the page that is interfering with it, this should work for both mouse and keyboard events.

If that fails to work, you may have issues with the AJAX block of code.

Link to comment
Share on other sites

Hi, Ingolme.  It is nice to see you back.

I tried the above code, but it fails.  When I change it to the following, the AJAX call works for keyboard submit, but the button-click behavior is squelched.

$('#qa_searchform').on('submit', function(event) {
  event.preventDefault();
  var search_qa_input = $("input#qa_input").val();
  var dataString = 'search_input=' + search_qa_input;
  $.ajax({...});
});

Roddy

Link to comment
Share on other sites

Forget the AJAX call. Let's start off trying to guarantee that the form behaves the same whether you use a keyboard or mouse input to submit it. Put an alert() statement in the event handler and verify that you're getting the same behavior for both actions.

$('#qa_searchform').on('submit', function(event) {
  event.preventDefault();
  var search_qa_input = $("input#qa_input").val();
  alert(search_qa_input);
});

 

Link to comment
Share on other sites

Ingolme:  The result is similar.  Rather than a successful AJAX call, a successful alert( ) appears.  Still, the form-button behavior is squelched.

The following produces two successful alert( )s.

(function() {
//	$('.error').hide();
	$('#qa_searchform').on('submit', function(event) {
	  event.preventDefault();
	  var search_qa_input = $("input#qa_input").val();
	  alert(search_qa_input);
	});
	$('.SearchButton').on('click', function() {
		event.preventDefault();
		var search_qa_input = $("input#qa_input").val();
		alert(search_qa_input);
	});
})();

Roddy

Edited by iwato
Link to comment
Share on other sites

I told you that you don't need a click event. The submit event will automatically take click events from all the buttons in the form. The biggest problem here is that you keep adding the click event back. The click event must be eliminated, destroyed, nullified.

Link to comment
Share on other sites

I hear you, but the browser apparently does not.

Is there some way to avoid having to declare the variable 

search_qa_input

twice.  Although no complaint is registered when simple alert() are performed, there is a reaction when the alert function is replaced with a function housing the AJAX call.

Never mind, the problem was resolved as follows:

(function() {
	$('#qa_searchform').on('submit', function(event) {
		event.preventDefault();
		findAndDisplay();
	});
	$('.SearchButton').on('click', function() {
		event.preventDefault();
		findAndDisplay();
	});
	function findAndDisplay() {
		var search_qa_input = $("input#qa_input").val();
		var dataString = 'search_input=' + search_qa_input;
		$.ajax({...});
	}
})();

The only difficulty left is to restore my error message functionality -- namely,

if (search_qa_input == "") {
    $("label#qa_input_error").show().append('<br />');
    $("input#qa_input").focus().focusout(function() {
        $("label#qa_input_error").hide();
    });					
    return false;
}

The following works for the form button, but not for the ENTER/RETURN key.

function findAndDisplay() {
    var search_qa_input = $("input#qa_input").val();
    if (search_qa_input == "") {
        $("label#qa_input_error").show().append('<br />');
        $("input#qa_input").focus().focusout(function() {
            $("label#qa_input_error").hide();
        });					
        return false;
    }
    var dataString = 'search_input=' + search_qa_input;
    $.ajax({...});
}

This said, because I have indicated the input type='text' form element as required, Safari does provide a rude alert that says, "Fill out this field'.

Now, unless you have a solution that is more in line with your own proposal I must move on, for I still have two major tasks  to complete before I start podcasting and time is running out.

Roddy

Edited by iwato
Link to comment
Share on other sites

Oops!  What works for Safari and Chrome, does not work for Firefox.  Firefox permits the desired AJAX call using the ENTER/RETURN key, but rejects the same using the form button.  Alas, what I though was a solution is not.

On the happy side, Chrome's alert uses the word please:

"Please fill out this field"

Roddy

Link to comment
Share on other sites

The click event is what's causing everything to stop working. It's the reason that your code works in one situation and not the other. If you're not going to listen to me I can't help you any further. Regardless of what the browser does, take my advice and remove the click event. If it is still not working after that then we can begin searching for the real cause of the problem.

Delete this block of code and do not add it back under any circumstances:

$('.SearchButton').on('click', function() {
  event.preventDefault();
  findAndDisplay();
});

Start off with this code and nothing else:

(function() {
	$('#qa_searchform').on('submit', function(event) {
		event.preventDefault();
		findAndDisplay();
	});

	function findAndDisplay() {
		var search_qa_input = $("input#qa_input").val();
		alert(search_qa_input);
	}
})();

If this does not work, then we need to simplify even further. Do not add any code, continue removing code until it is too simple to fail. Once we reach that point, we can start adding things back in one by one.

Link to comment
Share on other sites

As before, your proposal works for the ENTER/RETURN key (hereafter called the KEY), but not for the form button (hereafter called the BUTTON).  This, by the way, is true for all three browsers that are available to me (Safari, Firefox, and Chrome).  They all behave identically.  An alert appears for the KEY, but nothing occurs for the BUTTON.

Roddy

 

 

Edited by iwato
Link to comment
Share on other sites

If you use input type button, YOU DO need a JavaScript click event to initiate a submission which the forms onsubmit will act upon, whereas type submit NO such coding is required and forms onsubmit again will capture.

Within the onsubmit the preventDefault() is used in both cases preventing submission, enabling you to run some 'other tasks' instead.

Edited by dsonesuk
Link to comment
Share on other sites

9 hours ago, iwato said:

findAndDisplay_qa(searchString) {         var dataString = 'search_input=' + searchString;         $.ajax({***});     }

Would help if you declare it as a function

(function() {
                $('#qa_searchform').on('submit', function(event) {
                    event.preventDefault();
                    var search_qa_input = $("#qa_input").val();
                    findAndDisplay_qa(search_qa_input);
                });
                $('#qa_submit').on('click', function() {
                    $('#qa_searchform').submit();
                });
                function findAndDisplay_qa(searchString) {
                    var dataString = 'search_input=' + searchString;
                    //$.ajax({***});
                    alert('Eureka ' + dataString);
                }
            })();

Try this. A good editor would have picked this up.

The result is what is expected, onsubmit runs function as it should for both methods of submission.

This, by the way, is true for all three browsers that are available to you (Safari, Firefox, and Chrome) plus Microsoft Edge, Microsoft Explorer 11 and Opera that are available to me.

Edited by dsonesuk
Link to comment
Share on other sites

To illustrate difference further

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0" />
        <title>Document Title</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script  src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

        <style type="text/css">

        </style>
    </head>
    <body>
        <div id="search_qa_div">
            <div id='qa_header'>
                <h1 style='padding-top: 2.9em;'>The Onsite<br />Grammar Captive<br />Question and Answer<br />Search Engine</h1>
                <form id='qa_searchform' style='margin-top:2em;' action="#ifYouSeeMeSubmissionHasTakenPlace">
                    <fieldset id='qa_field'>
                        <legend>Search and Find</legend>
                        <input id='qa_input' type="text" class='SearchInput' placeholder='Enter keywords and phrases here ...' name='search_qa_input' required>
                        <input id='qa_submit' type="button" class='SearchButton' value="Search as button type with Click Event">
                        <input id='qa_truesubmit' type="submit" class='SearchButton' value="Search as True Submit type">
                        <input id='qa_submitNoClickEvent' type="button" class='SearchButton' value="Search Wont Work With No ClickEvent">

                    </fieldset><!-- end fieldset#qa_field -->
                    <label id="qa_input_error" class="error" for="qa_input">Please enter what interests you. Else, there is nothing to search.</label>
                    <p class='Hint'><span class='InlineHeading'>search guide</span>: A phrase surrounded by <em>double</em>-quotation marks<br />returns only those question and answer pairs that contain the exact phrase.</p>
                </form>
            </div><!-- end div#qa_header -->
            <div id='qa_matches'>Your matches will display here ...</div><!-- end div#qa_matches -->
        </div><!-- end #search_qa_div -->
        <div id="functionprocess">

        </div>
        <script>
            $(function() {
                $('#qa_searchform').on('submit', function(event) {
                    event.preventDefault();
                    var search_qa_input = $("#qa_input").val();
                    findAndDisplay_qa(search_qa_input);
                });
                $('#qa_submit').on('click', function() {
                    alert($(this).attr('type'));
                    $('#qa_searchform').submit();
                });
                function findAndDisplay_qa(searchString) {
                    var dataString = 'search_input=' + searchString;
                    //$.ajax({***});
                    alert('Eureka ' + dataString);
                }
            })();
        </script>
    </body>
</html>

 

Edited by dsonesuk
Link to comment
Share on other sites

I am now of the firm opinion that you're all guessing.

The following code

(function() {
	$('#qa_searchform').on('submit', function(event) {
		event.preventDefault();
		var searchValue_qa = $("#qa_input").val();
		findAndDisplay_qa(searchValue_qa);
	});
	$('#qa_input').on('click', function() {
		$('#qa_searchform').submit();
	});
	function findAndDisplay_qa(searchString) {
		var dataString = 'search_input=' + searchString;
		alert(dataString);
	}
})();

yields the following alert that is triggered simply by placing the curser inside the input field.

search_input=

Roddy

Edited by iwato
Link to comment
Share on other sites

I have shown everything there is and omitted the following:

if (search_qa_input == "") {
    $("label#qa_input_error").show().append('<br />');
    $("input#qa_input").focus().focusout(function() {
        $("label#qa_input_error").hide();
    });					
    return false;
}

I would invite you to Seattle to have a closer look, but I fear that you would not come, as I haven't enough money to pay for your flight, food, and lodging, and it would be presumptuous for me to ask you to pay your own way.

Roddy

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...