Onkeypress function not working on bootstrap input box - javascript

I've been trying to code a function that goes to a different page when the user hits the enter key into a certain input box. Here's the code:
<div class="container">
<div class="row">
<form>
<div id="search" onkeypress="enter(event)" >
<div class="input-group col-md-offset-8 col-md-3">
<input type="text" class="form-control">
<div class="input-group-btn">
<i class="glyphicon glyphicon-search"></i>
</div>
</div>
</div>
</form>
</div>
</div>
<script>
function enter(event){
if (event.keyCode == 13){
document.location.href = "newpage.com";
}
}
</script>
Thanks in advance!

What's happening is simple, you have a "form" tag, so when you hit enter, "onkeypress" is firing the event and the function "enter" that you created is handling that event, but having a "form" tag it just submitting a form.
To avoid that, just remove the "form" tag or just replace it for the following:
<form onsubmit="event.preventDefault();">
Also, you have to add the protocol if you want to redirect to a different page, like:
document.location.href = "http://newpage.com";
I hope it helps :)

Related

Enter to submit form

I am having trouble adding code to be able to submit form by clicking Enter. I have tried a few things, but I simply cannot make it work.
I'm quite new, so that might be why.
Thank you guys in advance.
<div class="box">
<h1>Foretag et opkald via Remote Control</h1>
<input type="number" id="dial">
<a id="call" href="" target-"null">Start opkald til <span id="tel"></span>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>
<script>
$('#dial').on('input', function() {
$('#tel').html($(this).val())
$('#call').attr("href", "http://192.168.6.91/servlet?key=number=" + $(this).val() + "&outgoing_uri=9081#213.128.137.88")
console.log($(this).val()) // get the current value of the input field.
});
</script>
If you want to perform any activity like form submittion based on enter pressed on textbox, you can track it by keycode in keyup event.
<div class="box">
<h1>Foretag et opkald via Remote Control</h1>
<input type="number" id="dial">
<a id="call" href="" target-"null">Start opkald til <span id="tel"></span>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>
<script>
$('#dial').on('keyup', function() {
var keycode = (event.keyCode ? event.keyCode : event.which);
$('#tel').html($(this).val())
$('#call').attr("href", "http://192.168.6.91/servlet?key=number=" + $(this).val() + "&outgoing_uri=9081#213.128.137.88")
console.log($(this).val()) // get the current value of the input field.
if(keycode == '13'){
//form submit
$('#call')[0].click();
}
});
</script>
In pure HTML:
<form>
<input id="myinput"/>
<button onclick="alert(document.getElementById('myinput').value)">Send</button>
</form>
A button inside a form will automatically be triggered whenever enter is pressed.
Instead of this:
<div class="box">
<h1>Foretag et opkald via Remote Control</h1>
<input type="number" id="dial">
<a id="call" href="" target-"null">Start opkald til <span id="tel"></span>
</div>
Try this:
<from id="#formId">
<h1>Foretag et opkald via Remote Control</h1>
<input type="number" id="dial">
<input type="submit" value="Enter">
</from>
To submit the form:
$("#myform").submit(function(e) {
// prevent Default functionality
e.preventDefault();
// get the input values from the from
});
If you wrap your input in a form, it will submit on enter key by default.
Here's an example of how to use this:
const form = document.getElementById("form");
form.addEventListener("submit", e => {
e.preventDefault();
const children = e.target.children;
for (child of children) {
if (child.type !== "submit") {
console.log(child.value); // do something here
}
}
})
<form id="form">
<input type="text"/>
<textarea></textarea>
<input type="submit" value="Submit">
</form>
It iterates over elements in a form and does something with each non-submit element. Note that pressing enter in a textarea will just create a new line.

Prevent angular form from submitting if input is blank

I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.

Angular blur validation preventing submission of separate form

I have an Angular page with a form for adding people, and a button (outside this form) to submit the list of people.
When the user focuses on a text input in the form, and then clicks to submit the list, the validation error from the text input appears but the submit event never occurs.
An example of this issue here: http://plnkr.co/edit/6Z0UUs
<div ng-controller="MyCtrl as vm">
<form name="form1" novalidate="">
<input type="text" name="field1" ng-model="vm.name" required>
<div ng-messages="form1.field1.$error" ng-if="form1.field1.$touched">
<label ng-message="required">Name is required</label>
</div>
<!--
This form adds a person to a list. I've not included this code to keep the example simple
<input type="submit" value="Add person">
-->
</form>
<button ng-click="vm.submit()">Submit list</button>
</div>
-
angular.module('myApp',[])
.controller('MyCtrl', function() {
var vm = this;
vm.name = '';
vm.submit = function () {
alert('submitted');
};
});
To replicate:
Click on the text input but leave blank
Click submit
Current behavior: "Name is required" appears thanks to the validation. Clicking 'Submit' again displays the 'submitted' alert.
Expected behavior: "Name is required" appears thanks to the validation and the 'submitted' alert appears.
Desired behavior: The 'submitted' alert appears and I add some code to vm.submit() to hide the 'Name is required' validation message as it's not important when the list is submitted.
I've observed that removing the ng-messages block fixes the issue, but I do need to show a validation message. Using a more basic directive (ng-show) to show the validation message instead does not help.
Any insights into what I'm doing wrong, or workarounds to achieve my desired behavior, would be great!
[Modified Answer] :
Here is a working plunker : http://plnkr.co/edit/JCyRi8xp4L3FtafABblS?p=preview
vm.preventDefaultIfSubmitted = function($event){
if($event.relatedTarget.id == "submit"){
$event.stopImmediatePropagation();
}
};
The idea is to get the $event when the blur occurs and then to look at the id of the relatedTarget (which is your button in this case) and if it is then you cancel the $event, otherwise you keep it.
That way if you click anywhere your validation message appears and if you click on submit it doesnt
May this help for form validation
<form role="form" name="projectBriefFrm">
<div class="form-group">
<label for="project_title">Project Title
<sup>*</sup>
</label>
<input ng-model="project.title" ng-required="true" type="text" class="form-control" name="title" placeholder="Untitled Project"
/>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.title.$invalid">Please provide title</span>
</div>
<div class="container" id="editor-title">
<label for="project_brief">Project Brief
<sup>*</sup>
</label>
<div class="row" id="editor">
<div class="col-lg-12 nopadding">
<textarea ng-model="project.brief" name="brief" cult-editor ng-required="true"></textarea>
</div>
</div>
</div>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.brief.$invalid">Please provide project brief</span>
</div>
</div>
</form>

php Form with jquery validation issue

** Updated with additional code **
I am redesigning a site for someone and reusing some of the php code from the previous developer. The form submits and does validation server-side on the process page. This is obviously bad from a user experience perspective. I am trying to incorporate jquery validation. I am more of a designer and have limited knowledge on php and moderate jquery.
Its a pretty straight forward form that has 2 submit options at the end. 1 button for paying with a check, 1 for paypal.
The code being used for these buttons is completely bypassing my jquery form validation. If I put a simple submit button the jquery validation kicks.
This is the code for the 2 buttons being used.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('form').validate();
});
</script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name: </label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a href="javascript:void(0)" onclick="document.regform.Submit.value = 'PayPal'; document.regform.submit()" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a href="javascript:void(0)" onclick="document.regform.submit()" class="btn btn-primary" >
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
The buttons are simply passing either paypal or null into the form submit process page and then redirecting after that. Is there a way I can make this pass jquery validation and then submit with those values?
You just need to add a rules object for the FirstName field and remove the attributes from the input element.
Also the following doesn't work:
// Uncaught TypeError: Cannot set property 'value' of undefined
document.regform.Submit.value = 'PayPal';
However if it did work there is a corner case, where the user clicks the paypal button but the form does not validate, the user then fixes the validation errors and submits the form with the check button. In this event the form will be submitted with Submit=PayPal.
jQuery(function($) {
var form = $('#lx'), submit = $('input[name=Submit]', form);
form.validate({
rules: {
FirstName: {
required: true,
minlength: 2
}
}
});
// lets keep JavaScript out of the DOM
$('#bypaypal, #bycheck').on('click', function(event) {
var paymentType = event.target.id === 'bypaypal' ? 'PayPal' : '';
submit.val(paymentType);
form.submit();
});
// this is just for demo purposes, you don't need it
form.on('submit', function() {
if (form.valid()) {
alert('Form is valid: Submit="' + submit.val() + '"');
}
});
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname">
<span class="font-standout">*</span> First Name:
</label>
<div class="col-sm-8">
<input type="text" name="FirstName" class="form-control input-lg mrs mls" />
<input type="hidden" name="Submit" value="" />
</div>
</div>
<a href="javascript:void(0);" id="bypaypal" class="btn btn-primary">
<i class="fa fa-paypal"></i>
<br/>Pay with Paypal Online
</a>
<a href="javascript:void(0);" id="bycheck" class="btn btn-primary">
<i class="fa fa-check"></i>
<br/>Pay By Check
</a>
</form>
Probably what's going on is the inline-javascript is hi-jacking the code and it never makes it to the jQuery validation. So remove it. Also, it's a good idea to add IDs to the a tag submit buttons to easily capture the click event. You also need to suppress the default action of an a tag, so use event.preventDefault (note that you must pass the event param into the .click function)
(1) Remove inline javascript.
(2) Assign IDs to your anchor tags.
(3) Then, use jQuery to test for click event.
working jsFiddle
HTML:
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name:</label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a id="paypal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a id="normal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
</form>
jQuery:
$('#paypal_submit, #normal_submit').click(function(e){
e.preventDefault; //stop a tag default action
var submit_type = this.id.split('_')[0]; //paypal or normal
var fn = $('#firstname').val();
if (fn=='' || fn.length < 4){
alert('Invalid first name');
$('#firstname').css({'background':'yellow','border':'1px solid orange'}).focus();
return false;
}else{
if (submit_type == 'paypal'){
$('#lx').val('PayPal').submit();
}else{
$('#lx').submit();
}
}
});
If you have multiple fields to check, here is another jsFiddle Demo that shows how to handle that:
http://jsfiddle.net/tyvk15cg/

Ember.js TextField action submits form

I have the following form:
<form class="form-horizontal" {{action "formSubmit"}}>
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
As you notice, I have two actions for this form:
When I type on the user input field and press enter, it fires the findUser action
When the form submits, the formSubmit action is called.
Now, here's the problem.
When I type something on the user text field and press enter, it fires the findUser action but also fires the formSubmit. As I know, this is how a form normally behaves. When you press enter on a text field, it submits the form.
Is there a workaround on this behavior? That when I press enter on a the user text field, I want the findUser action to be fired but not submit the form.
Please help.
One workaround is removing form itself. You can have action on button. You may have to sacrifice some form related features but still works very well. Here is the jsbin.
http://emberjs.jsbin.com/nifim/2/edit
There might be some other better way as well.
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser" bubbles=false}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary" {{action "formSubmit"}}>Save</button>
and javascript
App.IndexController = Ember.Controller.extend({
actions: {
findUser: function(){
console.log('Find User');
},
formSubmit: function(){
console.log('Form Submit');
}
}
});
Another workaround that allows using the form:
http://emberjs.jsbin.com/povud/1/
Just add 'onkeypress="return event.keyCode != 13;"' to the form element and place the {{action}} on the button itself:
<form class="form-horizontal" onkeypress="return event.keyCode != 13;">
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button class="btn btn-primary" {{action "formSubmit"}}>Save</button>
</form>

Categories