Can't unbind keypress; pressing 'enter' in searchbar passes the window.location/document.location I specified and goes to the wrong page - window

I'm working on a page that is part of a pre-existing site. There is some script attached to the page that is overriding my searchbar 'enter' presses, so that every time I press enter it goes to the site-search page instead of my events-search page. This is my function:
$(".searchBox").keypress(function (e) {
var key = e.which;
if (key == 13) // the enter key code
{
var searchTerms = $(this).val();
var newQueryString = updateQueryStringParameter(resetPage(document.URL), "q", searchTerms);
window.location.href = newQueryString;
}
});
By stepping through it, I can see that it is hitting each line of my method, including window.location.href... but then it keeps going, and loads the wrong page even though newQueryString is correct.
I tried using document.location isntead of window.location.href, and I tried unbinding my searchbox
$(document).ready(function () {
$(".searchBox").unbind();
}
but it didn't work...

You can use preventDefault() method to stop the default event propagation.
$("#myForm").submit(function(event){
event.preventDefault();
});
http://api.jquery.com/event.preventdefault/

Related

Firefox webextension - confirm function causes extension popup to close immediately

I would like to port an existing fully functional Chrome extension to Firefox, everything seems to work except the confirm() function behavior.
When the user clicks a specific button in the popup.html page, he is asked to confirm the action.
Chrome successfully prompts the dialog, I then get a Boolean back as soon as "ok" or "cancel" button is clicked, code related to the boolean returned is executed.
Firefox behavior feels buggy on the other hand. The confirm dialog prompts too but the extension popup is instantly dismissed, preventing further code in the click event handler to execute.
manifest.json : …, "default_popup": "popup.html", …
popup.html :
…
<script src="js/popup.js"></script>
</body>
popup.js :
removeButton.addEventListener('click', function () {
// Firefox: calling confirm() closes the popup.html page ...
// ... terminating event handler code
if (confirm("Please confirm you wish to remove this item.")) {
// …
}
});
Is there something to do about it or should I stop using confirm() and find a workaround ?
EDIT - Workaround solution
As a workaround, I set a 3 seconds countdown when the button is clicked and change its caption every second. Before time is up, if the user click again, the final action gets cancelled, otherwise final action is performed.
let log = document.querySelector('p')
,resetInterval = null
;
document.getElementById('resetbtn').addEventListener('click', function(e) {
if (!resetInterval) {
// Create a countdown and delete data when time is up.
e.target.content = e.target.innerHTML;
resetInterval = setInterval( function() {
var counter = +(e.target.innerHTML.trim().match(/\d+/)||[4])[0];
if (counter == 1) {
// Sending command to bacground page
// chrome.runtime.sendMessage({command:'remove'}, function (){
e.target.innerHTML = e.target.content;
resetInterval && clearInterval(resetInterval);
resetInterval = null;
log.innerHTML = 'Perform action…';
// });
} else e.target.innerHTML = 'Reset in '+(counter-1)+'s';
}, 1000);
log.innerHTML = '';
} else {
resetInterval && clearInterval(resetInterval);
e.target.innerHTML = e.target.content;
resetInterval = null;
log.innerHTML = 'Action aborted';
}
});
<button type="button" id="resetbtn">Reset</button>
<p></p>
Popout windows are designed to be dismissed when you move focus to another window. You can’t use dialogs (new windows) from the popout as they’re moving focus and thus dismissing the popout.

Using keypress() and keyup() when using an onscreen keyboard

I have a lovely piece of code which drives a search box on a php page, making the search box dynamic, and it works perfectly. I'm just trying to adapt it, and at a bit of a loss.
At the moment the search must be done on a keyboard to make the search work. This is from the keypress() and keyup() functions within the script.
My problem is that I'm trying to use this search with an onscreen keyboard and no physical keyboard, so there never is a keypress or keyup.
Is there anything I can do do you think to replace these.
Would I be best to add an amended version of the code below (without the keypress/keyup) to each onclick even of my onscreen keyboard, or just amend the code to react to onscreen clicks?
thanks if anyone can help
<!--Javascript to turn keystrokes into search value-->
<script type="text/javascript">
$(document).ready(function () {
// Hide the submit button
$(":submit").hide();
// Bind an event to the keypress in order to override the form submission when pressing the enter key
$("input[name='search_term']").keypress(function (e) {
if (e.which == 13) {
// prevent the form from submitting in the normal manner (return key)
e.preventDefault();
}
});
// Bind an event to the keypress event of the text box
$("input[name='search_term']").keyup(function () {
// Get the search value
var search_value = $(this).val();
// This time we're going to grab data from a file to display
var filename = "functions/search.php";
// Send these values
var posting = $.post(filename, { search_term: search_value });
// Display this value in our results container
posting.done(function (data) {
$("#search_results").empty().append(data);
});
});
});
</script>

Ajax loader and events runs more than once

I have a website that pages' contents loaded by ajax. All of my pages are seperate files actually and when I need to call a page, I just passed the link to my "pageLoader" function.
pageLoader handle with content loading and re-ignite/re-define the necessary functions like close button.
Since the actual function have ~250 lines, I did re-write a short version;
var pageLoader = function(link){
var page = $(link).attr("href").replace('#','');
if(page != lastCalledURL){
// Load the page.
$.ajax({
beforeSend: function(){ /* remove previously loaded content; */ },
success: function(data){
// remove the loaded content if user clicked to close button.
$("a.close-button").live("click", function(){
$(this).parent().fadeOut().remove();
return false;
});
// load another page if user click another page's link.
$("a.content-loader-link").live("click",function(){
pageLoader(this);
});
// handle with tabs
$("a.tabs").live("click", function(){
var index = $("a.tabs").index(this);
console.log(index);
return false;
});
}
});
lastCalledURL = page;
}
return false;
OK. If I click a link in the page, It calls pageLoader. If I click one of the links just once, pageLoader called once. If I click another link, pageLoader called twice. If I click another link again, pageLoader called third times and so on.
Same things happen for the links that bind with "live" function in the code. If I click a.tabs, it write to console twite. If I clicked another .tabs link, it write to console four times and increasing double for every click.
I don't why it happens. Please let me know if you have any idea.
You can solve it by using the bind and unbind. Like this:
$("a.tabs").unbind('click').bind("click", function(){
var index = $("a.tabs").index(this);
console.log(index);
return false;
});
But i would prefer that you attach this events in your $(document).ready function instead of everytime you make an AJAX call.
$(document).ready(function() {
// Attach your events here.
});
Those live event handlers "Attach a handler to the event for all elements which match the current selector, now and in the future." so you shouldn't need them in your ajax call.

jquery ajax post - not being fired first time

I'm trying to do an ajax post after a button is clicked, and it works in firefox but not in IE the first time the page is loaded. It does work if I refresh the page and try again second time - but not first time and this is crucial.
I've scanned over various web pages - could it be anything to do with the listener? (I've just seen this mentioned mentiond somewhere) Is there something not set correctly to do with ajax and posting when page first loads?
$(document).ready(function() {
$('#btnCont').bind('click',function () {
var itm = $("#txtItm").val();
var qty = $("#txtQty").val();
var msg = $("#txtMessage").val();
var op_id = $("#txtOp_id").val();
//if i alert these values out they alert out no prob
alert(itm+'-'+qty+'-'+msg+'-'+op_id);
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
I would start debugging the click event. I.e. if you try to put .bind into a a href tag, the tag itself has a click event that may act on an unwanted way. There exist a command that are named something like event.preventDefaults() that avoids the standard feature of click. After All, you try to manipulate the DOM last of all actions (document.load).
$('#btnCont').bind('click',function () { .. }
I would also try to debug the same functionality with adding onClientClick to the tag instead of adding bind to the document load.
I hope that bring some light.

jquery: bind click event to ajax-loaded elmente? live() won't work?

hey guys,
I have an input field that looks for matched characters on a page. This page simply lists anchor links. So when typing I constantly load() (using the jquery load() method) this page with all the links and I check for a matched set of characters. If a matched link is found it's displayed to the user. However all those links should have e.preventDefault() on them.
It simply won't work. #found is the container that shows the matched elements. All links that are clicked should have preventDefault() on them.
edit:
/*Animated scroll for anchorlinks*/
var anchor = '',
pageOffset = '',
viewOffset = 30,
scrollPos = '';
$(function() {
$("a[href*='#']").each(function() {
$(this).addClass('anchorLink');
$(this).bind('click', function(e) {
e.preventDefault();
//console.log('test');
anchor = $(this).attr('href').split('#')[1];
pageOffset = $("#"+anchor).offset();
scrollPos = pageOffset.top - viewOffset;
$('html, body').animate({scrollTop:scrollPos}, '500');
})
});
});
Well, I'm looking for all href's that contain a #. So I know those elements are anchors that jump to other elements. I don't want my page to jump, but rather scroll smoothly to this element with this specific #id.
This works fine when I use bind('click', ... for normal page-elements that have been loaded when the page is opened. It doesn't work for anchors that have been loaded via ajax! If I change the bind to live nothing does change for the ajax loaded elements - they still don't work. However normal anchors that have always been on the page are not triggering the function as well. So nothing works with live()!
When you say "it won't work" do you mean that your function is not been called or that you can not cancel out of the function? As far as I know you can not cancel out live events. With jQuery 1.4 you can use return false to cancel out live event propagation. Calling e.preventDefault() won't work.
Edit: right so this code should in principal work. What it still won't do is, it won't add the 'anchorLink' class to your new anchors. However if the clicks work then let me know and I will give you the right code to add the class too!
var anchor = '',
pageOffset = '',
viewOffset = 30,
scrollPos = '';
$(function() {
$("a[href*='#']").each(function() {
$(this).addClass('anchorLink');
});
$("a").live('click', function(e) {
if ($(this).attr("href").indexOf("#") > -1) {
e.preventDefault();
//console.log('test');
anchor = $(this).attr('href').split('#')[1];
pageOffset = $("#" + anchor).offset();
scrollPos = pageOffset.top - viewOffset;
$('html, body').animate({ scrollTop: scrollPos }, '500');
//nikhil: e.preventDefault() might not work, try return false here
}
});
});

Resources