jQuery UI Dialog Changes URL on Enter KeyPress - javascript

I'm trying to submit a form with AJAX, the form being content of jQuery UI Dialog.
I use the same code as in jQuery's documentation
but I modified the form so there is only one text input, so the form looks like this:
<form>
<fieldset>
<label for="answer"><strong>Your Answer : </strong></label>
<input type="text" name="answer" id="answer" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
When I click the OK (or Create User) Button, it works, i.e. submits the answer with AJAX, but I also want it to work when pressed Enter key.
now, when I type asd in input#answer and press enter, it makes the URL like this:
mysite.com/?answer=asd
I tried adding the function:
$('#answer').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed on answer input");
}
});
this time it alerts "enter pressed on answer input" and then converts the URL. Whereas, I don't want it to modify the URL, how can I delete that function? Where is it defined?
In short, I want the enter key to do only what I want it to do.
Thanks for any help !
Edit:
The buttons -that work on mouse click- are added in jQuery.dialog(); like this:
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
Answer: function() {
var answer = $("#dialog-form #answer").val();
alert("your answer : "+answer);
submit_with_ajax(answer);
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
alert("asd");
}
});

You can prevent the default action of an event with event.preventDefault(). I am not 100% sure how the form looks like in jQuery-ui and if preventing the default of the keypress works. As an alternative you can prevent the default action of the submit event which, as you would probably expect, prevents the form from being submitted (as per Gokul's answer). See mdn for more information on event.preventDefault().
$('#answer').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
e.preventDefault();
}
});
-- or --
$('whatevertheuiformis').on( 'submit', function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
e.preventDefault();
}
});

As yours...
<form>
<!-- <form onsubmit="return false"> is an optional -->
<fieldset>
<label for="answer">
<strong>Your Answer : </strong>
</label>
<input type="text" name="answer" id="answer"
class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
//jQuery Version
$('form').submit(function(){
return false;
});
// javascript
document.getElementById('my-form').onsubmit = function() {
return false;
}
$('#answer').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
e.preventDefault();
//alert("enter pressed on answer input");
submit_with_ajax(answer);
}
});
So Here the Form will not submit at all.. so that you can perform your AJAX submission or REQUEST....
Hope it helps...

DEMO
Try this,
Enter the value in input answer and click enter
$(document).ready(function () {
$(document).on('keypress',function(e)
{
if(e.which==13 && $("#answer").val().length>0)
{
alert("hi"); // do your ajax call here
}
});
});
Hope this helps

Related

How can we check which button is clicked in a jQuery UI dialog box?

I am trying to use jQuery UI to build a dialog box with Yes/No button for user confirmation. (This is because I want to make the UI uniform, as I have used jQuery UI to build the warning dialog boxes.) My intention is to ask for user confirmation if a large number (1000 or above) is submitted in the text box. So far my JavaScript code looks like this:
function checkclick(button1, button2, theForm) {
var val;
val = theForm.mybox.value;
v = parseInt(val) || 0;
var btns = {};
btns[button1] = function(){
$(this).dialog('close');
};
btns[button2] = function(){
$(this).dialog('close');
};
if (v >= 1000) {
$('#dialog').dialog({
autoOpen: true,
modal:true,
buttons:btns
});
$('#dialog_link').click(function () {
$('#dialog').dialog('open');
});
return false;
}
return true;
}
And my HTML looks like this:
<div id='dialog' title='Note' style='display:none'>
<p id='dialog_link'>This is a very large number. Are you sure?</p>
</div>
<form name='myForm' action='result.php' method='post'
onsubmit="return checkclick('Yes', 'No', this)">
<input type='text' name='mybox'>
<input type='submit'>
</form>
The problem is, when the user clicks either of the Yes or No button, it will go back to the same page. However, if I change the 'return false' to 'return true' inside the 'if' part, once the Submit button is clicked, the page will go directly to result.php without waiting for the user to click the Yes or No buttons. Is there any way to check which button is being clicked by the user, so that the page will go to result.php after clicking Yes, but remaining at the current page after clicking No?
jQuery dialog has the option buttons which can be used to describe the required buttons and it's action.
function checkclick(button1, button2, theForm) {
var val;
val = theForm.mybox.value;
v = parseInt(val) || 0;
if (v >= 1000) {
$('#dialog').dialog({
autoOpen: true,
modal:true,
buttons:{
"Yes":function() {
alert('Yes has been clicked'); //Your coding here
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
$('#dialog_link').click(function () {
$('#dialog').dialog('open');
});
return false;
}
return true;
}
I don't have the "Reputation" to comment on your follow up so I had to post as an answer. Apologies for the breach in protocol.
If I understand your goal correctly, you just need to conditionally submit the form. I believe you can accomplish this by preventing the default behavior if the user decides the form submission is too long. Something like this:
<form id="target" action="destination.html">
<input type="text" value="string value">
<input type="submit" value="Submit">
</form>
$( "#target" ).submit(function( event ) {
if (//result of dialog is false) {
event.preventDefault();
} else {
return;
}
});

JavaScript function getting called twice on Enter key press

I have a button in my html page
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
I have binded a jquery click event to this button like
$('#btnLogin').click(function () {
ValidateLogin();
});
I'm also checking the enter key press to call the same function ValidateLogin(); like below
$(document).keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
The issue that i'm facing is when the user presses the tab key to get in focus over the Login button and then press Enter Key the ValidateLogin() is called twice.How to deal with this situation.
Note : i can't use type="submit" to do a form submit ..since i'm using ajax call on button click
You should use the submit event instead. Your browser is probably firing the click event when pressing enter and that is effectively the same as pressing the submit button:
$("form").submit(function(e) {
// Stop the form submitting
e.preventDefault();
ValidateLogin();
});
function ValidateLogin() {
$.ajax({
// ...
}).done(function(e) {
if(!e.valid) {
alert("Invalid Login");
}
});
}
Second reason, even if your keypress was to work correctly, I can press a button by pressing spacebar too.
Here is a full Fiddle to demonstrate.
Since it's a form I would prefer to attach event on form elements instead on document.
Use form element like text, textarea etc. on click of enter should submit the form.
$('input:text, textarea').keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
In your case event is bubbled from the button to document hence it is called twice.
Its working fine check this fiddler DEMO
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
$('#btnLogin').click(function () {
//ValidateLogin();
alert('click');
});
$(document).keypress(function (e) {
if (e.which == 13) {
//ValidateLogin();
alert('enter');
}
e.preventDefault();
});

jQuery to submit a form

I have the following code which is not working. I hope you can help me with this.
basically I have a form that i want to confirm using jQuery Dialog first before submitting it. so when i click on submit i get the dialog but when i press yes to confirm nothing happens!!
$(function() {
$('#massform').submit(function(e){
e.preventDefault();
$('#dialog-mass-confirm').dialog('open');
});
$( "#dialog-mass-confirm" ).dialog({
autoOpen: false,
resizable: false,
draggable: false,
height:180,
modal: true,
buttons: {
"No": function() {
$( this ).dialog( "close" );
},
"Yes": function() {
$("#massform").submit();
}
}
});
});
<form id="massform" method="post" action="new.php">
<input type="text" name="email" size="41">
<input type="submit" value="Submit">
</form>
It appears that you may have a circular reference because you are rebinding the submit function for the form, and then calling submit from the modal which will fire the same event that opened the modal in the first place. I would suggest the following to avoid this problem:
$(function() {
$('#submitButton').click(function(e){
e.preventDefault();
$('#dialog-mass-confirm').dialog('open');
});
$( "#dialog-mass-confirm").dialog({
autoOpen: false,
resizable: false,
draggable: false,
height:180,
modal: true,
buttons: {
"No": function() {
$( this ).dialog( "close" );
},
"Yes": function() {
$("#massform").submit();
}
}
});
});
<form id="massform" method="post" action="new.php">
<input type="text" name="email" size="41">
<input ID="submitButton" type="button" value="Submit">
</form>
You shold look up scopes and event trigering in more detail so you understand the problem you are facing.
1.st you have created an jqery function which is bound to your form submit event.
$('#massform').submit(function(e){
e.preventDefault();
$('#dialog-mass-confirm').dialog('open');
});
When you use the submit button your event gets fired, and the dialog opens. When you however submit the form with
"Yes": function() {
$("#massform").submit();
It fires the bound function pointed out earlier... which prevents the form it self from being submitted. To be precise you just reopen the dialog. but that happens so fast that you don`t notice it.
If you are forced to use the submit action for compatibility reasons... you could use a loc variable to do the dirty job...
$('#massform').submit(function(e, lock){
if(lock)
e.preventDefault();
$('#dialog-mass-confirm').dialog('open');
});
while you may set the lock in the submit. Have never tried it tht way, but it should work. i usually end up using a variable from the document ready scope.
This is a dirty solution when you cant modify the form. Ugly but it works.

jquery: event for simulating live typing

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Hiding search field code only executes one time

I'm writing a piece of jQuery to make a search box appear when a user hovers over the search button, displays for five seconds, then disappears if the user hasn't given the search text field focus.
It currently just appears, disappears, then reappears for good. My code is below, you can see it in action at http://emilysenger.ca
jQuery(document).ready(function(){
jQuery('input').blur(function(){
jQuery('input').removeClass("focus");
})
.focus(function() {
jQuery(this).addClass("focus")
});
jQuery("div#sneakySearch form input#search").css("display", "none");
jQuery("div#sneakySearch form input#searchButton").hover(function(){
jQuery("div#sneakySearch form input#search").fadeIn("slow");
}, function(e){
jQuery(e).delay(5000,
function(e){
if(!jQuery("div#sneakySearch form input#search").hasClass("focus"))
{
jQuery("div#sneakySearch form input#search").fadeOut("slow");
}
});
});
});
Some help with this would be awesome. Thanks!
I made it so it fades out on the textbox's blur event too, and that it never fades out if the textbox has text in it. You can see it working here.
The HTML:
<div id="sneakySearch">
<form method="get" action="/">
<input type="text" name="s" id="search">
<input type="submit" value="Search" id="searchButton">
</form>
</div>
And the JS:
function fadeOutSearch() {
var element = jQuery("div#sneakySearch form input#search");
if (!element.hasClass("focus") && element.val() == "") {
element.fadeOut("slow");
}
}
jQuery(document).ready(function() {
jQuery('input').blur(function() {
jQuery('input').removeClass("focus");
setTimeout(fadeOutSearch, 1000);
}).focus(function() {
jQuery(this).addClass("focus")
});
jQuery("div#sneakySearch form input#search").hide();
jQuery("div#sneakySearch form input#searchButton").hover(function() {
jQuery("div#sneakySearch form input#search").fadeIn("slow");
}, function(e) {
setTimeout(fadeOutSearch, 1000);
});
});

Categories