I open my dialog with a button then I place my cursor in a input field and presses enter my dialog closes and this line is inserted to the address bar:
jQuery:
$('#dialog').load("form-incident.php").dialog({
title: "Add Incident",
autoOpen: false,
resizable: false,
width: 800,
modal:true,
position: ['center', 'top+50'],
buttons: {
Add: function(){
$.ajax({
url : 'save.php',
type : 'POST',
data : $('form').serialize(),
context: $(this),
success: function (result) {
if (result === "true") {
alert('Incident has been added successfully');
} else {
alert('ERROR: Cannot insert data to MySQL table');
}
window.location.reload();
$(this).dialog( "close" );
},
error : function(){
alert('ERROR: Check database connection');
}
});
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
form-incident.php:
<form>
Name: <input type="text" name="name" id="name"><br><br>
Project:
<select name="project" id="project">
<option value="test">Test</option>
</select><br><br>
Incident:<br> <textarea name="incident" id="incident" style="resize:none; width: 100%;" rows="14" cols="94"></textarea>
</form>
How can I fix the problem so the dialog box does not close but still reacts to enter if there was some suggestions from earlier where the form was filled out?
Okay, I forgot that implicit submission will still happen if there is only a single input element in the form, even if there isn't a submit button.
So, it looks like the problem is happening from the form being submitted. But in that case, calling preventDefault() on the submit even will fix it.
I threw together a fiddle with your code snippets from above, and was able to reproduce the problem. Once I put in the preventDefault(), it stopped happening. Please check it out, and see how it differs from your live code.
https://jsfiddle.net/elezar/u0sfx22p/2/
Related
I am trying to use a jQuery-UI dialog to make a "Change Password" form that lets the user of my site submit a new password for his/her account.
Here is the function that creates and opens the dialog:
function MakeChangePasswordDialog(userId) {
var form;
var dialog = $('#dialog-form').dialog({
autoOpen: false,
height: 400,
width: 350,
modal: false,
buttons: {
'OK': ChangePassword(userId, $('#password').val(), $('#confirm_password').val()),
'Cancel': function() {
dialog.dialog('close');
}
},
close: function() {
form.reset();
allFields.removeClass('ui-state-error');
}
});
// "Change Password" dialog form
form = dialog.find('form').on('submit', function (event) {
event.preventDefault();
ChangePassword(userId, $('#password').val(), $('#confirm_password').val());
});
dialog.dialog('open');
}
Here is the function that changes the password:
function ChangePassword (userId, newPassword, confirmNewPassword) {
$.ajax({
url: 'http://path/to/my/ajax/endpoint',
type: 'post',
data: { userId: userId, newPassword: newPassword, confirmNewPassword: confirmNewPassword },
success: function (result) {
if (result.substring(0, 1) == "1") {
alert('Password changed.');
} else {
alert('Password not changed.');
}
}, error: function(err){
console.log('Error changing password: ' + err);
}
});
}
The dialog displays just fine, but when I click the "OK" button, there is a long pause. After about ten seconds, the following error appears in the Google Chrome developer console:
Uncaught RangeError: Maximum call stack size exceeded
at buildParams (jquery.js?cdv=151:8426)
at buildParams (jquery.js?cdv=151:8417)
at buildParams (jquery.js?cdv=151:8411)
... (previous line repeats 7 times)
After getting this error, I inspected the source code using the debugger, and I saw that the "ChangePassword" function got called once immediately after the dialog was opened. I decided that this was erroneous behavior, so I modified the "MakeChangePasswordDialog" function so that the 'OK' button did not have any parameters passed to it. The modified function looked like the following:
function MakeChangePasswordDialog(userId) {
var form;
var dialog = $('#dialog-form').dialog({
autoOpen: false,
height: 400,
width: 350,
modal: false,
buttons: {
'OK': ChangePassword,
'Cancel': function() {
dialog.dialog('close');
}
},
close: function() {
form.reset();
allFields.removeClass('ui-state-error');
}
});
// "Change Password" dialog form
form = dialog.find('form').on('submit', function (event) {
event.preventDefault();
ChangePassword(userId, $('#password').val(),
$('#confirm_password').val());
});
dialog.dialog('open');
}
After doing this, I noticed that there was no long pause after I triggered the function, and no error was generated. The dialog displayed just fine, and I was able to enter a new password and confirmation password. However, after I clicked on the "OK" button, I received a similar error. Here it is:
Uncaught RangeError: Maximum call stack size exceeded
at buildParams (jquery.js?cdv=151:1)
at buildParams (jquery.js?cdv=151:8411)
... (the previous line repeats 8 times)
Also, after inspecting the "ChangePassword" function in the debugger, I noticed something peculiar. This is that, instead of passing the "userId," "$('#password')," and "$('#confirm_password')" variables to the function, the jQuery-UI dialog passed the JavaScript event that was generated when the user clicked the button. This caused the "userId" field to be wrong, and the other two fields to be undefined.
Does anyone have any advice for me?
UPDATE
I also have another problem: If I click the "Close" button, I get the following error:
TypeError: Cannot read property 'reset' of undefined
After inspecting the debugger, I found that the "form" element had a length of zero in the "close" function. This means that the jQuery selector that returns this element is returning nothing. Why would this be? Thanks so much in advance, and I can make this a new question if necessary. I just thought it would be more convenient to post it in my existing question, since there are so many questions that get asked on StackOverflow.
I am using jQuery version 3.2.1, jQuery-UI version 1.12.1, and Chrome version 66.
UPDATE
Thank you so much everyone. After following your suggestions, it works! The final version of my "MakeChangePasswordDialog" function is this:
var dialog;
function MakeChangePasswordDialog (userId) {
// "Change Password" dialog
dialog = $('#dialog-form').dialog({
autoOpen: false,
height: 400,
width: 350,
modal: false,
buttons: {
'OK': function () { ChangePassword (userId, $('#password').val(), $('#confirm_password').val()) },
'Cancel': function () {
dialog .dialog('close');
}
}
});
dialog .dialog('open');
}
Also, for completeness's sake, here is the div that contains the form:
<div id="dialog-form" title="Change Password" style="display:none;">
<form id="dialog-form-form">
<fieldset>
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all">
<label for="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" id="confirm_password" value="" 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>
First, thanks for taking the time to look at my question. Really. This is my question. I'm making a fancybox search page for a website I'm making. Getting the search results in fancybox all work fine.
But if the visitor just clicks on search it returns every item on the site. What I would like is make the form so, that the visitor has to at least enter 3 characters before the search does a search. If the visitor doesn't enter 3 or more characters fancybox will give an alert saying please enter at least 3 or more characters.
I've looked around stackoverflow and found this code:
$( document ).ready(function() {
input_value = $.trim($('#searchkey').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
}else{
//perform your code if it should not be empty.
}
});
So I placed my code inside the correct place, like so:
$( document ).ready(function() {
input_value = $.trim($('#str').val());
if(input_value == ''){
alert('Enter some value');
return false; //Does not submit the form
} else {
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
jQuery.fancybox({
width: 600,
height: 600,
openEffect: 'fade',
closeEffect: 'fade',
href: 'search-post-results.php',
type: "ajax",
ajax: {
type: "POST",
data: {
value: $('#str').val()
}
}
});
});
});
}
});
I'm not getting any syntax errors, but if I reload the page it gives me the correct alert. But thats if there are no characters entered. So I've changed this line:
if(input_value == ''){
to:
if(input_value == '2'){
Figuring that I should set a value. But that does nothing. Does anyone have a similar script/snippet that does the same? Or know why this isn't working?
Here is the HTML (nothing special there):
<form id="search">
<table>
<tr>
<td>
<input type="text" name="s" id="str" placeholder="Search...">
</td>
<td>
<button class="btn form-button btn-default">
<i class="fa fa-search"></i>
</button>
</td>
</tr>
</table>
</form>
Thans again for your time.
Use length property.
if( input_value.length < 3 ){
// error message if characters are less than 3
} else {
// continue the search
}
Try this ,
Also Please change validation position because if you reload then always alert will show . So you can validate after submit action.
$(function() {
$('#search').on('submit', function(e) {
e.preventDefault();
if(input_value.length < 3 ){
// Show your alert message.
}else{
// Here you start Ajax Request.
}
});
});
I want use loader.gif to display as processing before confirmation message shown when hit on submit button for contact form
loader.gif must be shown next to submit button
Can anyone plz help me to put code, as I don't know to which code to insert????
My fiddle link: http://jsfiddle.net/jPp64/
HTML
<div class="form-group">
<label for="exampleInputArea">Area</label>
<select style="color:#000 !important" class="form-control" id="exampleInputArea" placeholder="Select Month" name="exampleInputArea">
<option value="" >--Select Area--</option>
<option value="Area1">Area1</option>
<option value="Area2">Area2</option>
<option value="Area3">Area3</option>
</select>
<div style="color:red;" id="areaerror"></div>
</div>
<div class="form-group last">
<button class="btn btn-lg btn-red mailbtn">Submit</button>
</div>
JS
$('.mailbtn').live('click',function(){
area = $('#exampleInputArea').val();
if (area.length == 0 || area == '') {
$('#exampleInputArea').val('')
$('#areaerror').text('Area is Required');
return false;
} else {
$('#areaerror').text('');
}
$.ajax({
type: "POST",
async : false,
url: "mail.php",
data: {area:area}
})
.done(function( msg ) {
$('.mail_middle').html('');
$('.mail_middle').html('We will call you to confirm your delivery address.<br/>Thank you.');
return false;
});
});
All you need to do is put an image next to the Submit button where you want it and set the CSS on it to display: none; to hide it. Then when you are inside your .live('click') event, the first line should show the image using $('#imgId').show(); with jQuery. Then just hide the image again when the ajax is complete.
Keep in mind that since you'll probably be using a gif, you need to make your ajax call asynchronous so change the async: false to true. If you don't do this, your animated gif will appear as a static image because synchronous calls will lock the browser.
You could have your GIF in a div (where you like) with style="display:none;"
When you're sending your ajax request, simply use a jQuery's show().
When the data is received, use hide().
Example:
[...]
$.ajax({
type: "POST",
async : false,
url: "mail.php",
data: {area:area}
})
success: function(){
$('#ID_YOURGIF').show();
},
.done(function( msg ) {
$('.mail_middle').html('');
$('.mail_middle').html('We will call you to confirm your delivery address.<br/>Thank you.');
return false;
});
$('#ID_YOURGIF').hide();
[...]
I'm using bootstrap typeahead and I'm wondering, how do I make it submit when clicking the enter button? In other words, if I typed "hello" into the typeahead input and pressed enter, how would I submit "hello"?
I've already made it so that the typeahead doesn't auto-select the first result.
This is my code:
<form method="POST" action="script.php">
<input name="typeahead_field" class="typeahead" data-provide="typeahead" autocomplete="off" type="text">
</form>
jQuery:
$('.typeahead').typeahead({
items: 10,
source: function (query, process) {
$.ajax({
url: 'typeahead.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
// code that returns each result
return html;
},
updater: function(data) {
// code that redirects the user if they click the selection
},
});
Please help!
Old question, but worth answering. Here is a possible solution:
$('.typeahead').on('keydown', function(e) {
if (e.keyCode == 13) {
var ta = $(this).data('typeahead');
var val = ta.$menu.find('.active').data('value');
if (!val)
$('#your-form').submit();
}
}
EDIT: First attempt was very naive :)
You need a submit button to enable submit on enter. You can hide the button with this CSS:
<input type="submit" style="position: absolute; left: -9999px">
(from https://stackoverflow.com/a/477699/759971)
works well, but doesn't highlight selection like mouse-over event does. Maybe this solution would work better as seems to encapsulate the gist of previous answer.
https://bwbecker.github.io/blog/2015/08/29/pain-with-twitter-typeahead-widget/
On a website I'm working on, when you click sign on, a jquery dialoge modal pops up, but you have to click on OK to submit the form, you can't just hit enter. I need it to be able to have enter work also. It seems like what I have should work, but it doesn't
I'm using jquery-1.3.2.js. I also have a php file with the following piece of code in it: `
<tr valign="top" align="right" style="height:40px"><td >
<div id="signin">
<table style="margin-top:4px;margin-right:4px;border-style:solid;border-width:1px">
<tr><td style="width:165px;">
<div><center>
<a title="Sign In" onclick="LoginDialogOpen()" href="javascript:void();">Sign In</a><b> | </b>
<a title="Create Account" href="CreateAccount.html">Create Account</a>
</center></div>
</td></tr>
</table>
</div>
</td></tr>
<div id="Signin_Dialog" >
<div id="bg">
<label><span>Email:</span></label>
<input type="text" name="email" id="email" class="dialog-input-text"/>
<br>
<label><span>Password:</span></label>
<input type="password" name="password" id="password" class="dialog-input-text"/>
<br>
<br>
<center><b><label id="login_error" style="color:red"><span> </span></label></center></b>
</div>
</div>
<script>
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
</script>`
i have a javascript file with the following function:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
$('#login_dialog').keypress(function(e) {
if (e.which == 13) {
$("body").addClass("curWait");
sql = "select client_id from users where email = '" + $("#email")[0].value + "' and login_password='" + $("#password")[0].value + "'";
$.get('BongoData.php', { task:"SQLResultToJSON", sql: sql}, ResultOfLoginAttempt, "json");
}
});
}
That is the code I have, I don't understand why it isn't working.
I also had it try $('#login_dialog').dialog('isOpen'); right after i opened it, but it always returned false oddly enough. Please help if you can.
I strongly recommend to consider all notes made by the others regarding raw client side SQL!
Regarding your actual question I propose the following:
Put a form in your login dialog like so:
<div id="login_dialog">
<form method="get" action="BongoData.php">
<input type="text" name="email" />
<input type="password" name="password" />
<input type="submit" />
</form>
</div>
Then in your script part where the dialog is initialized write something like:
$('#login_dialog').dialog({
autoOpen: false,
width: 310,
overlay: { opacity: 0.5, background: "black" },
modal: true,
buttons: {
"Ok": function() { $('#login_dialog form').submit(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
// hide the original submit button if javascript is active
$('#login_dialog form input[type=submit]').hide();
// register a submit handler to submit the form asynchronously
$('#login_dialog form').submit(function () {
// calling serialize() on a form transforms form inputs to a string suitable for $.get and $.post
$.get($(this).attr('action'), $(this).serialize(), ResultOfLoginAttempt, "json");
// prevent that the browser submits the form.
return false;
});
// and register a key listener to submit the form if the user presses enter on the password input field
$('#login_dialog form input[type=password]').onKeyDown(function (e) {
if (e.which == 13) {
// just trigger the submit handler
$('#login_dialog form).submit();
}
});
With these preparations you can simplify your javascript a lot:
function LoginDialogOpen(){
$('#login_dialog').dialog('open');
}
Some additional notes:
Don't use SQL in your javascript. Instead write a customized php file with prepared sql to verify login data. In this solution the login form degrades gracefully if no javascript is present as it is a standard html form which can be sent by the browser. You should also be aware of the fact, that some browser send forms (i.e. trigger the submit handler) on Enter without further requirements, but as it's browser specific you cannot rely on this if it's a must for your application. As a last action you should eventually check whether you need to close the dialog manually within your "ResultOfLoginAttempt" method.
Look at the Tamper Plugin for Fire Fox : Tamper Data 10.1.0
Genertate SQL on the client side is bad. You can hijack the http request.
I think you mean if (e.keyCode == 13) { rather than if (e.which == 13) {.
Also Ian Elliot is right. You should never have the actual sql as any part of your javascript or any part of your form. You can submit values to the server that will eventually be interpolated into your SQL*, but never the complete SQL.
*Once the values have been properly validated, sanitized, & optionally passed through another layer of abstraction (think MVC).