Question

I don't understand why $('#searchbox').live prevents my search input to be typed in. I can log the event but nothing shows up. But when I comment out the searchbox line it suddenly seems to allow text in the searchbox. Plus the search function via the magnifying glass click works! Very strange.

Has anyone had an issue like this?

The reason I structured it this way is because I want this function to be used by my other applications.

function initModuleSearch(selector){
    $('#clear_x').live('click', {name:'clear', id:selector}, performSearch);//clears search
    $('#magnify').live('click', {name:'find', id:selector}, performSearch);//submits search
    $('#searchbox').live('keyup', {name:'enter', id:selector}, performSearch);//submits search
    return false;
}

function performSearch(evt){
    var eventType = evt.type;        
    var eventName = evt.data.name;
    var selector = evt.data.id;
    var searchInput = $('#searchbox');

    console.log('Hello:' + eventName)

    //do some search and filter stuff below here

   evt.preventDefault();//disallow browser to perform default action
   return false;
}



initModuleSearch(".module");//init searchbox function
Was it helpful?

Solution

evt.preventDefault(); or even return false will prevent you to type anything in the textbox.

If you feel its not required then remove it from the method.

OTHER TIPS

You catch the keyup-event, call the performSearch-function and pass the event, and within that function you then call the .preventDefault() on that event, which I believe will prevent the keystroke from being registered in the input.

You could perhaps try something like:

if (eventType !== "keyup")
   evt.preventDefault();

That way, the clicks on your other to elements will be prevented, but you will still be able to type in the search input.

Clarification:

Your three initial event-listeners that you add:

$('#clear_x').live('click', {name:'clear', id:selector}, performSearch);//clears search
$('#magnify').live('click', {name:'find', id:selector}, performSearch);//submits search
$('#searchbox').live('keyup', {name:'enter', id:selector}, performSearch);//submits search

All call the same function performSearch. Within that function, you take the event that you just caught evt (in the case with the search box, that is the keyup-event), and then you call the .preventDefault() method on it evt.preventDefault(), which tells the browser to discard its default behavior for this keyup-event, which normally would be to add the character of the key you just stroke into the input-field. When you say evt.preventDefault(), you tell the browser "Don't do that, let me do some other custom stuff instead...", so the browser will not add that keystroke to the input-field.

Are your with me?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top