Populating form on keydown ENTER and preventing form from submitting - javascript

JS
$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
e.prevent_default();
return false;
}
$('#save_clinic').submit(function(){return false;});
});
HTML
<form accept-charset="utf-8" method="post" id="save_clinic" action="#">
<p>
<b>Findings</b>
<ol id='mf'></ol>
<input type="text" hold="mf" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<p>
<b>Medical Procedures:</b>
<ol id=mp></ol>
<input type="text" hold="mp" class="add_to_list" value="" name="">
<!--the input hv no name cause i dont want it to be submitted, this is for adding only-->
</p>
<input type=submit>
</form>
Problem:
I want to prevent submit on keypress ENTER and only allow submit on submit button click,
but my current js prevent submit for both and if I remove
$('#save_clinic').submit(function(){return false;});
from js then the form auto submit when user is trying to populate the form.
Can some one please tell me what is the problem here?
example

The function is called preventDefault (no underscore, capital 'D'), not prevent_default. Give that a try and remove this line:
$('#save_clinic').submit(function(){return false;});

I think this should be outside:
$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
}
e.prevent_default(); // take this out from the if
$('#save_clinic').submit(function(){return false;});
});

$('.add_to_list').live('keydown',function (e){
if(e.keyCode == '13'){
var holder=$(this).attr('hold'),
val=$(this).val();
if(holder == 'mf' ||holder == 'mp' ||holder == 'orders'){
var v='#'+holder;
h='<li class="entery deletable"><input type="hidden" name="'+holder+'[]" value="'+val+'">'+val+'</li>';
$(v).append(h);
$(this).val('');
}
//return false;
e.preventDefault();
AND
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
both works fine now.. thanks all

Related

empty check for multiple form in a page separately

I have two forms (consist with input,textarea,checkbox) in a page. I want check emptiness of these forms separately on click seperate button.
I use the following script. But it shows empty message if any of these form input is empty.
$('#submit').click(function(e) {
var empty = false;
$('input, textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
alert("empty");
e.preventDefault();
}
else {
document.getElementById("contact").submit();
}
})()
Never assign stuff to submit buttons
Do not submit a form from a submit button if you have chosen to use preventDefault if something wrong. It could submit the form twice
$(function() {
// on the submit event NOT the button click
$('form').on("submit", function(e) { // any form - use .formClass if necessary to specific forms
var empty = false;
$("input, textarea", this).each(function() { // this form's inputs incl submit
if ($.trim($(this).val()) == "") { // trim it too
console.log(this.name,"empty")
empty = true;
return false; // no need to continue
}
});
if (empty) {
alert(this.id + " is empty"); // or set a class on the div
e.preventDefault(); // cancel submission
}
});
});
div {
border: 1px solid black;
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input type="text" value="" name="field1" /><br/>
<textarea name="field2"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
<hr/>
<form id="form2">
<div>
<input type="text" value="" name="field3" /><br/>
<textarea name="field4"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
You could also add required to the fields
You need to restrain the handler to the form containing the clicked button:
$('#submit').click(function(e) {
var form = $(this).parents('form:first');
var empty = false;
$('input, textarea', form).each(function() {
// the rest is the same
I'd also like to point out that you cannot have the same ID on multiple controls, so
$('#submit')
should always return exactly one button. You should do something like this, where you distinguish the buttons by class instead:
<input type="submit" id="submitA" class="submitButton">
<input type="submit" id="submitB" class="submitButton">
and select with
$('.submitButton')
you know you can also use jquery to reset the form like so
form.resetForm();

Enter key doesn't activate button

I have a form with one field that the user needs to type into, and a button underneath that when clicked, does some jQuery and hides the login-form. But when I hit enter after typing something in, the page refreshes...
There's part of me that thinks it doesn't need to be an <input> or a <form>
I don't actually need to post anything. I have tried changing the input to a <button> which completely ruins my styling and still doesn't work. What's the best way of getting round this?
<div class="login-page">
<div class="form">
<form class="login-form" method="POST">
<!-- user inputs -->
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<!-- your submit button -->
<input class="login" type="button" id="submit" value="login">
</div>
True, Adam. If the form does not contain the type submit button, a keypress event has to be added manually. Otherwise Enter will act as the Accept Button on the form.
You need to attach keypress event to the form or at least the field. For convenience, you also need to combine the callback functions into one.
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
// submit the form.
}
});
$('#username').on('keypress', function(event){
var code = event.keyCode || event.which;
if(code == 13){
console.log('Submitting form');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="login-form" method="POST">
<p class="phc">PHC:</p><input type="text" id="username" placeholder="Enter Your PHC Here" />
<input class="login" type="button" id="submit" value="login">
</form>
If the enter key is pressed when focused to an input field inside a form that has a submit button, the default browser behaviour is to fire a submit event on that form. You can prevent this happening by either:
return false;
or
e.preventDefault();
Full code:
$('.login-form').on('submit', function() {
return false;
});
Fiddle: https://jsfiddle.net/nc1e2gm6/
Bear in mind that if you go down the route of using e.preventDefault(); instead or return false;, you need to pass the e variable from the function call, like:
$('.login-form').on('submit', function(e) { ...
Don't think i explained it very well but i have fixed it, the enter key now activates the submit button rather than refresh the page.
$("form").submit(function() { return false; });
$(document).ready(function(){
$('#username').keypress(function(e){
if(e.keyCode==13)
$('#submit').click();
});
});

Combine several events

I have a text field and a button. Either when the button is clicked or enter is hit, a function should be executed.
My approach works is intended. However, is it possible to combine those 2 functions (click and keypress), so that I only have 1?
$("button").click(function() {
getInput();
});
$("#name").keypress(function(e) {
if (e.which == 13) {
getInput();
}
});
function getInput() {
alert($("#name").val())
}
So I need to just append those events.
Here is a fiddle.
You can listen for multiple events using .on('listOfEvents')
Than you just need some additional rules to check when you need to run function.
$("button, #name").on('click keypress', function(e) {
if ($(e.currentTarget).attr('id') == 'submit' || e.which == 13) {
getInput();
}
});
function getInput() {
alert($("#name").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<button id="submit">
OK
</button>
function getInput(){
return $(".result").text($("input").val());
}
$("form").on("submit", (ev)=>{
ev.preventDefault();
// handle submission
getInput();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<input type="text" />
<button>ok</button>
</form>
<div class="result"></div>
you can wrap your input and button in a form and listen for a submit event on that form. Forms can be submitted by pressing enter in an input inside of them or clicking a button that is enclosed
HTML
<form action="">
<input type="text" />
<button>ok</button>
</form>
Javascript
$("form").on("submit", (ev)=>{
ev.preventDefault();
// handle submission
getInput();
})
#eltonkamami answer is one idea and my idea is to provide same class for both input field and button like this :
(But, this will trigger whenever input field is changed)
$(".same").bind("click keypress", function() {
getInput();
});
function getInput() {
console.log($("#name").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" class="same" />
<button id="submit" class="same">
OK
</button>
Hope it helps :)
We can differentiate a click and keypress by e.key or e.type parameters
Try this,
var getInput = function(e) {
if((e.which & e.which==13) || !e.key)
//e.key is a parameter for keypress event and not for click
alert($("#name").val())
}
$("button").click(getInput);
$("#name").keypress(getInput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="name" class="same" />
<button id="submit" class="same">
Click
</button>
$("button,#name").on("click keypress",function(e) {
//alert($(e.currentTarget).html());
if (e.which == 13) {
getInput();
}else if(event.type == 'click'){
getInput();
}
});
function getInput() {
alert($("#name").val())
}

How to prevent submitting search form when search field is empty?

Here the code below disables search button when search box is empty. When input type for search button is set to submit then neither submit nor the enter key from keyboard submits empty form but when I change input type to button and put the cursor inside input field and press enter button even empty form is posted causing reloading of page. How to prevent submitting search form on pressing enter when search field is empty?
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
<script>
$(document).ready(function(){
$('.Button').attr('disabled',true);
$('.search').keyup(function(){
if($(this).val().length !=0)
$('.Button').attr('disabled', false);
else
$('.Button').attr('disabled',true);
})
});
</script>
Add a event listener for the form submission
$('form').submit(function(e){
// check logic here
if ($('.search').val().length < 1)
e.preventDefault()
});
where e.preventDefault will avoid the form being submitted if no value
otherwise the form will submitted normally
here is your code with some modification:
JsFiddle Demo
$(document).ready(function(){
// By default submit is disabled
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
if($(this).val().length !=0 ) {
$('.Button').prop('disabled', false);
} else {
$( ".search").focus();
$('.Button').prop('disabled', true);
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
JsFiddle Demo
You can try like this
$('form').submit(function(e){
if ($('.search').val().length<=0)
return false;
});
you should use prop instead of attr if you want to change disabled
$(function() {
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
$('.Button').prop('disabled', !$(this).val());
});
});

How to submit a form when a checkbox is checked?

I want to submit a form only when a check box is checked, or display "Please check the check box", is there any way to do that? Can any one guide me ?
thanks
<form name="myForm" action="mailsent.php" method="post">
<input type="checkbox" class="chk_row" name="chk1[]"" value=" '.$rows["id"].'"/>
<input type="submit" value="" style="margin:7px 26px -27px 1424px;background-image: url(/image/exporttt.png);background-repeat: no-repeat;cursor:pointer;" >
</form>
Edited code:
<form name="myForm" action="mailsent.php" method="post">
<input type="checkbox" class="chk_row" id="chk1" name="chk1[]"" value=" '.$rows["id"].'"/>
<input type="submit" value="" style="margin:7px 26px -27px 1424px;background-image: url(/image/exporttt.png);background-repeat: no-repeat;cursor:pointer;" >
</form>
<script>
$('form').submit(function(){
if(!$('#chk1').is(':checked')){
alert("Please Check ");
return false;
}
});
</script>
Using JQuery
You should give your checkbox unique ID
$('form').submit(function(){
var flag=0;
$('.chk_row').each(function(){
if(($(this).is(':checked'))){
flag=1
return false;
}
});
if(flag==0){
alert("Please Check Checkbox");
return false
}
});
Your your_checkboxId is what you give id in your input chekcbox
eg.
<input type="checkbox" id="your_checkboxId" name="chk_name" value="some" / >
You can validate using jquery, give your submit button with id 'submit', and then use this code
$('#submit').click(function(e){
e.preventDefault();
if( $("[name='chk1[]']").is( ':checked')){
return true;
} else {
// your custom code here
return false;
}
})
try this
$("#submit").click(function(e)
{
if($("#check").is(':checked'))
{
$("#form").prop("action","mailsent.php");
}else
{
e.preventDefault();
}
});
And you need not specify the action in form tag. #form is id of form, #check is id of checkbox.
assuming there is only one checkbox here, and I am selecting it using the class name. You may modify the selector as per the implementation to pick the desired one.
$(document).ready(function(){
$('.chk_row').change(function(e){
if($(this).attr('checked') === 'checked')
{
$('form[name="myForm"]').submit();
}
});
});

Categories

Resources