How to trigger onclick function when user inputs keywords? Jquery - javascript

I have an input box
<input type="text" name="search" id="search" />
<img src="icon.png" alt="" id="doSearch" />
I use Jquery and I have onclick event for "doSearch". So when I enter some words like "ab" .. and click on "icon" It sends an ajax request to php file and gets results back appended to dom.
$('#doSearch').click(function() {
$(".showResults").show("fast");
var input_text = $('input[name="search"]').val(); //retrieve text
$.ajax({
method: "get" ...
... some more lines
}) etc etc
I am wondering how can I trigger onclick function automatically, when some characters are entered in the input box so that users dont have to click on image icon to get the results. Also, how I can set focus on the image icon when I press tab key while in the input box.
Thanks a lot for your help.
EDIT:
I have some other input boxes in the same form as well. So this input acts as somewhat similar to stack overflow tags input.

Something like that?
$('#doSearch').keyPress(function(e){
if($(this).val()=='??') $('#doSearch').trigger('click')
});

The proper way to do it would be to do this:
<form id='search'>
<input type="text" name="search" id="search" />
<input type="image" src="icon.png" />
</form>
That way the image will be the submit button of the form, and whenever a user presses enter the form's submit event will be fired and you can do what you want.
This is how you could do the jQuery:
$('#search').submit(function() {
// do what you were doing
return false; // prevent form submission
});
This will also have the upside of being friendly to people with Javascript disabled, as you could then check in the server if it is not an AJAX request and perhaps display the full page with the requested content instead. I am pretty sure this will also make it so that TAB goes to the image as well.

Related

How to submit a form without action or submit button

I was looking at one image web site and was puzzled by the javascript they used. The web site has a image, below that there is a text input field you can input your comments. After you input your comments, you press the enter key to commit the comment.
The html looks like this:
<form class="-cx-PRIVATE-PostInfo__commentCreator" data-reactid=".0.1.0.0.0.2.2.1">
<input class="-cx-PRIVATE-PostInfo__commentCreatorInput" placeholder="Add a comment…" type="text" value="" data-reactid=".0.1.0.0.0.2.2.1.0">
</form>
There is no action in the form and no submit button. How can they submit the form?
The form's action attribute will default to the current URL.
Try filling in some text and hitting enter:
<form>
<input type="text" name="lookInTheUrlAfterHittingEnter" />
</form>
As #Traktor53 says, hitting enter whilst focus is on the text input will submit the form.
Input elements of type text (for a single line of text) have submitted their form if the enter key is pressed while filling them in since the year dot AFAIK. I did not find any mention of this in HTML5's documentation for this input type element.

Accidental JavaScript redirct?

I have a form that adds an item to a list when I press enter or hit a submit button. I'm not sure what I've changed, but suddenly pressing enter seems to redirect the URL, while clicking the button acts normally.
The HTML portion looks like this:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
</form>
The jQuery is:
$('#check').click(function () {
addIngredient('new-ingredient');
});
$('.new-ingredient').keypress(function (e) {
if (e.keyCode == 13) {
addIngredient('new-ingredient');
}
});
So it's running the same function either way. In both cases, it successfully adds the ingredient to the list, but in the 2nd case, the page is redirected from "recipe.html" to "recipe.html?new-ingredient=".
And here's the part that really confuses me: when I add an extra input to the form, this problem doesn't occur when I press enter in either box:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<input type="text"></input>
</form>
Also, if I add in an actual button (not my clickable image), it redirects like pressing enter, even though I have no code to do anything if the button is pressed. In this case, the extra input field has no effect.
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<button id="button">Add Ingredient</button>
</form>
I have absolutely no idea why this is happening. Even if I get rid of the jQuery to perform an action when I hit enter, this still happens. I'm new to JavaScript, so sorry if this is something obvious, but I'd really appreciate some help.
I can also provide more of my code if it's relevant, but I didn't want to clog things up with a ton of code.
Hitting enter (or clicking the button if its there) is submitting the form (this makes it appear to "redirect the URL"). You need to prevent that from happening with e.preventDefault(). So in the click listener:
$('#button').click(function(e){
e.preventDefault();
addIngredient('new-ingredient');
});
Put that in each of the listeners, or get rid of your form tags so there isn't anything to submit (as was mentioned in the comments).
I don't entirely blame you for being confused. The browser default behavior is to perform the "submit" action, whatever it is, when someone presses enter while a field in the form is highlighted. As elclanrs said, you can override the submit action; in fact, I'm pretty sure in JQuery it's just this:
$('#add-ingr').submit(function(e) {
if ('event is not coming from button')...{
e.preventDefault();
}
});
I'm afraid I couldn't explain why adding a blank input changed the effect, though. Through my laziness, I have also left you the work of determining the best way of allowing actual submissions, though (if the form gets submitted to the server, you won't want to block submit every time)

Submit form to new window only when specific submit button is pressed?

I have a form, which has a few different submit buttons on it all doing different things with the same post data.
Lets say for simplicity sake the form looks like this:
<form method="post">
<input type="hidden" name="ids" value="1,2,3,4" />
<input type="submit" id="picking" name="picking" value="Picking" />
<input type="submit" id="shipping" name="shipping" value="Shipping" />
<input type="submit" id="invoice" name="invoice" value="Invoice" />
</form>
At the moment the form submits to itself and I work out server side which submit button is pressed, build a URL from the POST data, then do a PHP redirect to what I need to go. This works fine.
However, I am looking for the form to post its data to a new window, but only when "invoice" is clicked. This rules out just adding target="_blank" to the form, as the other 2 buttons would submit to new pages as well.
I also can't split the form into 3 different forms as the data is a lot more complex than the above, and a lot of it is input by the user.
Is there a way to do this using JavaScript/JQuery? If so, where would I start?
Thanks
could you not add target blank to the form when invoice is clicked?:
$("#invoice").click(function(){
$('#form_id').attr('target', '_blank');
});
or:
$(document).on("click","#invoice",function(){
$('#form_id').attr('target', '_blank');
});
Try adding a click handler to the correct submit button.
$('#invoice').on('click', function(){
//doStuff
});
This will allow you to control the action of #invoice without affecting the others.

Button onclick works fine but undesired behavior when pressing enter to submit form

I'm not sure if I need a form for this, it's a javascript that takes an input from a textbox, does some calculation on it, and displays the results in a div. I just want the user to be able to submit by clicking submit or by pressing enter.
In short, if the button type is "button", clicking works fine but pressing enter works strangely, and if the button type is "submit", pressing enter works fine, but clicking works strangely. Below is a sample of the code (removed some business logic and other variables that were working fine to make it simpler to display here):
<form action="#" onsubmit="calcserial()">
Serial no: <input type="text" name="serialno" id="serialno" /><br />
<input type="button" value="Submit" onclick="calcserial()" />
</form>
<script type="text/javascript">
function calcserial(){
var x=document.getElementById('serialno').value;
var year=[business logic];
var month=[business logic];
document.getElementById('results').innerHTML="Shipped: " + month + ", " + year;
}
</script>
<div id=results></div>
To give more detail about the strange behavior, when input type is "button" and I press enter, rather than running the calcserial() function, the textbox is cleared and the url is changed to:
[filename].php?serialno=[value]#
With [value] being what ever was in the text box. Then, if I put in the same exact value again and press enter again, it works as intended, but only if the url already shows the value I am submitting. If I enter a different value, the text box is cleared again and the url is changed to show the new value. If I switch the input type to "submit", the problem is resolved for pressing enter, but the same problem then occurs when clicking the button to submit.
Why is this happening? Any ideas how to resolve it? Thanks!
Try changing this:
<form action="#" onsubmit="calcserial()">
To this:
<form action="#" onsubmit="calcserial();return false;">
That should stop the default action that would normally happen on submit of a form, which in your case with action="#" results in the same page being reloaded.
Given that you don't actually want to submit anything (to the webserver) you don't really need a form for this. An <input type="button"> plus checking for enter onkeyup of the text input could achieve the same effect.

textbox should invoke button click event

I have a textbox and a button; the button click event navigates to other location in the website. I want to do the same thing on pressing the enter key but unable to do that. Please help me solve this. My code snippet follows:
function call()
{
document.location= "location.aspx";
}
<input type="text" id="txt1" onkeydown ="if(event.keyCode==13)document.getElementById('bt1').click()"/>
<input type="button" id="bt1" value ="Hit me" onclick ="call()" />
This is the same as the click, both would call this function...
onkeydown ="if(event.keyCode==13) call()"
If you can edit your HTML code, you wont probably need to do any JS to get this to working.
The INPUT fields in your HTML should be wrapped inside a FORM tag (atleast thats how it semantically makes more sense in most of the cases).
If you can do that, you can then change the INPUT element from TYPE button to Type SUBMIT and can then listen for the onsubmit event on your FORM element.
The event is fired both on pressing of enter key and click of the button and it works pretty smoothly across the browsers. The only problem is IE which doesnt fire the onsubmit event on a form with just 1 text input field. For that, you will have to insert another field into the form. You can hide it for your case. More ref at : http://style-vs-substance.com/development/form-submit-by-enter-key-and-internet-explorer/
EDIT: Code Sample
<form id="myForm">
<!--[if IE]>
<input type="text" style="display: none;" disabled="disabled" size="1" /><![endif]-->
<input type="text"/>
<input type="submit" value="Search"/>
</form>
Then in your JS:
var formHandler = document.getElementById('myForm');
formHandler.onsubmit = function(){
//this callback will be invoked both by the search button and enter key now
//your logic here
}

Categories