i am currently working on a HTML Form (building it with the pug view engine), that I try to work with in an ajax request after fill-out.
When pressing Enter after editing my input-element, it seems to submit the form (post request i suppose?). I would like to the enter-press event to (just like my button) fire a jquery function instead.
The form is build as following:
form(class="form" action="")
div(class="form-group")
label(for="testid") Tickersymbol
input(name="symbol", type="text", class="form-control", id="testid", placeholder="Please enter the symbol")
div(class = "form-group")
button(class="btn btn-primary" id="getdata" type="button") Get Info
Current JQuery Code:
// This does not work
$("#inputStocksymbol").trigger('click', function (){
console.log("Enter event should have happened.")
})
// This does work
$("#getquote").click( function () {
console.log("Button has been pressed")
})
Are there any suggestions on how this would be possible?
Thanks!
The Return keypress within an input of a form will, by default, submit that form. Therefore, if you want to run some logic when this occurs hook to the submit event:
$("form.form").on('submit', function(e) {
e.preventDefault()
// run your code here
console.log("Button has been pressed");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" action="">
<div class="form-group">
<label for="testid">Tickersymbol</label>
<input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
<div class="form-group">
<button class="btn btn-primary" id="getdata" type="button">Get data</button>
</div>
</div>
</form>
Alternatively, if you just want to run some code when Return is pressed within the input, but do not allow the keypress to submit the form, you can hook a keypress event handler directly to the input, making sure to call stopPropagation():
$("#testid").on('keypress', e => {
if (e.keyCode === 13) {
e.preventDefault();
e.stopPropagation();
// run your code here
console.log("Return has been pressed");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" action="">
<div class="form-group">
<label for="testid">Tickersymbol</label>
<input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
<div class="form-group">
<button class="btn btn-primary" id="getdata" type="button">Get data</button>
</div>
</div>
</form>
Related
Currently I am trying to make my input field required.
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit">Continue</button> </center>
</form>
When I have the above portion it works, however I need it to work whenever I have my button containing a onlick event. <button id="process2" type="submit" onclick="move()">Continue</button> how can I go about doing this?
The issue is currently - The onclick request will fire, and it'll prompt the required option, however the onclick request should not fire unless the required option is populated.
Instead of the onclick , you should listen for the form's submit, and call move() inside it
document.querySelector('form').addEventListener('submit', event => {
event.preventDefault();
console.log('submitted');
move();
});
function move() {
console.log('moving ..');
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<button id="process2" type="submit">Continue</button>
</form>
Or you can just simply fire the move function but wrap your deserted effect inside if statement that will check if input is empty or not...
function move() {
element = document.getElementById("username").value;
if (element === "") {
console.log("input wasnt populated do something");
}
}
<form name="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button id="process2" type="submit" onclick="move()">Continue</button> </center>
</form>
Using jquery you can listen the submit event on form like then call move function to redirect to other page or whatever logic you want
$(document).on('submit','form',function(){
event.preventDefault();
// call move function here , move();
});
I would like to make my function available for user if they click on the button but if they press enter as well. Here is example:
$('#searchBtn').on('click', function searchUser(){
$.ajax({
type: 'POST',
url: 'Components/Application.cfc?method=findUser',
data: {'searchFldVal':searchFldVal},
dataType: 'json'
}).done(function(obj){
return true;
}else{
return false;
}
});
return false;
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
});
}
});
<form name="searchForm" id="searchForm" action="#" method="POST" onsubmit="searchUser()">
<div>
<input type="text" name="searchFld" id="searchFld" size="24" maxlength="24" value="" title="Maximum size of the field is 24 characters." placeholder="Example: John, Miller" />
</div>
<div>
<input type="button" name="searchBtn" id="searchBtn" value="Search"/>
</div>
</form>
Code above works fine if I click on button but if I enter few letters and press enter my page will reload. This file is saved as .cfm file. I would like to run searchUser() function on both onClick and onKeypress. If anyone knows how this can be achieved please let me know.
Since you're using jQuery, do not use inline event handlers. Define the function and call it when the form is being submitted as below:
function searchUser(e) {
e.preventDefault();
alert ("Do your ajax here instead of alert...");
}
$("#searchForm").on("submit", searchUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="searchForm" id="searchForm" action="#" method="POST">
<div>
<input type="text" name="searchFld" id="searchFld" size="24" maxlength="24" value="" title="Maximum size of the field is 24 characters." placeholder="Example: John, Miller" />
</div>
<div>
<input type="submit" name="searchBtn" id="searchBtn" value="Search"/>
</div>
</form>
Note:
removed inline event handler from the form
changed button type to submit.
If you are using AJAX to communicate with your server, you might want to leave the method, action, and submit callback off of the form entirely. This is what will cause the default submit behavior of the page reload. Instead, attach a listener to the search field itself, that listens for the enter key press.
$('#searchBtn').on('click', searchUser);
$('#searchFld').on('keypress', function(e){
e.preventDefault();
if(e.code == 'Enter'){
searchUser();
}
});
function searchUser(){
// search for the user
}
I have a button submit inside a form and just a normal button outside of it. I want to validate a form:
function myButtonHandler(evt) {
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
}
This doesn't show the standard error tips inside of input elements when they're invalid when I click on a button -- ones shown by a browser when I click the submit button. How can I get these validation message to pop up when I click on my normal button when the form is invalid?
<form id="my_form">
<input type="text" placeholder="Name" required="true"/>
<input type="submit" id="submit" value="go" />
</form>
No jquery.
You'll need to add the code you've shown to a function that is set up as the click event callback for the normal button:
var myForm = document.querySelector("form"); // reference to form
var btn = document.querySelector("[type='button']"); // reference to normal button
// Set up click event handling function for normal button
btn.addEventListener("click", function(){
if (myForm.checkValidity()) {
alert("yes");
} else {
alert("no");
}
});
<form>
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="button">Check Validity</button>
If you just want to show the normal browser's validation errors, you can make the second button also a submit button. It's OK for the button to be outside of the form as long as you tie it back to the form with the form attribute.
<form id="theForm">
<input type="text" required>
<button type="submit">submit</button>
</form>
<button type="submit" form="theForm">Check Validity</button>
I am creating a comment functionality and below are my code so far.
html
<form action="http://website.com/transaction_items/add_comment" class="" id="form-comment" role="form" method="post" accept-charset="utf-8">
<input type="hidden" name="checklists_item_id" value="6" style="display:none;">
<input type="hidden" name="user_id" value="1" style="display:none;">
<div class="input-group col-xs-12">
<input type="text" name="comment" value="" class="form-control" id="comment-input" placeholder="Enter your comments..">
<span class="input-group-btn">
<button class="btn btn-default" id="doc-comment" type="button">Post</button>
</span>
</div>
</form>
jQuery
This function is called when document is ready.
function comment () {
$('#doc-comment').click(function (e) {
var form_id = '#' + $(this).parents('form').attr('id');
// submit data from the form
submit.send(form_id);
});
}
The problem:
Using the button <button class="btn btn-default" id="doc-comment" type="button">Post</button> to submit data work fine, but
if I use enter in the keyboard, submit.send(form_id); will not do its function, instead the default form submission will execute.
How can I use ajax if use enter in the keyboard to submit form data?
nutshell
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// do your ajax stuff here
});
you can then toss the onclick button listener.. as this will handle the button submit as well
There are more ways to submit a form then simply pressing the submit button.
You need to:
Use the forms submit method
Keep the form from doing the full submit.
-
// This will catch the *enter* as well as the submit button
$("#form-comment").on('submit', function(evt) {
evt.preventDefault();
// You can then submit the form via ajax and update things as needed.
});
IF you are going to use a button you should at least do a
<button type="button">...</button>
which behaves differently.
$("#form-comment").keyup(function (e) { // On pressing enter
if (e.keyCode == 13) {
// put your ajax code here
}
});
You may have to disable the default Enter event for the form submit button as well depending on your browser.
So in the Jquery Button click function make sure you have something like
event.preventDefault();
My website has a simple form that is linked with MailChimp. The problem is that the form's submit button has conflicting interests, specifically, there's javascript email-field validation code that
is requiring the button to have type="submit" written in the button code. But if I include type=submit, it prevents my form from submitting to MailChimp.
Here is the button code in 2 forms. The first is the form which allows javascript error validation to work but submission to MailChimp to NOT work (notice the type)
<button class='buttonmain' type="submit" >Submit Form</button>
The second form does not have type="submit" and so js validation won't work, but it will submit to MailChimp:
<button class='buttonmain'>Submit Form</button>
Here's the full form
<form id="form-signup_v1"
name="form-signup_v1"
method="POST"
action="http://mysite.us10.list-manage.com/subscribe/post"
>
<!-- MailChimp Code -->
<input type="hidden" name="u" value="g02362223cdaf329adf5">
<input type="hidden" name="id" value="32da65235dba0">
<div class="errorstyle">
<div class="field">
<div class="ui left labeled input">
<input id="MERGE0"
name="MERGE0"
placeholder="My Email Address"
type="text"
data-validation="[EMAIL]">
<div class="ui corner label">
<i class="asterisk icon">*</i>
</div>
</div>
</div>
</div>
<button class='buttonmain' type="submit" >Submit</button>
</form>
and here's the script for validating the e-mail field.
Notice how it calls on "submit".
<script>
$('#form-signup_v1').validate({
submit: {
settings: {
inputContainer: '.field'
},
callback: {
onBeforeSubmit: function (node) {
myBeforeSubmitFunction(':D', ':)', node);
},
onSubmit: function (node) {
console.log('#' + node.id + ' has a submit override.');
//node.submit();
}
}
},
debug: true
});
function myBeforeSubmitFunction(a, b, node) {
console.log(a, b);
$(node).find('input:not([type="submit"]), select, textarea').attr('readonly', 'true');
$(node).append('<div class="ui active loader"></div>');
}
$('#prefill-signup_v1').on('click', function () {
var form = $(this).closest('form');
form.find('#signup_v1-name').val('John Doe');
form.find('#signup_v1-username').val('RocketJoe');
form.find('#signup_v1-password').val('test123');
form.find('#signup_v1-password-confirm').val('test123');
form.find('#signup_v1-email').val('test#test.test');
form.find('#signup_v1-email-confirm').val('test#test.test');
});
</script>
How do I combine the 2 button code forms I posted at the beginning, so that the form IS validated with js and also submits to MC?
Thanks so much!
I solved it myself doing the following:
Changing the script to include:
function myBeforeSubmitFunction(a, b, node) {
document.getElementById("form-signup_v1").submit();