jQuery - triggering multiple events one by one - javascript

I'm using jquery tagsInput plugin where I need to dynamically modify the query(deleting the query or entering the new query) without actually typing in the search box connected with tagsInput plugin.
My problem here is I want to trigger backspace event at first then enter event next. Here is the code.
function triggering_events() {
$(".tag").each(function() {
var e = jQuery.Event("keydown");
e.keyCode = 8;
e.which = 8;
$("#input-search_tag").trigger(e); //triggering backspace event
});
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); //triggering enter event
}
But only the backspace event is triggering from the above code. How can I make that enter event work?
Could anyone point out the mistake I've done?
Thanks!

you can try use the methods removeTag and addTag for remove and add tag's:
function triggering_events() {
var
idInput = 'input-search',
input = $("#" + idInput);
$("#"+idInput+"_tagsinput .tag").each(function() {
var tag = $.trim($(this).find('span:eq(0)').text());
input.removeTag(tag);
});
input.addTag("food");
}
run

There is an issue here:
$("#input-search_tag").val("food").trigger(e); //triggering enter event
.val() returns you a string value of the jquery Element, it is not a chainable method. strings do not have a trigger method.
You could fix this by splitting it into two calls:
var input = $("#input-search_tag");
input.val("food");
input.trigger(e); // triggering enter event
Or using .end():
$("#input-search_tag").val("food").end().trigger(e); //triggering enter event
Edit: putting it all together, along with reusing one event instead of creating multiples:
function triggering_events() {
var e = jQuery.Event("keydown");
e.which = 8;
$(".tag").each(function() {
$("#input-search_tag").trigger(e); // triggering backspace event
});
e.which = 13;
$("#input-search_tag").val("food").end().trigger(e); // triggering enter event
}

Related

Trigger a "ENTER" in programmatically

It is possible to program a "Enter" after a value is added to a input text box?
If yes, I need help on my code below. It does't trigger the "ENTER" keypress.
My code as below:
$('#clo_cart').click( function () {
/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.which = 13;
eneterKey.keycode = 13;
$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}//end of button click
Pls Help
Just replace the keydown event with keypress event. There are some differences between how they use event.which property. This might be one of the cases where the two of them use different values for event.which.
var eneterKey = jQuery.Event("keypress");
Also note that which property has been deprecated. You can compare with the event.key property. It should have value Enter when the enter key is to be simulated.
$('#clo_cart').click( function () {
/*Save ENTER in variable*/
var eneterKey = jQuery.Event("keydown");
eneterKey.key = 'Enter';
$("#scan_char").focus().val('CLOSECTN').trigger(eneterKey);
}
You can use this code,
$('#clo_cart').click( function () {
var e = $.Event( "keypress", { which: 13 } );
$("#scan_char").focus().val('CLOSECTN').trigger(e);
}//end of bu
This code below work fine for me.
$('#clo_cart').click( function () {
$("#scan_char").focus().val('CLOSECTN').trigger(enterKey());
}//end of button click
/* Function to allow program keypress ENTER */
function enterKey() {
return $.Event( "keypress", { which: 13 } );
}

Sending keypress to a form field

I want a user to click on something, have it auto-fill an input field (a search field), and then automatically send an enter keypress to execute it. My code below, it does not appear to send the enter command. It my code, I will have to manually press enter to start the search. Is there an error in the code? Thanks.
jsfiddle here: https://jsfiddle.net/eliluong/5n50mun2/
$('.clickme').bind('click', function() {
var $this = $(this);
var input_text = "search for this";
$('#quicksearch').val(input_text);
$('#quicksearch').focus();
var e = jQuery.Event('keypress');
e.which = 13;
$('#quicksearch').trigger(e);
});
Not too sure but replace this:
$('#quicksearch').trigger(e);
With This:
$(this).trigger(e.which);
Alternatively, you could just use JQueries Built in submit function, no need to capture the keypress:
$('.clickme').click(function () {
var input_text = "search for this";
$('#quicksearch').val(input_text);
$('#quicksearch').submit();
});
var e = jQuery.Event("keypress");
e.which = 13;
e.keyCode = 13;
$("#quicksearch").trigger(e);
Haven't you forgotten the third line of the above code?
Moreover you have to click the button that submits the form, not the #quicksearch button :)

JS onkeydown/onkeyup - convert to jQuery keydown/keyup

I currently have some js for phone number validation that is using inline event listeners in the input field. I need to change this example so that instead of attaching the event listeners inline, I would be targeting the DOM element in jQuery and adding the event listeners. Here's a working example of what I have so far: http://jsfiddle.net/yVdgL/21/
window.mask = function (e,f){
var len = f.value.length;
var key = whichKey(e);
if((key>=47 && key<=58) || (key>=96 && key<=105))
{
if( len==1 )f.value='('+f.value
else if(len==4 )f.value=f.value+')'
else if(len==8 )f.value=f.value+'-'
else f.value=f.value;
}
}
function whichKey(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
return code
}
and
<input type="text" name="phone" id="phone" onkeydown="mask(event,this)" onkeyup="mask(event,this)" maxlength="13" />
I tried this but was unable to achieve the functionality that I need.
i have update you jsfiddle example:-
jQuery(document).ready(function(){
jQuery('#edit-phone1').keyup(function(event){
mask(event,this);
});
jQuery('#edit-phone1').keydown(function(event){
mask(event,this);
});
});
click here to see working example:-
http://jsfiddle.net/yVdgL/38/
or you can try :-
$(document).ready(function() {
$('#edit-phone1').on("keyup keydown", function(e) {
mask(e, this);
});
});
link for this is:-http://jsfiddle.net/yVdgL/56/
In older, pre-HTML5 browsers, $("#phone").keyup( function ) or keydown is definitely what you're looking for.
In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form. $("#phone").bind('input',function);
You never defined event.
jQuery('#edit-phone1').keyup(function(){
jQuery('#edit-phone1').mask(event,this); //<-- what is event?
});
just add it
Second issue is you are treating window.mask like a jQuery plugin and it is not a plugin.
jQuery('#edit-phone1').keyup(function(event){ //<-- add event here
mask(event,this);
});

Prevent From Writing on TextArea using Bind Event "input propertychange"

I am handling the content inside a textarea using binding a function to the event "input propertychange"
Like this:
$('#textarea').bind('input propertychange', function () {
var textarea = document.getElementById('textarea');
window.lastLineWriting = textarea.value.substr(0, textarea.value.length).split("\n").length;
var writingOnLine = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
if (writingOnLine < window.lastLineWriting) {
//dont write on textarea
}
});
I don't know how to prevent the char typed by the user's keyboard to appear on the textarea... Inside that if I want to prevent the text to be inserted on textarea..
How can I do this?
you could easily stop the user from typing with this code, using jQuery:
$('textarea').bind('keypress', function (e) {
e.preventDefault();
return false;
});
NOTE:
this code will prevent the user from typing in all the textareas, to bind it specifically to one or some selected elements, you must change the selector to the desired elements.
var editable = false // Your Condition
if(editable != "true"){
$("#textarea" ).attr("disabled",true);
}

Multiple event listener in Javascript

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");

Categories