Jump to content

Simulating a Button Click with the Enter Key


iwato

Recommended Posts

The following script was found on StackOverflow.  It is suppose to simulate a button click with the up-tick of an Enter key.

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});

Now, I am not using it for a textbox, but for a search box.  In order to get it to work I have tried the following:

  1. Used the <form> element as the selector for the keyup() function.
  2. Used the <input> element of the  search box as the selector for the keyup() function
  3. Entered the code in various places within my script including the html and the called javascript documents that make the search engine work.

To no avail.

Now, it is true that I have not been entirely methodological in my selection of HTML elements and code placement.  Still, ss many times as I have tried, however, you would think that Lady Luck would be on my side.

Any hints?

Please advise.

Roddy

Link to comment
Share on other sites

Try debugging to determine whether the issue is with the event not firing or whether the click() method isn't working by first verifying that you can get the key event to work on its own. You should be able to capture key events anywhere on the page by putting the event listener on the document object.

Why do you want to click a button with a key event? If the button is triggering an event handler, you can call that event handler directly from the key event instead of using the button as a middle-man. If the button is submitting a form, you can call the form's submit() method from the event handler instead.

Link to comment
Share on other sites

Unfortunately, I do not know how to target a chained event in jQuery.  Is it even possible.  Or, must I break the chain and repeat the selector.

Notice where the .click() method occurs in the following code.

	$("#search_letter").mouseover(function() {
			$(this).css({"cursor": "pointer", "font-weight":"800"});
		})
		.click(function() {
			if (window.selfSearchResults !== null) {
				$('#main').html(selfSearchResults);
				$.getScript('_utilities/javascript/search_second_go.js');
				$.getScript('_utilities/javascript/search_letter.js');
			} else {
				var searchLetterContent = $("#search_letter_div").html();
				$("#main").html(searchLetterContent);
				$("#main .error").hide();
				$.getScript('_utilities/javascript/search_letter.js');
			}
		})
		.mouseup(function() {
			$(this).css({"color": "#fadb9d","font-weight": "normal"});
		$('body, html').animate({scrollTop: $('#main').offset().top},800);
	});

Roddy

Link to comment
Share on other sites

function handleClick() {
  if (window.selfSearchResults !== null) {
    $('#main').html(selfSearchResults);
    $.getScript('_utilities/javascript/search_second_go.js');
    $.getScript('_utilities/javascript/search_letter.js');
  } else {
    var searchLetterContent = $("#search_letter_div").html();
    $("#main").html(searchLetterContent);
    $("#main .error").hide();
    $.getScript('_utilities/javascript/search_letter.js');
  }
}

function handleMouseUp() {
  $(this).css({"color": "#fadb9d","font-weight": "normal"});
  $('body, html').animate({scrollTop: $('#main').offset().top},800);
}

function handleMouseOver() {
  $(this).css({"cursor": "pointer", "font-weight":"800"});
}

$("#search_letter").mouseover(handleMouseOver).click(handleClick).mouseup(handleMouseUp);

Now you can call handleClick when someone presses the enter key.  You can choose more meaningful names if you want to, you don't have to chain everything with anonymous functions.

Link to comment
Share on other sites

As handleClick, handleMouseUp, and handleMouseOver are all called functions should they not be inserted as such -- namely,

$("#search_letter").mouseover(handleMouseOver()).click(handleClick()).mouseup(handleMouseUp());

Roddy

Link to comment
Share on other sites

No, you do not want to call the functions right away, you just want to give a reference to them so that they can be called when the event happens.

Link to comment
Share on other sites

As every that I have tried still fails, I would like to a hold on this problem.  I will return to it later.  

Link to comment
Share on other sites

OK.  Having resolved the dysfunctional link I may now return to the key problem.  Please find below my most recent attempt at including the .keyup() method.  Unfortunately, it too has failed.

Roddy

$("div.discover").mouseover(function() {
    $(this).find("span.discover_text").css({"cursor": "pointer","line-height":"1.6em","font-size":"1.4em"});
});
$("div.discover").click(function() {
    $(this).next("div.hidden_info").slideToggle(800, function() {
        $('.podcast_link').find('a').on('click', function(event){
            //event.preventDefault();
            var attribute = $(this).attr('href');
            var href_arr = attribute.split('?');
            var query_str = href_arr[1];
            var pairs = query_str.split('&');
            var data = [];
            $.each(pairs, function(i, v){
                var pair = v.split('=');
                var key = pair[0];
                var value = pair[1];
                var data_arr = [key, value];
                data.push(data_arr);
            });
            if(event.keyCode === 13) {
                $('.podcast_link').find('a').click();
            }
        });
    });
    $(this).mouseup(function() {
        $(this).css({"color": "#ccc", "font-weight": "normal"});
    });
    $('body, html').animate({scrollTop: $(this).offset().top},800);
})
.mouseout(function() {
    $("span.discover_text").css({"cursor":"auto","line-height":"1.6em","font-size":"1em"});
});

 

Link to comment
Share on other sites

I've rewritten the code from your most recent post to clearly distinguish the steps your program is taking. What I find is that the click event you're using is assigning a value to a variable named "data" but is never actually using that variable. Your program would not behave any differently if you deleted all those 12 lines of code. I don't know which text field you want to register the key event one, so I've left "#id_of_element" as a placeholder.

Please try to describe in short simple steps what exactly is supposed to happen when the link is clicked.

 


/* Core logic */
$discover = $("div.discover"); // Store a reference to the element for faster access

/*
 Assign all event handlers outside of functions, otherwise things get messy and
 you will end up with duplicated event handlers on the same element
 */

$discover.click(beginSlide);
$discover.mouseup(returnToNormal);
$("#id_of_element").keyup(somethingAboutData);
$('.podcast_link').find('a').click(somethingAboutData);

// The following events could easily be replaced by pure CSS:
$discover.mouseover(highlight);
$discover.mouseout(unhighlight);

/* Function declarations */
function highlight() {
  $(this).find("span.discover_text").css({"cursor": "pointer","line-height":"1.6em","font-size":"1.4em"});
}

function unhighlight() {
  $(this).find("span.discover_text").css({"cursor":"auto","line-height":"1.6em","font-size":"1em"});
};

function beginSlide() {
  $(this).next("div.hidden_info").slideToggle(800);
  $('body, html').animate({scrollTop: $(this).offset().top}, 800);
}

function returnToNormal() {
  $(this).css({"color": "#ccc", "font-weight": "normal"});
}
  
function somethingAboutData(event) {
  // For the keyboard event, only do something if the key code is 13
  if(event.type == "keyup") {
    if(event.keyCode != 13) {
      return;
    }
  }

  var $link;
  if(e.type == "keyup") {
    // This is the links that you want to click
    $link = $('.podcast_link').find('a');
  } else {
    $link = $(this);
  }

  /*
   The following logic does not do anything, it assigns a value to the data
   variable, but that variable is not being used anywhere.
   */
  var attribute = $link.attr('href');
  var href_arr = attribute.split('?');
  var query_str = href_arr[1];
  var pairs = query_str.split('&');
  var data = [];
  $.each(pairs, function(i, v){
      var pair = v.split('=');
      var key = pair[0];
      var value = pair[1];
      var data_arr = [key, value];
      data.push(data_arr);
  });

  /*
   I assume that by clicking on the link, you mean redirecting the page to the
   value in its href attribute
   */
  
  if(event.type == "keyup") {
    location.href = $link.attr('href');
  }
}

 

Link to comment
Share on other sites

The twelve lines of code that you are dismissing are a carry-over from another implementation that uses an AJAX call that is unnecessary for the current implementation.  You are correct; they could be left out, as they are a waste of CPU time.

Roddy

Link to comment
Share on other sites

Finally, I have time again and would like to return to your suggestion.  Unfortunately, our communication was not entirely successful, and I would like to turn your attention to the following:

(function() {
	$(".SearchButton").click(function() {
		var search_podcast_input = $("#podcast_input").val();
		if (search_podcast_input == "") {
			$("#podcast_input_error").show().append('<br />');
			$("#podcast_input").focus().focusout(function() {
				$("#podcast_input_error").hide();
			});					
			return false;
		}
		var dataString = 'search_input=' + search_podcast_input;
		$.ajax();
	});
})();

Under current conditions and among other user actions either of two events could occur:

  1. When the user clicks on the <input type='submit' class='SearchButton'> submit button the undefined AJAX call in the above code is sent to a PHP processing page.  
  2. When the user clicks on the ENTER/RETURN key, he refreshes the page, eliminates what he just entered into the form, and must start all over again.

What i do not understand is how to prevent the ENTER/RETURN key from refreshing the page on the one hand and cause the form to be submitted on the other.  Now, it is easy to understand how the computer knows that the form button or ENTER/RETURN key has been activated, and it is easy to bind a particular action to a form button.  Binding an action to the ENTER/RETURN key is, however, completely different, in so far as the key has many uses and can be performed at any time.   I simply do not understand, how to insure that activating the ENTER/RETURN key will produce the desired effect at the time  that it is desired and no other.

Can you help with my understanding in this regard?

For example, is it the location of the cursor inside a form that tells the ENTER/RETURN key what action to trigger?

Roddy

Edited by iwato
Link to comment
Share on other sites

You should be listening for form events instead of key events or click events. What's important here is that somebody is attempting to submit the form.

(function(){
var form = document.getElementById("letter_searchform");
var input = document.getElementById("letter_input");
form.addEventListener("submit", search, false);

function search(e) {
  // Stops form submission regardless of whether it was a click or a key event
  e.preventDefault();

  // If the input is empty, return
  var search_podcast_input = input.value;
  if (search_podcast_input == "") {
    $("#podcast_input_error").show().append('<br />');
    $("#podcast_input").focus().focusout(function() {
      $("#podcast_input_error").hide();
    });			
    return false;
  }
  
  // Send an AJAX request
  var dataString = 'search_input=' + search_podcast_input;
  $.ajax();
}
})();

 

Link to comment
Share on other sites

If I have understood you correctly,  I would then add the following listener in order to make the AJAX request via activation of the ENTER/RETURN key

form.addEventListener('keyup', search, false);

Is this correct?

In effect, I would have two listeners attached to the same form event.  Have I got it now?

Roddy

Link to comment
Share on other sites

No, you do not need a keyup listener. Pressing Enter on a form field automatically calls the forms submit method. The "submit" event is the one you should be listening for, not the keyup event.

Link to comment
Share on other sites

Ingolme:  I tried your code, but it failed.  As a result, I am going to try to rewrite it in jQuery -- a version of Javascript that I understand a little better.  In order to achieve this, however, I would like very much for you to answer the following questions in regard to your own code.

QUESTION ONE:  Is it possible for Javascript to be confused by the creation of new variables called form and input?  Might these not already exist within the javascript namespace?

QUESTION TWO: How does the word false function in the following expression.  How might I replicate its functionality with the jQuery .on( ) or .submit( ) methods?

form.addEventListener("submit", search, false);

MY ATTEMPT TO IMPLEMENT YOUR CODE

(function() {
//	$('.error').hide();
//	$(".SearchButton").click(function() {
	var form = document.getElementById("qa_searchform");
	var input = document.getElementById("qa_input");
	form.addEventListener("submit", search, false);

	function search(e) {
		e.preventDefault();

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

		// Send an AJAX request
		var dataString = 'search_input=' + search_qa_input;
		$.ajax({
			type: "POST",
			url: './_utilities/php/search_qa.php',
			data: dataString,
			dataType: 'JSON',
			statusCode: {
				404: function() {
				alert( "Page not found" );
			}},
		/*********************************
		First AJAX call. Success Function
		*********************************/
			success: function(jsonData) {
				$('#qa_matches').html('');
				$('#qa_matches').css({'background-color':'#fff','background-image':'none'}).html("<p>Your Search Results for [ <span style='font-weight:bold;'>" + search_qa_input + "</span> ] in descending order of matched relevance are:</p>");
				$.each(jsonData, function(key, object){
					$('#qa_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.qa_question + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>The Answer ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.qa_answer + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read</a></div><div><p style='font-size:0.8em;margin-top:-0.3em;'>the newsletter in which this question and answer first appeared!</p></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
				});
/*					$('#qa_matches').append('<div>letter_no: ' + object.letter_no + '<br />qa_question: ' + object.qa_question + '<br />qa_answer: ' + object.qa_answer + '<br />submission_date: ' + object.submission_date + '<br />revision_date: ' + object.revision_date + '</div>');
*/
/*					$('#letter_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.letter_title + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>Discover more ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.letter_abstract + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read!</a></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
*/
//				});
				var collection = $(".paginate");
				var collNum = collection.length;
				var perPage = 2;
				collection.slice(perPage).hide();
				$('#qa_matches').append("<div id='pagn'></div><!-- end div#pagn -->");
				$("#pagn").pagination({
					items: collNum,
					itemsOnPage: perPage,
					cssStyle: "light-theme",
					onPageClick: function(pageNum) {
						var start = perPage * (pageNum - 1);
						var end = start + perPage;
						collection.hide().slice(start, end).show();
						$('body, html').animate({scrollTop: $('#qa_matches').offset().top},800);

					}
				});
				/*********************
					Insert BEGINS here
				*********************/
				$("div.discover").mouseover(function() {
					$(this).find("span.discover_text").css({"cursor": "pointer","line-height":"1.6em","font-size":"1.4em"});
				});
				$("div.discover").click(function() {
					$(this).next("div.hidden_info").slideToggle(800, function() {
						$('.news_link').find('a').on('click', function(event){
						event.preventDefault();
						var attribute = $(this).attr('href');
						var href_arr = attribute.split('?');
						var query_str = href_arr[1];
						var pairs = query_str.split('&');
						var data = [];
						$.each(pairs, function(i, v){
							var pair = v.split('=');
							var key = pair[0];
							var value = pair[1];
							var data_arr = [key, value];
							data.push(data_arr);
						});

/***********************************************************************************************
							Call the Newsletter template						***********************************************************************************************/              
						var nested_ajax = $.ajax({
//										url: './_utilities/php/newsletter.php',
								url: './newsletter/template/newsletter_generator_local.php',
								method: 'GET',
//										data: {'hash': data[0][1],'letter_no': data[1][1]},
								data: {'letter_no': data[0][1]},
								dataType: 'html',
								statusCode: {
									404: function() {
										alert( "Page not found" );
									}
								},
								success: function(template) {
									$("#main").css('background-image','none').html(template);
									$("#letter_dissemination").hide();
									$('body, html').animate({scrollTop: $('#main').offset().top},800);
									$("#click_share").mouseenter(function() {
										$(this).css({'cursor':'pointer','color':'#5a4149'});
									});
									$("#click_share").click(function(){
										$("#letter_dissemination").slideToggle(800, function(){
											var jsSocialsURL ='./_utilities/javascript/jssocials.js';
											$.getScript(jsSocialsURL, function() {
												$("#share").jsSocials(
													{showLabel: false,
													showCount: false,
													shares: ["email", "twitter", "facebook", "googleplus", "linkedin", "pinterest", "whatsapp"]
												});
											});
										});
									})
									.mouseout(function() {
										$(this).css({'cursor':'none','color':'#4E7F4E'});
									}).end();
								},
								complete: function(jqXHR, textStatus) {
									if (history.pushState) {
										var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?letter_no=" + data[0][1];
										window.history.pushState({path:newurl},'',newurl);
										window.pushedNewUrl = newurl;
									}
								}
						});				
					});
					});
					$(this).mouseup(function() {
						$(this).css({"color": "#ccc", "font-weight": "normal"});
					});
//											$('body, html').animate({scrollTop: $(this).offset().top},800);
				})
				.mouseout(function() {
					$("span.discover_text").css({"cursor":"auto","line-height":"1.6em","font-size":"1em"});
				});
			},
			complete: function(jqXHR, status) {
				selfSearchResults_QA = $('#main').html();
				/*********************
					Insert ENDS here
				*********************/				
			}
		});
	}
//	});
})();

THE ONLINE REFERENCE (without your code)

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

When I replace this code with the above code, there are no error messages, but nothing appears.

Roddy

 

 

Edited by iwato
Link to comment
Share on other sites

Its not a good idea to use variable names such as form or input, as dot notation uses a similar method you are using, so confusion can arise. Even using id

reference name similar to function name can cause issues.

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

Please find below the three critical pieces of code used to implement button-and-key functionality as proposed by Ingolme.  They have been tested locally, but not remotely.  Without Ingolme's proposal the local and remote versions are identical.

The HTML (overview.html)

<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;'>
            <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 -->

jQUERY LOAD FUNCTIONS (overview.js)

$("#search_qa").mouseover(function() {
        $(this).css({"cursor": "pointer", "font-weight":"800"});
    })
    .mouseout(function() {
        $(this).css("font-weight", "normal");
});
//Causes the weight of the font to change, displays the hidden text to appear in the #main <div> element, and brings about a change in color.
$("#search_qa").mouseover(function() {
        $(this).css({"cursor": "pointer", "font-weight":"800"});
    })
    .click(function() {
        if (window.selfSearchResults_QA !== null) {
            var aside_height = $('aside').height();
//				$('#main').html(selfSearchResults_QA);
            $('#main').html(selfSearchResults_QA).css('min-height', aside_height);
            $.getScript('_utilities/javascript/search_second_go_qa.js');
            $.getScript('_utilities/javascript/search_qa.js');				
        } else {
            var aside_height = $('aside').height();
            var searchQAContent = $("#search_qa_div").html();
//				$("#main").html(searchQAContent);
            $("#main").html(searchQAContent).css('min-height', aside_height);
            $("#main .error").hide();
            $.getScript('_utilities/javascript/search_qa.js');
        }
    })
    .mouseup(function() {
        $(this).css({"color": "#fadb9d","font-weight": "normal"});
    $('body, html').animate({scrollTop: $('#main').offset().top},800);
});

The PROPOSED, but failed JAVASCRIPT

(function() {
//	$('.error').hide();
//	$(".SearchButton").click(function() {
	var form_var = document.getElementById("qa_searchform");
	var input_var = document.getElementById("qa_input");
	form_var.addEventListener("submit", search, false);

	function search(e) {
		e.preventDefault();

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

		// Send an AJAX request
		var dataString = 'search_input=' + search_qa_input;
		$.ajax({
			type: "POST",
			url: './_utilities/php/search_qa.php',
			data: dataString,
			dataType: 'JSON',
			statusCode: {
				404: function() {
				alert( "Page not found" );
			}},
		/*********************************
		First AJAX call. Success Function
		*********************************/
			success: function(jsonData) {
				$('#qa_matches').html('');
				$('#qa_matches').css({'background-color':'#fff','background-image':'none'}).html("<p>Your Search Results for [ <span style='font-weight:bold;'>" + search_qa_input + "</span> ] in descending order of matched relevance are:</p>");
				$.each(jsonData, function(key, object){
					$('#qa_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.qa_question + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>The Answer ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.qa_answer + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read</a></div><div><p style='font-size:0.8em;margin-top:-0.3em;'>the newsletter in which this question and answer first appeared!</p></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
				});
/*					$('#qa_matches').append('<div>letter_no: ' + object.letter_no + '<br />qa_question: ' + object.qa_question + '<br />qa_answer: ' + object.qa_answer + '<br />submission_date: ' + object.submission_date + '<br />revision_date: ' + object.revision_date + '</div>');
*/
/*					$('#letter_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.letter_title + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>Discover more ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.letter_abstract + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read!</a></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
*/
//				});
				var collection = $(".paginate");
				var collNum = collection.length;
				var perPage = 2;
				collection.slice(perPage).hide();
				$('#qa_matches').append("<div id='pagn'></div><!-- end div#pagn -->");
				$("#pagn").pagination({
					items: collNum,
					itemsOnPage: perPage,
					cssStyle: "light-theme",
					onPageClick: function(pageNum) {
						var start = perPage * (pageNum - 1);
						var end = start + perPage;
						collection.hide().slice(start, end).show();
						$('body, html').animate({scrollTop: $('#qa_matches').offset().top},800);

					}
				});
				/*********************
					Insert BEGINS here
				*********************/
				$("div.discover").mouseover(function() {
					$(this).find("span.discover_text").css({"cursor": "pointer","line-height":"1.6em","font-size":"1.4em"});
				});
				$("div.discover").click(function() {
					$(this).next("div.hidden_info").slideToggle(800, function() {
						$('.news_link').find('a').on('click', function(event){
						event.preventDefault();
						var attribute = $(this).attr('href');
						var href_arr = attribute.split('?');
						var query_str = href_arr[1];
						var pairs = query_str.split('&');
						var data = [];
						$.each(pairs, function(i, v){
							var pair = v.split('=');
							var key = pair[0];
							var value = pair[1];
							var data_arr = [key, value];
							data.push(data_arr);
						});

/***********************************************************************************************
							Call the Newsletter template						***********************************************************************************************/              
						var nested_ajax = $.ajax({
//										url: './_utilities/php/newsletter.php',
								url: './newsletter/template/newsletter_generator_local.php',
								method: 'GET',
//										data: {'hash': data[0][1],'letter_no': data[1][1]},
								data: {'letter_no': data[0][1]},
								dataType: 'html',
								statusCode: {
									404: function() {
										alert( "Page not found" );
									}
								},
								success: function(template) {
									$("#main").css('background-image','none').html(template);
									$("#letter_dissemination").hide();
									$('body, html').animate({scrollTop: $('#main').offset().top},800);
									$("#click_share").mouseenter(function() {
										$(this).css({'cursor':'pointer','color':'#5a4149'});
									});
									$("#click_share").click(function(){
										$("#letter_dissemination").slideToggle(800, function(){
											var jsSocialsURL ='./_utilities/javascript/jssocials.js';
											$.getScript(jsSocialsURL, function() {
												$("#share").jsSocials(
													{showLabel: false,
													showCount: false,
													shares: ["email", "twitter", "facebook", "googleplus", "linkedin", "pinterest", "whatsapp"]
												});
											});
										});
									})
									.mouseout(function() {
										$(this).css({'cursor':'none','color':'#4E7F4E'});
									}).end();
								},
								complete: function(jqXHR, textStatus) {
									if (history.pushState) {
										var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?letter_no=" + data[0][1];
										window.history.pushState({path:newurl},'',newurl);
										window.pushedNewUrl = newurl;
									}
								}
						});				
					});
					});
					$(this).mouseup(function() {
						$(this).css({"color": "#ccc", "font-weight": "normal"});
					});
//											$('body, html').animate({scrollTop: $(this).offset().top},800);
				})
				.mouseout(function() {
					$("span.discover_text").css({"cursor":"auto","line-height":"1.6em","font-size":"1em"});
				});
			},
			complete: function(jqXHR, status) {
				selfSearchResults_QA = $('#main').html();
				/*********************
					Insert ENDS here
				*********************/				
			}
		});
	}
//	});
})();

The above code works until something is entered into the search box, whereupon clicking the Search button or depressing the ENTER/RETURN key yields nothing.

Roddy

Link to comment
Share on other sites

The requirements of your project are not clearly defined. You should not be asking questions like "How do I simulate a click using a key event?". Your end goal is not to click a button, it's to perform the action that happens when the button is clicked. What is that action? I don't know, you haven't made it clear, but knowing exactly what that action is is the most important factor in solving the problem. For now, I'll call the action "X".

You have a form with a button and a text field. When the button is clicked, the form gets submitted. When somebody presses Enter in the text field, the form also gets submitted. Therefore we can perform action X during the submit event of the form. Do not use the click event. Do not use the keyup event. Only use the submit event.
 

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

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

In order to keep the code readable, I highly advise against using anonymous functions. It's mixing function declarations with your program logic. Give your functions names, then use those functions as arguments in your jQuery calls. Applying this principle to the code above yields this, which might appear longer at first, but when the code logic is complicated it is much easier to see what's going on when the function declarations are out of the way as long as the functions have meaningful names.

/* Code logic goes here */
$("REFERENCE TO FORM").on("submit", formSubmissionHandler);


/* Function declarations go here */
function formSubmissionHandler(e) {
	// Stop the form from reloading the page
	e.preventDefault();

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

 

Link to comment
Share on other sites

We are making progress -- sort of.  For, implementing the following strategy

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

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

results in a successful ENTER/RETURN form submission, but results in a failed button click.

(function() {
//	$('.error').hide();
//	$(".SearchButton").click(function() {
	$('#qa_searchform').on('submit', function(e) {
		e.preventDefault();
		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;
		}
		/********************************************************************************
		First AJAX call.  Send input search query to PHP processor for database retrieval 
		********************************************************************************/
		var dataString = 'search_input=' + search_qa_input;
		$.ajax({
			type: "POST",
			url: './_utilities/php/search_qa.php',
			data: dataString,
			dataType: 'JSON',
			statusCode: {
				404: function() {
				alert( "Page not found" );
			}},
		/*********************************
		First AJAX call. Success Function
		*********************************/
			success: function(jsonData) {
				$('#qa_matches').html('');
				$('#qa_matches').css({'background-color':'#fff','background-image':'none'}).html("<p>Your Search Results for [ <span style='font-weight:bold;'>" + search_qa_input + "</span> ] in descending order of matched relevance are:</p>");
				$.each(jsonData, function(key, object){
					$('#qa_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.qa_question + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>The Answer ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.qa_answer + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read</a></div><div><p style='font-size:0.8em;margin-top:-0.3em;'>the newsletter in which this question and answer first appeared!</p></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
				});
/*					$('#qa_matches').append('<div>letter_no: ' + object.letter_no + '<br />qa_question: ' + object.qa_question + '<br />qa_answer: ' + object.qa_answer + '<br />submission_date: ' + object.submission_date + '<br />revision_date: ' + object.revision_date + '</div>');
*/
/*					$('#letter_matches').append("<div class='paginate'><div class='item_info podcast_item'><div class='news_num'>No. " + object.letter_no + "</div><div class='news_title'>" + object.letter_title + "<br /><span class='pubdate'>" + object.submission_date + "</span></div></div><div class='discover'><span class='discover_text'>Discover more ...</span></div><div class='hidden_info'><div class='news_describe'>" + object.letter_abstract + "</div><div class='news_link'><a href='?letter_no=" + object.letter_no + "' title='Seven Gates - Edition No. " + object.letter_no + "' target='_self'>Click and Read!</a></div></div><!-- end div.hidden_info --><hr class='hr_divide' /></div><!-- end div.paginate -->");
*/
//				});
				var collection = $(".paginate");
				var collNum = collection.length;
				var perPage = 2;
				collection.slice(perPage).hide();
				$('#qa_matches').append("<div id='pagn'></div><!-- end div#pagn -->");
				$("#pagn").pagination({
					items: collNum,
					itemsOnPage: perPage,
					cssStyle: "light-theme",
					onPageClick: function(pageNum) {
						var start = perPage * (pageNum - 1);
						var end = start + perPage;
						collection.hide().slice(start, end).show();
						$('body, html').animate({scrollTop: $('#qa_matches').offset().top},800);

					}
				});
				/*********************
					Insert BEGINS here
				*********************/
				$("div.discover").mouseover(function() {
					$(this).find("span.discover_text").css({"cursor": "pointer","line-height":"1.6em","font-size":"1.4em"});
				});
				$("div.discover").click(function() {
					$(this).next("div.hidden_info").slideToggle(800, function() {
						$('.news_link').find('a').on('click', function(event){
						event.preventDefault();
						var attribute = $(this).attr('href');
						var href_arr = attribute.split('?');
						var query_str = href_arr[1];
						var pairs = query_str.split('&');
						var data = [];
						$.each(pairs, function(i, v){
							var pair = v.split('=');
							var key = pair[0];
							var value = pair[1];
							var data_arr = [key, value];
							data.push(data_arr);
						});

/***********************************************************************************************
							Call the Newsletter template						***********************************************************************************************/              
						var nested_ajax = $.ajax({
//										url: './_utilities/php/newsletter.php',
								url: './newsletter/template/newsletter_generator_local.php',
								method: 'GET',
//										data: {'hash': data[0][1],'letter_no': data[1][1]},
								data: {'letter_no': data[0][1]},
								dataType: 'html',
								statusCode: {
									404: function() {
										alert( "Page not found" );
									}
								},
								success: function(template) {
									$("#main").css('background-image','none').html(template);
									$("#letter_dissemination").hide();
									$('body, html').animate({scrollTop: $('#main').offset().top},800);
									$("#click_share").mouseenter(function() {
										$(this).css({'cursor':'pointer','color':'#5a4149'});
									});
									$("#click_share").click(function(){
										$("#letter_dissemination").slideToggle(800, function(){
											var jsSocialsURL ='./_utilities/javascript/jssocials.js';
											$.getScript(jsSocialsURL, function() {
												$("#share").jsSocials(
													{showLabel: false,
													showCount: false,
													shares: ["email", "twitter", "facebook", "googleplus", "linkedin", "pinterest", "whatsapp"]
												});
											});
										});
									})
									.mouseout(function() {
										$(this).css({'cursor':'none','color':'#4E7F4E'});
									}).end();
								},
								complete: function(jqXHR, textStatus) {
									if (history.pushState) {
										var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?letter_no=" + data[0][1];
										window.history.pushState({path:newurl},'',newurl);
										window.pushedNewUrl = newurl;
									}
								}
						});				
					});
					});
					$(this).mouseup(function() {
						$(this).css({"color": "#ccc", "font-weight": "normal"});
					});
//											$('body, html').animate({scrollTop: $(this).offset().top},800);
				})
				.mouseout(function() {
					$("span.discover_text").css({"cursor":"auto","line-height":"1.6em","font-size":"1em"});
				});
			},
			complete: function(jqXHR, status) {
				selfSearchResults_QA = $('#main').html();
				/*********************
					Insert ENDS here
				*********************/				
			}
		});
	});
})();

Further elaboration is requested.

Roddy

 

Edited by iwato
Link to comment
Share on other sites

JSG - The original intent of this thread was to discover a way to prevent users from blowing away form data on the one hand and allowing them to submit it in two different ways (form button and ENTER/RETURN key) on the other.  This has not changed despite the various directions in which the discussion has progressed.

It all began when i disabled the default behavior of the <input type='submit'> form element so that I could achieve additional tasks when the user submitted his form data using the form element.  Disabling the default behavior of the this element, however, caused depression of the ENTER/RETURN key to renew the entire page and blow away the user's form data.  As many user's are accustomed to submitting form data via the ENTER/RETURN key I have been looking for a way to get the form element and ENTER/RETURN key to achieve the same task.

The most recently published code causes the form data to be submitted and activates the additional behavior as it should, but the same cannot be triggered by clicking on the <input type='submit'> form element.

In contrast, the correction previous to the most recent correction achieved the opposite:  clicking on the <input type='submit'> element caused the data to be submitted and activated the additional behavior but silenced the ability of the ENTER/RETURN key to achieve the same task.

Is it not reasonable to believe that clicking on the form control and the ENTER/RETURN key could both achieve the same task -- namely, cause the user's form data to be submitted and consummate the additional tasks?

I hope that this renders the matter clear.

Roddy

 

Link to comment
Share on other sites

Is it not reasonable to believe that clicking on the form control and the ENTER/RETURN key could both achieve the same task -- namely, cause the user's form data to be submitted and consummate the additional tasks?

Not only is it reasonable, but it is the default behavior for form controls.  Pressing enter while in a text field will submit the form by default.  If that's not happening, then you've stopped the default behavior and now you're trying to find a way to add it back.  

Either way, Ingolme is correct.  You should not change the default behavior of anything in the form, don't mess with the click events or whatever else.  Focus only on the submit event, and then no matter how they submit the form your function will still run.

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...