Javascript not closing menu - javascript

I have a piece of JavaScript which I use to search my site. When you type into the search it pulls up the products matching you query. This works fine, but I want the dropdown to close when the user clicks on the page. I know very little about JavaScript so any advice or even a point in the right direction will be appreciated.
function showSmartSearch() {
$.ajax({
url: "index.php?route=product/ajaxsearch&search=" + $("input[name='search']").val(),
type: "GET",
success: function(e) {
$("#smartsearchdiv").css("display", "block");
var t = "";
$("#smartsearchdiv").html(e)
}
})
}
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none")
}
var wait;
$(document).ready(function() {
$("input[name='search']").after('<div id="smartsearchdiv" style="margin-top:30px;background:white;width:230px;position:absolute;z-index:999;"></div>').blur(function() {}).keydown(function(e) {
if ($("input[name='search']").length && e.which == 38) {
e.preventDefault();
return false
}
}).keyup(function(e) {
if (!$("input[name='search']").val()) {
$("#smartsearchdiv").css("display", "none")
}
var t = $("input[name='search']").val();
var n = t.length;
if (t.replace(/^\s+|\s+$/g, "") && (e.which == 8 || 47 < e.which && e.which < 112 || e.which > 185)) {
if (n > 0) {
showSmartSearch()
} else {
hideSmartSearch()
}
}
if ($("#smartsearchdiv li").length && (e.which == 38 || e.which == 40)) {}
}).blur(function() {})
});
function hideSmartSearch() {
$("#smartsearchdiv").css("display", "none");
}

You can try this:
$(document).click(function(e){ // hide list if clicked outside
if($(e.target).is('#smartSearchDiv, #smartSearchDiv *'))return;
hideSmartSearch();
});
Also this:
$(document).click(function(e){ // hide list if clicked outside
if(!$(e.target).is('#smartSearchDiv'))
hideSmartSearch();
});

Use this:
$("#smartSearchDiv").click(function(e){
e.stopPropagation();
});
$(body).click(function(){
if($("#smartSearchDiv").is(":visible")){
hideSmartSearch();
}
});
This way, if you click on your search div, event will stop propagation to its parents, and nothing will happen. Otherwise, it will go upto your body and fire a close function.

Related

Keypress but not when input or textarea is in focus

I'm using the code below :
$(document).keypress(function (e) {
if (e.which === 68 || e.which === 100) {
doStuff();
}
});
What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.
How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.
Thanks !
Alternatively to e.target, you could test if the current active element is an input or textarea:
$(document).keypress(function (e) {
var focussedTag = document.activeElement && document.activeElement.nodeName;
if( focussedTag === 'INPUT' || focussedTag === 'TEXTAREA' ) {
return;
}
if (e.which === 68 || e.which === 100) {
doStuff();
}
} );
Fiddle: https://jsfiddle.net/e1qtapo6/
$(document).on('keypress', ':not(:input)', function (e) {
if (e.which === 68 || e.which === 100) {
doStuff();
}
});
Add another check before executing the 'doStuff' function. Check if the user has any input element in focus, and if true then only execute the statement.
Something like this:
$(document).keypress(function (e) {
if ( (e.which === 68 || e.which === 100) && (!$(input).is(":focus")) ) {
doStuff();
}
});
Another one -
$(document).keypress(function (e) {
if (e.which === 68 || e.which === 100) {
var _node = e.target.nodeName;
if( _node !== "INPUT" && _node !== "TEXTAREA" ){
doStuff();
}
}
});

How can I use keyup and down true false

I have the following code to allow user to enter single digit code in an input box, if user presses delete key, then, I would like to recheck some condition and allow user type again. How do I do it?:
$('.code').bind('keyup', function(event) {
var value = $(this).val();
console.log("value.." + value.length);
if (value.length === 1) {
$('.InputInsertCodeLast').bind('keydown', function(event) {
var code = event.keyCode || event.which;
console.log('You pressed a "key" key in textbox' + event.keyCode);
if ((code === 8 || code === 46) || (value.length === 0)) {
return true;
} else {
//code to not allow any changes to be made to input field
return false;
}
});
} else if (value.length === 0) {
console.log("value.length,,0");
$('.InputInsertCodeLast').bind('keydown', function(event) {
console.log("value.length,22,0");
return true;
});
}
});
https://plnkr.co/edit/SpjcKkTA4UaJ0GzzEuYf?p=info
window.onload = function() {
window.addEventListener('keydown', function(event) {
event.preventDefault();
if(event.key === 'Backspace'){
console.log('backspace');
}
});
}
of course this is just a suggest to give an idea how things work, you can workout a more efficent solution based on this :)

Number in textfield should be autoformatted only after user clicks outside the textbox?

I have a problem. Basically, what happens in my case is that the numbers in my textbox are autoformatted as I type. I don't want this to happen. What I want is that the numbers should be autoformatted only when the user clicks outside the textbox.
In my input tag I have :
onkeyup="format(event, this);"
My javascript function is :
function format(e, obj) {
if (e.keyCode == 36) {
press1(obj);
}
if (e.keyCode == 13) {
return false;
}
if ((e.keyCode <= 34) || (e.keyCode >= 46 && e.keyCode < 58) || (e.keyCode >= 96 && e.keyCode <= 105)) { // //alert(e.keyCode);
obj.value = CommaFormatted(obj.value);
} else {
if (e && e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
return false;
}
}
where the press1 function is:
function press1(textControlID) {
var text = textControlID;
if (text.getAttribute("maxlength") == text.value.length) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
return true;
}
if (text != null && text.value.length > 0) {
if (text.createTextRange) {
var FieldRange = text.createTextRange();
FieldRange.moveStart('character', text.value.length);
FieldRange.collapse();
FieldRange.select();
} else if (text.setSelectionRange) {
var textLength = text.value.length;
text.setSelectionRange(textLength, textLength);
}
}
}
I really hope this could be solved. Please!
You could change onkeyup to onblur, which is the event that gets fired when the control loses focus - clicking out of it.
The onkeyup event fires with every keypress.

Call function based on input

I've an textbox in asp.net,when i enter ";" semicolon in textbox means it have to call a function.Is there any way to do this.please help me out guys..i tried change function but it calls at every keypress in textbox.
$('#prgrp').on('change', function (evt)
{
var txt = $("#prgrp").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
var duplicateValues = [];
for (var i = 0; i < valueSortArray.length; i++)
{
if (valueSortArray[i + 1] == valueSortArray[i])
{
duplicateValues.push(valueSortArray[i]);
}
}
if (duplicateValues.length > 0)
{
$("#duplicate").html("Don't enter repeated values");
$('#duplicate').css('color', 'RED');
$("#prgrp").autocomplete("disable");
}
else {
$("#duplicate").html("");
$("#prgrp").autocomplete("enable");
}
});
Try this:-
$("#prgrp").keypress(function (e) {
if (e.keyCode == 59) {
//Call your function here
}
});
Please note, you can also use e.which in place of e.keyCode as it is jquery standardized.
Try this
$('#prgrp').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if(code == 59) { //
//Do something
}
});
Demo
try this code
$( "#prgrp" ).keypress(function( event ) {
if ( event.which == 59 || event.keycode == 59 ) {
//your function call
}
});

How to limit Tab listener to callback only if the textbox has change

I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/

Categories