search form doesn't submits - javascript

I have this search form:
JSFIDDLE
and it doesn't submits. When I click to enter or search icon. why?
<form action="/search.php" method="get">
<fieldset>
<ul class="toolbar clearfix">
<li><button type="submit" id="btn-search"><span class="fa fa-search" style="color:gray;"></span></button></li>
<li><input type="search" id="search" placeholder="" name="s"></li>
</ul>
</fieldset>
</form>
$(document).ready(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
$('#search').fadeIn().focus();
});
});

Because you are preventing form submit with e.preventDefault()
and not submitting form with any other methods.
You can submit your form using ajax like this:
$('#btn-search').on('click', function(e) {
e.preventDefault();
if( $('#search').val() ){
$.ajax({
url : 'submit.php',
data : { 'input': $('#search').val() },
success : function( response ) {
alert( response );
}
});
}
$('#search').animate({
width: 'toggle',
}).focus();
});
and write submit functions in submit.php
Inside submit.php you can write what you need to do with user input. Something like this:
<?php
echo "You have entered: " . $_GET['input'];
?>
Hope this helps..

Related

jquery submit form and stay on same page not working

The code below is supposed to submit the form and stay on the current page. It does submit the form, but it doesn't stay on the same page as it redirects to the form processing page. I have tried using event.preventDefault(); and return false; but neither are stopping the redirect. I tried them one at a time and then later added both at the same time and at different locations in the function, but the redirect still happens.
function submitForm() {
var $subForm = $('#signupForm')[0] ;
if (!$subForm.checkValidity()) {
$subForm.find(':submit').click() ;
return ;
}
$subForm.submit(function(event){
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
return false ; // not working here
}
My form is defined as:
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
....
<button type="button" onclick='submitForm();' id="ccInfoButton" style="" class="btn btn-primary buttonSignup" disabled >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
The issue is because of where you are trying to handle the submit event. The code below achieves the goal of submitting the form and staying on the same page. You can see it work with the code snippet below.
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // not working here
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
<!DOCTYPE html>
<html>
<body>
<form method="POST" id="signupForm" action="submitSignup.php" enctype="multipart/form-data" validate>
<input type="text" name="eee" required/>
<input type="submit" style="display: none;" required/>
<button type="button" onclick='submitForm();' id="ccInfoButton" class="btn btn-primary buttonSignup" >CREATE ACCOUNT NOW<i class="iconRequired icon-chevron-right"></i></button>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
</script>
</html>
#DankyiAnnoKwaku - kudos to Dankyi for getting me on the right track, but his solution didn't work for me, I had to adapt it a bit more:
<script type="text/javascript">
function submitForm() {
console.log("SUBMIT BUTTON CLICKED");
var subForm = $('#signupForm')[0] ;
if (!subForm.checkValidity()) {
console.log("INVALID FORM SUBMISSION");
$('#signupForm').find(':submit').click() ;
return ;
}
$("#signupForm").submit();
}
// Had to wrap the `submit(function(event)` in the root `$(document).ready ....`
$(document).ready(function(event) {
$("#signupForm").submit(function(event){
console.log("FORM SUBMITTED AND PAGE DOES NOT REDIRECT");
event.preventDefault(); // now working
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
console.log(response) ;
},'json');
return false; // not working here
});
}) ;
</script>

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

jQuery submit 'this' form

I'm trying to submit a form, once the user has accepted they want to continue via the jQuery UI Dialog.
<form method="POST" action="url" onsubmit="return APP.dom.confirm(this);">
<button type="submit" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
</form>
My APP.dom.confirm method looks like:
confirm: function(form) {
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(form).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
return false;
}
This works, however when they click confirm I'd like the form to get submitted.
$(form).submit();
That doesn't work. Logging it out I get the above HTML back. I've tried variations of, to no avail:
$(form).clostest('form').submit();
How do I submit this?
Change
$(form).submit();
to
form.submit();
When you call submit on a jQuery object, it calls your submit handler again. Calling it directly on the DOM element does not.
Example (interestingly, Stack Snippets won't let me submit a form, not even with target="_blank"):
var nesting = 0;
function submitHandler(form) {
var which = $(form).find("input[type=radio]:checked").val();
++nesting;
if (nesting > 5) {
snippet.log("Nested to 5, gave up");
} else {
if (which === "jQuery") {
snippet.log("Calling via jQuery, nesting = " + nesting);
$(form).submit();
} else {
snippet.log("Calling via DOM, nesting = " + nesting);
form.submit();
}
}
--nesting;
return false;
}
<form id="the-form"
onsubmit="return submitHandler(this);"
action="http://www.google.com/search"
target="_blank"
method="GET">
<input type="text" name="q" value="kittens">
<div>
<label>
<input type="radio" name="opts" value="jQuery"> Submit with jQuery
</label>
</div>
<div>
<label>
<input type="radio" name="opts" value="DOM"> Submit with DOM
</label>
</div>
<button>Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
confirm: function() {
var that = this;
$("#dialog-confirm").dialog({
modal: true,
buttons: {
"Confirm": function() {
$(that).submit();
},
"Cancel": function() {
$(this).dialog("close" );
}
}
});
}
Replace onsubmit="return APP.dom.confirm(this);" by
$('form').on('submit', APP.dom.confirm);

Submit form via Enter key and Submit button both

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.
$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});
look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser
Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

Categories

Resources