How to trigger click event when pressing enter key? Text area - html

I have search area which works fine as I need it to but the problem is when i hit enter it won't search for results, so you need to press button to do so. I tried different codes but nothing is working and I'm wondering if anyone has solution for it. This is code that I have:
<input
data-path=".title"
data-button="#title-search-button"
type="text"
value=""
placeholder="Search..."
data-control-type="textbox"
data-control-name="title-filter"
data-control-action="filter"
/>
I guess this could work with "onkeydown=" but not really sure what to add after it.
I would really appreciate if someone has solution for this.

Although you can use the onkeydown attribute I prefer to do these things through JavaScript event listeners & handlers. If you want to do this with the onkeydown attribute then look at Bryan's answer.
I would first add an ID/Class name to the input so we can easily target it. In my example i will add searchTextas the ID for this input.
JavaScript:
document.getElementById('searchText').addEventListener("keydown",function(e){
if(e.keyCode == 13){
//doSomething()
}
});
jQuery:
$('#searchText').on('keydown',function(e){
if(e.which == '13'){
//doSomething();
}
});

Yes, this would work with keydown. But you will need to add javascript for it to work.
<input
data-path=".title"
data-button="#title-search-button"
type="text"
value=""
placeholder="Search..."
data-control-type="textbox"
data-control-name="title-filter"
data-control-action="filter"
onkeydown="if (event.keyCode == 13) { // Your search results code here;
return false; }"
/>

You will have to add an event listener for keyup for your input field. e.keyCode will give you the special keys (which happens to be 13 for Enter)
Here is an example:
$("#myinput").on('keyup', function (e) {
if (e.keyCode == 13) {
alert("Enter clicked");
// add your code here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
id = "myinput"
data-path=".title"
data-button="#title-search-button"
type="text"
value=""
placeholder="Search..."
data-control-type="textbox"
data-control-name="title-filter"
data-control-action="filter"
/>
Hope this helps!

I have given a sample code below using plan javascript. This solution will work without jquery or other libraries.
On the key press event, you can either call the same method of the click event (or) trigger the button click directly as per the option 1 and option 2 mentioned below.
function triggerSearch() {
if(event.keyCode === 13) {
// Option 1: You can call the 'search' method directly
//search();
// Option 2: OR you can trigger the button `click` event
getElement('searchButton').click();
}
}
function search() {
var searchTerm = getElement('searchTextBox').value;
getElement('searchTerm').innerHTML = searchTerm;
}
function getElement(id) {
return document.getElementById(id);
}
<input
data-path=".title"
data-button="#title-search-button"
type="text"
value=""
placeholder="Search..."
data-control-type="textbox"
data-control-name="title-filter"
data-control-action="filter"
id="searchTextBox"
onkeydown="triggerSearch()"
/>
<input type="button" value="Search" id="searchButton" onclick="search()" />
<br/><br/>
Search Term: <span id="searchTerm"></span>

Related

I made the html & js code to do the validation check. But the data is submitted before checking the data

<form name="mForm" action="${pageContext.request.contextPath}/login/insertSeller.do" method="post">
id : <input type="text" name="id" />
<input type="submit" value="register" onClick="doAction()" />
</form>
<script>
function doAction() {
var f = document.mForm;
var id = f.id;
if (id.value == "") {
alert("insert your id");
id.focus();
return false;
}
return true;
}
</script>
Is there any error to correct?
If I click the button, the alert window opens with a message,
but the data is submitted without the validation check.
What do I need to do?
Please help me :)
You really shouldn’t have inline event handlers in modern HTML. Nevertheless, you could try the following:
<input … onclick="return doAction()">
The return in the onclick causes the input to wait for permission.
For the sake of completeness, here is how I would do it in a modern browser:
First, use a button instead:
<button type="submit">register</button>
Second, give your button a name
<button name="register" type="submit">register</button>
You can give a name to the older style input element, and the process will still work.
Next, add the following to your JavaScript:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('button[name="register"]).onclick=doAction;
},false);
The main function acts as a startup script. The point of it is that it is waiting for the DOM to have loaded. Otherwise it’s not possible to look for elements that aren’t there yet.
Note that you assign to the onclick event handler the name of the function.

How can I detect keydown or keypress event in angular.js?

I'm trying to get the value of a mobile number textbox to validate its input value using angular.js. I'm a newbie in using angular.js and not so sure how to implement those events and put some javascript to validate or manipulate the form inputs on my html code.
This is my HTML:
<div>
<label for="mobile_number">Mobile Number</label>
<input type="text" id="mobile_number" placeholder="+639178983214" required
ngcontroller="RegisterDataController" ng-keydown="keydown">
</div>
And my controller:
function RegisterDataController($scope, $element) {
console.log('register data controller');
console.log($element);
$scope.keydown = function(keyEvent) {
console.log('keydown -'+keyEvent);
};
}
I'm not sure how to use the keydown event in angular.js, I also searched how to properly use it. And can i validate my inputs on the directives? Or should I use a controller like what I've done to use the events like keydown or keypress?
Update:
ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.
<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">
<!-- or call a controller/directive method and pass $event as parameter.
With access to $event you can now do stuff like
finding which key was pressed -->
<input ng-keypress="changed($event)">
Read more here:
https://docs.angularjs.org/api/ng/directive/ngKeypress
https://docs.angularjs.org/api/ng/directive/ngKeydown
https://docs.angularjs.org/api/ng/directive/ngKeyup
Earlier solutions:
Solution 1: Use ng-change with ng-model
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController" ng-change="keydown()">
JS:
function RegisterDataController($scope) {
$scope.keydown = function() {
/* validate $scope.mobileNumber here*/
};
}
Solution 2. Use $watch
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController">
JS:
$scope.$watch("mobileNumber", function(newValue, oldValue) {
/* change noticed */
});
You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.
The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):
var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// this next line will convert the string
// function name into an actual function
var functionToCall = scope.$eval(attrs.ngKeydown);
elem.on('keydown', function(e){
// on the keydown event, call my function
// and pass it the keycode of the key
// that was pressed
// ex: if ENTER was pressed, e.which == 13
functionToCall(e.which);
});
}
};
});
The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:
<input type="text" on-keydown="onKeydown">
And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:
$scope.onKeydown = function(keycode){
// do something with the keycode
}
Hopefully that helps either you or someone else who wants to know
You can checkout Angular UI # http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress
(also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.

Making 'file' input element mandatory (required)

I want to make (an HTML) 'file' input element mandatory: something like
<input type='file' required = 'required' .../>
But it is not working.
I saw this WW3 manual which states 'required' attribute is new to HTML 5. But I am not using HTML 5 in the project I am working which doesn't support the new feature.
Any idea?
Thanks to HTML5, it is as easy as this:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>
You can do it using Jquery like this:-
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadfile').val();
if(imgVal=='')
{
alert("empty input file");
return false;
}
});
});
</script>
<input type="file" name="image" id="uploadfile" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
As of now in 2017, I am able to do this-
<input type='file' required />
and when you submit the form, it asks for file.
You could create a polyfill that executes on the form submit. For example:
/* Attach the form event when jQuery loads. */
$(document).ready(function(e){
/* Handle any form's submit event. */
$("form").submit(function(e){
e.preventDefault(); /* Stop the form from submitting immediately. */
var continueInvoke = true; /* Variable used to avoid $(this) scope confusion with .each() function. */
/* Loop through each form element that has the required="" attribute. */
$("form input[required]").each(function(){
/* If the element has no value. */
if($(this).val() == ""){
continueInvoke = false; /* Set the variable to false, to indicate that the form should not be submited. */
}
});
/* Read the variable. Detect any items with no value. */
if(continueInvoke == true){
$(this).submit(); /* Submit the form. */
}
});
});
This script waits for the form to be submitted, then loops though each form element that has the required attribute has a value entered. If everything has a value, it submits the form.
An example element to be checked could be:
<input type="file" name="file_input" required="true" />
(You can remove the comments & minify this code when using it on your website)
var imgVal = $('[type=file]').val();
Similar to Vivek's suggestion, but now you have a more generic selector of the input file and you don't rely on specific ID or class.
See this demo.
Some times the input field is not bound with the form.
I might seem within the <form> and </form> tags but it is outside these tags.
You can try applying the form attribute to the input field to make sure it is related to your form.
<input type="file" name="" required="" form="YOUR-FORM-ID-HERE" />
I hope it helps.
All statements above are entirely correct. However, it is possible for a malicious user to send a POST request without using your form in order to generate errors. Thus, HTML and JS, while offering a user-friendly approach, will not prevent these sorts of attacks. To do so, make sure that your server double checks request data to make sure nothing is empty.
https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>

HTML Text Input: Avoid submit when enter is pressed

I have an HTML input which is a textfield.
When I am pressing the enter, this will call the submit, which is normal.
Now, I would like to do something else when Enter is clicked on that textBox.
I am trying something like that:
<input type="text"
id="first_page"
onPaste=""
onkeydown="if (event.keyCode == 13) alert('enter')" />
The alert works well but the submit is still done. My page is reloading after that.
Could you help me please.
write return false; and check it
Using jQuery:
<script>
$('#first_page').keypress(function(e) {
if (e.keyCode == '13') {
e.preventDefault();
//your code here
}
});​
</script>
using javascript
<input type="text" id="first_page" onPaste="" onkeydown="if (event.keyCode == 13) { alert('enter');return false;}" />
Other option would be using onkeypress
<input type="text" id="first_page" onPaste="" onkeypress="if (event.keyCode == 13) {alert('enter'); return false;}" />
You could try the below script :
<script>
function checkEnter(event)
{
if (event.keyCode == 13)
{
alert('enter')
return false;
}
}
</script>
And the Html:
<input type="text" id="first_page" onPaste="" onkeydown="return checkEnter(event);" />
You should be returning false in the keydown event handler function in order to prevent further processing of the event.
Also, you might find the following question useful: Prevent Users from submitting form by hitting enter.
write the following code after alert('enter')
return false;
Use this, it worked in mine.
Replace on the keydown:
onkeydown="if (event.keyCode == 13 || event.which == 13) event.preventDefault();"
$(function () {$('#form').validationEngine(); });
It will work in my mvc problem
using jquery you can avoid all submiting or some element
$("#form").submit(function(e) {
e.preventDefault();
});

Return Key: How to focus the right form

I have more than one form on the same page:
I would like to know if there is any way I can submit the right form when the user press the "return keyboard key" ?
Thanks
How about this:
<form id="form1">
<input type="text" />
</form>
<form id="form2">
<input type="text" />
</form>
<script type="text/javascript">
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onkeypress = function(e) {
e = e || window.event;
if (e.keyCode == 13)
this.submit();
}
}
</script>
Basically loop through each form, wire the onkeypress event for each one that checks for enter (keycode == 13) and calls submit on that form.
I assume by right form you mean the form the user is working on !
Well it is not the cleanest of way but if you really want to work this way, You can designate form boundaries and you can set the focus to the appropriate submit button as soon as the user scroll pass from one form to other.
With neater version, you can drive the users to chose appropriate options and lead them to work on a single form (may be hide the irrelevant form once you get enough information about what user is going to work on)
Check which element has the focus. Check which form is his parent. Execute submit.
document.onkeypress = function() {
var element = activeElement.parentNode;
while(element.nodeType != /form/i) {
element = element.parentNode;
}
element.submit();
}