I have a search box and search button. I want to call a javascript method in case somebody types in search box and hits enter or clicks on search button.
So far with keypress event it's working fine:
function Search(e) {
if(e.keyCode==13) {
//DO operation
}
}
If I want to call same function on onclick event of search button, how can I use same method shown above. Only purpose here is not to duplicate same code by writing two different methods which at the end do same thing.
Add listeners to both events (onclick and onkeypress) and use event's type:
function Search(e) {
if( e.type == 'click' ||
(e.type=='keypress' && e.keyCode==13) ){
//DO operation
}
}
Demo here.
function Search(e) {
var doOper = function() {
//DO operation
}
if(e.keyCode==13) {
doOper();
}
if(buttonClicked) {
doOper();
}
}
Related
I have a form that is split into sections. When the user clicks "continue", I have a jquery script that checks to see if all required fields are filled out. If any aren't, then a box appears with a warning and buttons (They are actually <a> tags) for 'yes' and 'no'. I attach an onclick event to the 'yes' button that triggers a function. The function works, but a # appears in the address bar (website.com/page#), which I'm guessing is because the event.preventDefault(); in my code isn't working.
Here is the function that adds the onclick event:
function checkSection (event, check, goTo) {
event.preventDefault();
var emptyFields = "0";
$("#ia"+check+"Div .check").each(function() {
var val = $(this).val();
if (val == "") {
emptyFields++;
}
});
if (emptyFields >= 1) {
$(".mask").show();
$("#warningBox").show();
$(document).on("click", "#yesBtn", function() {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
$(".mask").hide();
});
} else {
var x = window['save'+check];
x(event, goTo);
$("#warningBox").hide();
}
}
Here is the tag I am adding the event to:
<div class="medBtn short">
<div class="btnTbl">
Yes
</div>
</div>
The function I end up calling is like this:
function saveContact(event, val) {
event.preventDefault();
//Do Stuff - This is the function where event.preventDefault(); isn't working
}
Like I said, the function still works, so if it's not something I can get around, that is fine. I just don't like having a # in the address bar.
The event object doesn't exist until the event occurs
You prevent default inside the actual event handler
$(document).on("click", "#yesBtn", function(event) {
event.preventDefault();
....
})
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
How to add multiple event listeners in the same initialization?
For example:
<input type="text" id="text">
<button id="button_click">Search</button>
JavaScript:
var myElement = document.getElementById('button_click');
myElement.addEventListener('click', myFunc());
This is working correctly however I would like to have another event listener for this input filed in the same call if that is possible, so when user clicks enter or presses the button it triggers the same event listener.
Just one note. User needs to be focused on the input field to trigger an "enter" event.
Just bind your function to 2 listeners, each one of the wished element:
document.getElementById('button_click').addEventListener('click', myFunc);
document.getElementById('text').addEventListener('keyup', keyupFunc);
where the new function test if the user pressed enter and then execute the other function :
function keyupFunc(evt) {
if(evt.keyCode === 13) // keycode for return
myFunc();
}
Working jsFiddle : http://jsfiddle.net/cG7HW/
Try this:
function addMultipleEvents(elements, events){
var tokens = events.split(" ");
if(tokens.length == elements.length){
for(var i = 0; i< tokens.length; i++){
elements[i].addEventListener(tokens[i], (e.which == 13 || e.which == 48)?myFunc:); //not myFunc()
}
}
}
var textObj = document.getElementById("textId");
var btnObj = document.getElementById("btnId");
addMultipleEvents([textObj,btnObj], 'click keyup');
UPDATE:
function addMultipleEvents(elements, events) {
var tokens = events.split(" ");
if (tokens.length == elements.length) {
for (var i = 0; i < tokens.length; i++) {
elements[i].addEventListener(tokens[i], myFunc); //not myFunc()
}
}
}
var textObj = document.getElementById("textId");
var btnObj = document.getElementById("btnId");
addMultipleEvents([btnObj, textObj], 'click keyup');
function myFunc(e) {
if (e.which == 13 || e.which == 1) {
alert("hello");
}
}
Working Fiddle
I think the best way to do this is by using for loops.
const events = ["click", "mouseover"]
for (i in events) {
document.getElementById("button_click").addEventListener(events[i], () => myFunc())
}
The code above loops through every events inside an array and adds it to the button.
Yeah this is a good question and can apply to other scenarios. You have a form and a user will have input text field, a radio box, a select option. So now you want the submit button to go from disabled to enabled. You decide to add an event listener to check if fieldA and fieldB and fieldC is first to enable submit button.
If you use event listener on Keyup", and all your fields are valid, the submit button will become enabled only if the last field is a text field because the event will only be triggered when you let go the key. This means it will not trigger if the radio box or select option is selected with your mouse. We must not rely in the order the fields are filled for the logic to work. Again, If you use "click", it sucks, because user will have to click somewhere on page in order for the event listener to fire and run the logic. So i think we'll need an event lister on mouseup, keyup and change for this example below. I assume you made all your validations and variables for the form fields already. We need a function with parameters of multiple events names as a string, the element we want to target (document, or button or form), and a custom function that contains our logic.
// Create function that takes parameters of multiple event listeners, an element to target, and a function to execute logic
function enableTheSubmitButton(element, eventNamesString, customFunction) {
eventNamesString.split(' ').forEach(e => element.addEventListener(e, listener, false));
}
// Call the above function and loop through the three event names inside the string, then invoke each event name to your customFunction, you can add more events or change the event names maybe mousedown, keyup etc.
enableSubmitButton(document, 'keyup mouseup change', function(){
// The logic inside your customFunction
if (isNameValid && isLocationValid && isProjectValid){
publishButton.disabled = false;
} else {
publishButton.disabled = true;
// Do more stuff like: "Hey your fields are not valid."
}
});
// The isNameValid isLocationValid, isProjectValid are coming from your previous validation Javascript for perhaps a select field, radio buttons, and text fields. I am adding it as an example, they have to be equal to true.
// The publishButton is a variable to target the form submit button of which you want enabled or disabled based one weather the form fields are valid or not.
// For example: const publishButton = document.getElementById("publish");
i have an html textbox with onkeypress event to send message like below
<input type="text" data-bind="attr:{id: 'txtDim' + $data.userID, onkeypress: $root.sendMsg('#txtDim' + $data.userID, $data)}" />
I have written javascript function to to send message while preesing enter button like below:
self.sendMsg = function (id, data) {
$(id).keydown(function (e) {
if (e.which == 13) {
//method called to send message
//self.SendDIM(data);
}
});
};
In my case i have to press enter button 2 times to send the message.
1: keypress call self.sendMsg
2: keypress call self.SendDIM
But i need to send message on one keypress only. It can be done in plain javascript only. But i need viewmodel data, so applied in data-bind. So not working fine.
The reason you need to press enter twice is that your sendMsg method is only attaching a handler to the keydown event. This handler is then invoked on the second button press.
A better approach would be to write a custom binding handler that attaches the event handler and passes the view model through:
ko.bindingHandlers.returnAction = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).keydown(function(e) {
if (e.which === 13) {
value(viewModel);
}
});
}
};
You can see a running example here
I have added keypress event like below to textbox
<input type="text" data-bind="attr:{id: 'txtGoalsheetNote' + $data.userID}, event:{keypress: $root.SendMsg}" />
And in javascript i have added the following method by keeping event as a parameter
self.SendMsg= function (data, event) {
try {
if (event.which == 13) {
//call method here
return false;
}
return true;
}
catch (e)
{ }
}
Then its work.
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.