I have a search form which which takes an input and pass the data to a django view.
the form has a search button which on click opens a input box like shown in images given below:
Now when i enter something into the input and press enter, it just collapses the input box and no action occurs. It happens every time. I want it to call the function associated with form. I figured out that the problem is in the javascript but don't know how to fix it.
html:
<form class="navbar-form" role="search" method="POST" action="{% url 'search' %}">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search_box">
<span class="input-group-btn">
<button name="search" type="submit" class="search-btn"> <span class="glyphicon glyphicon-search"> <span class="sr-only">Search</span> </span> </button>
</span>
</div>
</form>
javascript:
e(function() {
function t() {
var t = e('.navbar-collapse form[role="search"].active');
t.find("input").val(""), t.removeClass("active")
}
e('header, .navbar-collapse form[role="search"] button[type="reset"]').on("click keyup", function(n) {
console.log(n.currentTarget), (27 == n.which && e('.navbar-collapse form[role="search"]').hasClass("active") || "reset" == e(n.currentTarget).attr("type")) && t()
}), e(document).on("click", '.navbar-collapse form[role="search"]:not(.active) button[type="submit"]', function(t) {
t.preventDefault();
var n = e(this).closest("form"),
i = n.find("input");
n.addClass("active"), i.focus()
}), e(document).on("click", '.navbar-collapse form[role="search"].active button[type="submit"]', function(n) {
n.preventDefault();
var i = e(this).closest("form"),
s = i.find("input");
e("#showSearchTerm").text(s.val()), t()
})
}
css:
.navbar-collapse form[role="search"] input {
font-size: 18pt;
opacity: 0;
display: none;
height: 48px;
position: relative;
z-index: 2;
float: left;
}
.navbar-collapse form[role="search"].active input {
display: table-cell;
opacity: 1;
z-index: 100;
border-radius: 0;
border: none;
line-height: 45px;
height: 75px;
font-size: 14px;
padding: 0px 25px;
width: 315px;
}
.navbar-collapse {float:right; padding:0px}
its because you didn't submit form
Try this to submit form..
Without AJAX
$('form#myForm').submit();
with performing AJAX
$('input#submitButton').click( function() {
$.post( 'some-url', $('form#myForm').serialize(), function(data) {
... do something with response from server
},
'json' // I expect a JSON response
);
});
$('input#submitButton').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
... do something with the data...
}
});
});
Hope this helps..
Letting you know the step by step procedure.
Set a .keyup event on the search input. $("[name='search_box']").keyup(function(e){ .... });
Check if the keycode of the pressed key is equal to 13 (enter key) if(e.keyCode==13){ ... }
If it is 13 then call the function associated with the form.
Related
I am attempting to use jQuery Validate's errorPlacement function to place an error message, but I cannot figure it out. Whenever I hit submit, the input slides down, instead of the error placing in the newsletterValidate div.
Does anyone see what I am doing wrong in my errorPlacement code?
$('#newsletterForm').validate({
//errorClass: 'invalid',
errorPlacement: function(error, element) {
//element.val(error[0].outerText);
//error.appendTo(element.next('div'));
error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
},
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#newsletterForm').serialize();
$.ajax({
url: 'http://localhost:8080/php/newsletterSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
alert(data);
} else {
$('#newsletterInput')[0].reset();
$('#newsletterSuccess').show();
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
#newsletterInput {
width: 70%;
border: none;
padding: 15px 10px;
outline: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
display: inline-block;
background: pink;
}
#newsletterSubmit {
width: 25%;
display: inline-block;
border: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
padding: 15px 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<div>
<form id="newsletterForm">
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</form>
</div>
<div id="newsletterValidate"></div>
error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
I'm not sure why you are using jQuery to traverse around inside the DOM when you already know the unique id. So just skip right to your target...
error.appendTo($('#newsletterValidate'));
Demo 1: jsfiddle.net/b2enbs0s/
However, now that it's working, you can see there's a different problem. The message is being repeated.
That's because you're trying to place the message outside of the form container...
<div>
<form id="newsletterForm">
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</form>
</div>
<!--// outside of the form //-->
<div id="newsletterValidate"></div>
In this case, the plugin creates the validation message but cannot find it again in order to properly toggle it.
The fix is to place the message element inside of the form container where the plugin can automatically find & toggle after it's created. The following structure visually renders identical to your original layout...
<form id="newsletterForm">
<div>
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</div>
<!--// inside of the form //-->
<div id="newsletterValidate"></div>
</form>
Final Working Demo: jsfiddle.net/b2enbs0s/1/
The following code is based jQuery Modal form just like https://jqueryui.com/dialog/#modal-form .
I hope to click a button to open a modal form, and select files in the modal form, then click "Upload" button to post data the server side.
But I find the data don't be posted when I click "Upload" button. Why ?
And more, what action is the code form = dialog.find("form").on("submit", function (event) {...} ? I think I can remove the code form = dialog.find("form").on("submit", function (event) {...}, right?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Dialog - Modal form</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
var dialog, form;
function mySubmit() {
var valid = true;
if (valid) {
dialog.dialog("close");
$("#MyUploadFile").submit();
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Upload": mySubmit,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
mySubmit();
});
$("#create-user").button().on("click", function () {
dialog.dialog("open");
});
});
</script>
</head>
<body>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form action="" method="post" enctype="multipart/form-data" id="MyUploadFile">
<input type="file" name="myupload" multiple="multiple" />
</form>
</div>
<button id="create-user">select files and upload</button>
</body>
</html>
Expanding on the example you made reference to and what I said in the comments, I do have a better example for you to consider.
HTML
<div id="dialog-form" title="File Upload">
<p class="validateTips">Select a file to upload.</p>
<form>
<fieldset>
<label for="name">File</label>
<input type="file" id="uploadFile" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<div id="users-contain" class="ui-widget">
<h1>Uploaded Files:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>File</th>
<th>Folder</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Archive.xls</td>
<td>/upload</td>
<td>02/28/2017</td>
</tr>
</tbody>
</table>
</div>
<button id="upload-file-button">Upload New File</button>
CSS
label,
input {
display: block;
}
input.text {
margin-bottom: 12px;
width: 95%;
padding: .4em;
}
fieldset {
padding: 0;
border: 0;
margin-top: 25px;
}
h1 {
font-size: 1.2em;
margin: .6em 0;
}
div#users-contain {
width: 350px;
margin: 20px 0;
}
div#users-contain table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
}
div#users-contain table td,
div#users-contain table th {
border: 1px solid #eee;
padding: .6em 10px;
text-align: left;
}
.ui-dialog .ui-state-error {
padding: .3em;
}
.validateTips {
border: 1px solid transparent;
padding: 0.3em;
}
JavaScript
$(function() {
var dialog, form;
function updateTips(t) {
$(".validateTips")
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
$(".validateTips").removeClass("ui-state-highlight", 1500);
}, 500);
}
function uploadFile() {
var valid = false;
var $input = $("#uploadFile");
if ($input[0].files.length === 0) {
updateTips("You must select a file.");
return valid;
}
var fileData = new FormData();
$.each($input[0].files, function(k, v) {
fileData.append(k, v);
});
// Barrowed from https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
$.ajax({
url: "./php/upload.php",
type: "POST",
data: fileData,
cache: false,
dataType: "JSON",
processData: false,
contentType: false,
success: function(results, textStatus, jqXHR) {
// 'results' will be a JSON object return from our form handler
// 'results.error' may contain error details, like: Path Not Found
if (typeof results.error === 'undefined') {
// At this point, we should have uploaded the file
// our form handler has return some response
// We can update a table to do something with the data
valid = true;
} else {
// Handle errors here
updateTips("Error: " + results.error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
updateTips("Error: " + textStatus);
// STOP LOADING SPINNER
}
});
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Upload": uploadFile,
Cancel: function() {
dialog.dialog("close");
}
},
close: function() {
form[0].reset();
}
});
form = dialog.find("form").on("submit", function(event) {
event.preventDefault();
uploadFile();
});
$("#upload-file-button").button().on("click", function() {
dialog.dialog("open");
});
});
As you can see, this is very similar to the original example in the way it works. It's not there through, since you have more work that has to be done server side.
Remember that jQuery is a framework for JavaScript, which is Client Side Scripting. To handle file uploads, your web server must be able to handle the HTTP POST data in some manner. This may be a CGI, ASP, ASP.NET, or PHP script.
I made a comment about https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax which is a very straight forward article about using AJAX to upload a file to a PHP Script. I advise you read through it and continue your research so that you can better understand this action. Since now that you're letting users upload content, you are making your web site and possible your whole server open to attack via a backdoor script.
This will set you on the right path but the journey does not end here.
I have a table that have checkboxes inside. after select it how to return a sum of values from table in modal before confirm the form? and how to render the ajax response from controller?
in my view
$("#envia-vendas").ajaxForm({
url: '../vendas/confirmar',
type: 'post',
success: function (data) {
$('#myModal').modal('show');
console.log(data);
},
in my controller
//dostuf
if($this->request->is('ajax')){
$sum = $sum;
$this->render('ajax/confirmado', 'ajax');
echo 'bal';
$this->set('text', 'test');
$this->set('_serialize', ['text']);
}
how to print the result in the view without reloading page?
What this fiddle does is grabs all of your inputs, then pops up a modal after the values and names have been injected for confirmation.
It should give you a good starting point. What this is setup to do is give you the confirmation screen without the need for additional server calls.
Just set your action to the route that you want to pass the information to for server interactions.
HTML
<form id="test-form" method="post" action="your/action/here">
<input type="text" name="test" value="" />
<input type="submit" name="submit-form" value="submit" />
</form>
<div class="modal">
<div class="form-info-wrapper">
</div>
<a class="confirm">Confirm Information</a>
</div>
CSS
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
background: #FFF;
}
JS
jQuery(document).ready(function ($){
$('body').on('click', 'input[type=submit]', function (e) {
e.preventDefault();
var data = $(this).parent('form').serializeArray();
$('.form-info-wrapper').empty();
for(_data in data)
{
$('.form-info-wrapper').append(data[_data].name + ': ' + data[_data].value);
}
$('.modal').fadeIn();
});
$('.confirm').click(function (e){
e.preventDefault();
$('#test-form').submit();
});
});
https://jsfiddle.net/ojaeacps/2/
I want to display a loading image after I submit a form. Here is my current code (I am using Bootstrap):
<form method="GET" action="/search/results" id="searchform">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Search" style="min-width: 300px;" required autofocus>
</div>
<button type="submit" class="btn btn-dark btn-md">Search</button>
</div>
<br>
<div class="form-group">
<h4 class="text-muted">Scoring Type</h4>
<label class="radio-inline">
<input type="radio" name="scoring" id="standard" value="standard" checked> Standard
</label>
<!-- other radio options -->
</div>
</form>
<br>
<div class="modal">
</div>
<style>
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url("{% static 'img/loading.gif' %}")
50% 50%
no-repeat;
}
body.loading {
overflow: hidden;
}
body.loading .modal {
display: block;
}
</style>
The form submits to a page called /search/results, but I want this page to be loaded with ajax. Once it is done loading, I want to fully replace the search webpage with the webpage that contains the results. While it is loading, I want $('body').addClass('loading'); to be applied, which will display the loading icon in the way I want (I do not want any changes in css, it works how I want it to). I have looked all over the place but I cannot seem to find a solution that works for me. Thanks.
To make sure the form wont submit as normal ones:
remove method="GET";
<form action="/search/results" id="searchform">
Js:
$("#searchform").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this );
var url = $form.attr( "action" );
//before send
$("body").addClass("loading");
/* Send the data using post */
var posting = $.post(url , $( "#searchform" ).serialize() );
/* Alerts the results */
posting.done(function( data ) {
//use data
$("body").removeClass("loading");
});
});
use the below procedure:
var data = $("#searchform").serialize();
$('#searchform').on('submit',function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "/search/results",
data: data,
dataType: "json",
success: function(data) {
//on success remove the image
},
error: function(){
alert('error handing here');
}
});
})
I have a form that if you click on the input field giving it focus the submit button displays.
However the issue I'm having is that when you try to click on the submit button it disappears as the focus has been removed from the input.
Here is my code:
<form method="post" id="subForm" class="clearfix">
<input id="fieldEmail" placeholder="email address" type="email"/>
<button type="submit"><i class="arrow"></i></button>
</form>
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
$(this).next().removeClass('visible');
});
And here is a JSFiddle
What is the best way to keep the toggling of class 'visible' but allow me to click the submit button?
It has to do with the order of events.
You can use mousedown to detect where the focus moves to because it triggers before the blur:
(function () {
var submit_focus = false;
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if (submit_focus) {
submit_focus = true;
} else {
$(this).next().removeClass('visible');
}
});
$('#submit').mousedown(function () {
submit_focus = true;
});
}());
http://jsfiddle.net/cnLon9k3/4/
I suggest to put a check inside the function which hides the button and see if the input field has some value (if yes, you wouldn´t want to hide the button, or?)
e.g:
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if($(this).val() === ""){
$(this).next().removeClass('visible');
}
});
We can have a check that on blur of textfield, the new focused element is button or not.
$('#fieldEmail').focus(function () {
$(this).next().addClass('visible');
}).blur(function () {
if(!event.relatedTarget||event.relatedTarget.type!='submit')
$(this).next().removeClass('visible');
});
form {
color:#333;
position: relative;
}
input {
padding:0 5px 5px;
text-align: center;
border:none;
text-transform: uppercase;
font-size:12px;
width:170px;
margin-left:15px;
float:left;
letter-spacing: 2px;
}
button {
display: none;
background: #ff0000;
border:none;
}
.arrow {
background:#ff0000;
width:15px;
height:15px;
display: block;
}
.visible {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="subForm" class="clearfix">
<input id="fieldEmail" placeholder="email address" type="email"/>
<button type="submit"><i class="arrow"></i></button>
</form>
I would suggest to capture each click event on document and if the target of that event is not submit button or email input then hide the submit button as below and remove the blur event from input
$(document).on('click',function(e){
if(e.target.type!="submit" && e.target.type !="email")
{
$('#fieldEmail').next().removeClass('visible')
}
});
DEMO HERE