I submit a <form> in javascript with 'ENTER' key and call a function. This function returns false so that the page is not reloaded.
Unfortunately, the box is not cleared as shown in the picture.
the end of the list, but 'toto' and other entries were proposed. The suggestion box is not cleared.
How could I clear it?
Here is the code used
$('form').on('submit', function () {
var newUser = $('input.user').val()
displayPerson(newUser) // add the person
$('input.user').val('')
return false;
});
I would suggest to briefly remove the focus from the input:
$('form').on('submit', function () {
var newUser = $('input.user').val()
displayPerson(newUser) // add the person
$('input.user').val('').blur(); // <-- blur
setTimeout(function () { // Allow time for blur to happen
$('input.user').focus(); // <-- put focus back (if desired).
}, 0);
return false;
});
Related
I'm experiencing some issues preventing form submission when I try to submit an invalid situation.
Assume I have the following code:
window.onload = function(){
$("form").on("submit",function (event) {
$("#errorDiv").fadeOut(null, null, function () {
OnSubmitForm(event)
});
})
}
function OnSubmitForm(event) {
let items = $("#mytable").dxDataGrid("instance").getSelectedRowsData();
if (items.length == 0) {
event.preventDefault();
} else if (items.some(item => item.booleanProperty != true)) {
event.preventDefault();
let badItems = items.filter(item => item.booleanProperty != true).map(item => item.id);
let divText = "<strong>bad items:<br>"
+ badItems.join("<br>") +"</strong>";
$("#errorDiv").html(divText);
$("#errorDiv").fadeIn();
}
}
My intention is to fadeOut the div I use to display the error, and when the animation is complete I call OnSubmitForm, passing event to it.
The flow of my actions is the following:
I click the submit button
fadeOut kicks in
OnSubmitForm is called
the else if condition is true, so the block is executed
event.preventDefault() works
I click again the submit button
Form is submitted
What's happening?
Plus, I've noted that the result of event.isPreventedByDefault() returns false before the first event.preventDefault(), then it returns true, because the event was already prevented once, according to the MDN documentation.
More info
I forgot to mention that if I do the same violating the first "rule" (first if statement) everything works as expected.
You call OnSubmitForm when the fade out is complete. This happens after the submit event handler function has finished without preventing the default behaviour.
The form has already been submitted by the time you try to stop it.
I have a div which contains an input element to enter some values. These values are added just above the div as a list element upon pressing enter or onFocusOut event. To this point it is fine. But if user types some value and does not press enter and directly clicks on save button, the onFocusOut function for that div should not be called. Instead it should take that typed value and call some save function. Do you have any suggestion on how to detect it?
My code snippet is here
JS:
divInput.onkeypress = function (event){
return someTestFunc();
}
divInput.tabIndex="-1";
$(divInput).focusout(function (e) {
if ($(this).find(e.relatedTarget).length == 0) {
addToList();
}
});
It is not a very delicate solution, but you could use a setTimeout before adding the item to the list and clear the setTimeout on save.button click.
Try this:
var $saveButton = $('#exampleButton')[0],
$divInput = $('#exampleInput')[0],
timedEvent = -1;
$($saveButton).on('click', function(event){
if(timedEvent) {
clearTimeout(timedEvent)
}
alert('not add to list & save');
})
$divInput.tabIndex="-1";
$($divInput).on('focusout', function(e) {
timedEvent = window.setTimeout(function() {
if ($(this).find(e.relatedTarget).length == 0) {
alert('add to list');
}
}, 200);
});
Check this working fiddle
(Fiddle: http://jsfiddle.net/qdP3j/)
I have this div:
<div id="addContactList"></div>
I use AJAX and change its innerHTML with something like:
<div id="<%= data[i].id %>">
<img src="<%= picture %>">
<button class="addAsFriend">Add as Friend</button>
</div>
In my JS, I have
$('#addContactList').on('click', '.addAsFriend', function () {
$(this).text('Request sent!');
$(this).attr('disabled','disabled');
});
What happens is that when I click on a button for the first time, I see that the click function ran; "Request sent!" is being shown but it immediately reverts back to the initial button. When I click a second time, it works fine.
I tried using event.stopPropagation and preventDefault but same issue happens.
As stated, it probably comes from the AJAX part:
Basically, I have 3 input fields on a page, and users can enter data in them. If there is data in the fields, they are posted and I use the data to query the database. There is a delay function of 250ms to prevent posting immediately every time a letter is typed.
var addContactsList = document.getElementById('addContactList');
$('#addContactForm').on('keyup change', function () {
var self = this;
// Add a short delay to not post for every letter typed quickly
delay(function() {
var userSearchData = {};
userSearchData.userId = 23;
$.each(['email', 'username', 'fullName'], function (_, el) {
var val = $(self).find('input[name="' + el + '"]').val();
if (val.length >= 3) {
userSearchData[el] = val;
}
});
if ( !isEmpty(userSearchData) ) {
$.post('/post/addContact', { userSearchData: userSearchData }, function (data) {
if (data) {
new EJS({url: '/templates/addAContact.ejs'}).update('addContactList', { data: data })
} else {
addContactsList.innerHTML = '';
}
});
} else {
addContactsList.innerHTML = '';
}
}, 225 );
});
It's because of the "keyup change". Change was being triggered again when clicking elsewhere (the add friend button).
Now though the problem is when people use the autocomplete feature using the mouse, it will not trigger because change isn't there anymore.
As you noticed, the change event fires when your input field loses focus (when you click on the button). You can keep the change event, and check if the change event is firing while the input field is focussed
$('#addContactForm').on('keyup change', function () {
if (!$(document.activeElement).is('input')) return; //add this line
I have below javascript code for window.onbeforeunload. I am calling code behind button click method when pressed browser back button.
Now the problem is cursor is not stopping until $("#buttonclientid").click() completes. Just calling the method and moving to next statement. How to hold or stop cursor until $("#buttonclientid").click() complete and then move to next step?
var form_has_been_modified = 0;
$(function () {
$("input").keyup(function () {
form_has_been_modified = 1;
})
window.onbeforeunload = function (e) {
if (!form_has_been_modified) {
return;
}
doYouWantTo();
}
});
function doYouWantTo(){
doIt=confirm('Do you want to save the data before leave the page?');
if (doIt) {
var returnbutton;
//cursor should stop here until click function completes.
returnbutton = $("#buttonclientid").click();
}
else{
}
}
I believe your problem lies in the fact that your doYouWantTo function does not return a value to be passed back into onbeforeunload so it is leaving the page while also running the function, rather than waiting until it completes.
Your best action here would be something like:
return doYouWantTo()
....
if(doIt) {
$('#buttonclientid').click(function() { // unsure if you can attach callback to click but idea is same
return true;
});
} else {
return true;
}
When binding an event handler to the onbeforeunload event, it should return one of two things:
if you want a confirm to show, your handler should return a string
if you don't want a confirm to show (skip the handler), return undefined (or don't return at all, same effect)
That being said, your code should look something like this:
var form_has_been_modified = false;
$("input").keyup(function () {
form_has_been_modified = true; // use a boolean :P
});
window.onbeforeunload = function (e) {
if (form_has_been_modified) {
return 'Do you want to save the data before leave the page?';
} else {
return undefined; // this can be omitted if you prefer
}
};
The only way to tell what a user clicked on the system dialog is to use setTimeout. See this question for details on that subject.
I got a function which checks if some input fields are changed:
var somethingchanged = false;
$(".container-box fieldset input").change(function() {
somethingchanged = true;
});
And a function which waits on window.onload and fires this:
window.onbeforeunload = function(e) {
if (somethingchanged) {
var message = "Fields have been edited without saving - continue?";
if (typeof e == "undefined") {
e = window.event;
}
if (e) {
e.returnValue = message;
}
return message;
}
}
But if I edit some of the fields and hit the save button, the event triggers, because there is a post-back and the fields have been edited. Is there anyway around this, so the event does not fire upon clicking the save button?
Thanks
When I do this pattern I have a showDirtyPrompt on the page. Then whenever an action occurs which I don't want to go through the dirty check I just set the variable to false. You can do this on the client side click event of the button.
The nice thing about this is that there might be other cases where you don't want to prompt, the user you might have other buttons which do other post backs for example. This way your dirty check function doesn't have to check several buttons, you flip the responsability around.
<input type="button" onclick="javascript:showDirtyPrompt=false;".../>
function unloadHandler()
{
if (showDirtyPrompt)
{
//have your regular logic run here
}
showDirtyPrompt=true;
}
Yes. Check to see that the button clicked is not the save button. So it could be something like
if ($this.id.not("savebuttonID")) {
trigger stuff
}