onkeypress textbox issue - javascript

I have this:
<input type="text" ID="txtMy" name="txtMy" onkeypress="initialize();"/>
And in my .js file I have:
initialize()
{
var x = $("#txtMy").val();
}
But, if I have '2' in my textbox, and then I enter 4, the value of x is still 2. How to resolve this?

Use keyup
Here is how you do that in the unobtrusive way.
HTML
<input type="text" id="txtMy" />
Script
$(function(){
$("#txtMy").keyup(function (event) {
alert($(this).val())
});
});
Working Sample : http://jsfiddle.net/VmELF/4/
If you want to bind the functionality to a text box which is being injected to the DOM after the dom load( possible by an Ajax call etc...), you may use jQuery on
$(function(){
$("body").on("keyup","#txtSearchKey",function (event) {
alert($(this).val())
});
});

Your spelling of initialize in the onkeypress does not match the declaration (inititalize).

keydown and keypress events both execute BEFORE the entered key has actually appeared in the text box. If you want to get the new value of the input after the key has appeared, use the keyup event instead.
<input type="text" ID="txtMy" name="txtMy" onkeyup="initialize();"/>
initialize()
{
var x = $("#txtMy").val();
}
You should consider binding your event handlers in javascript using .on(), since you're using the library anyways. Keeping your logic (javascript) seperated from your view (html) is a good habit to get in to.

instead of markup event handler you can use jquery:
var x;
$("#txtMy").on("keyup", function(){
x = $(this).val();
alert(x);
})

A few things:
Use the keyup event. keypress is firing before the character is recorded.
Your initialize() function is misspelled in your HTML snippet.
See the working jsfiddle at http://jsfiddle.net/8XTLW/1/

Related

blur event doesn't trigger at first attempt

I'm trying to update the DOM based on the value entered in a text box.
HTML:
<input id="event-name" type="text"/>
JQUERY:
$('#event-name').on('blur',function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
this works on the first blur in Chrome. When I tried it in opera, mozilla and edge it doesn't worked on the first attempt.
It worked when I added this before the jquery.
$("#event-name").focus();
$("#event-name").blur();
$("#event-name").focus();
I did this to make the first $.post call to occur when the page opens.
Why is this problem happening?
How to solve this in a proper way?
Please help!
You can try this code:
var lazyTriggerEvent = function(id,event,callback){
var searchTrigger=null;
$("#"+id).bind(event,function(){
var text = $.trim($(this).val());
clearTimeout(searchTrigger);
searchTrigger = setTimeout(function(){
callback(text);
},500);
})
};
//use keyup event
lazyTriggerEvent("event-name","keyup",function(){})
It often happens with elements across browsers that consequent events do not work when binding an event to them through ID or class. The following solution should help you:
$(document).on('blur','#event-name', function(){
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Alternatively, you could use keyup event. You can do so following:
$(document).on('keyup','#event-name', function(){
var eventName = $(this).val();
$.post("scripts/add-team-support.php",{eventName : eventName},function(minAndMaxString){
//my code here
});
});
Also, using - in IDs is not a good approach. Rather, either stick to camelCase or underscore_format of naming convention.

Call onclick attribute programatically and talk to the event parameter

I have read the other post relating to this matter. Unfortunately it has not resolved my problem. I am happy to use jQuery, so I am looking for the cleanest solution.
I have radio buttons defined as follow:
a = 5;
input.value = "myButton";
input.onclick = (function (a) {
return function (e) {
changeSelectedRadio(e.srcElement, a);
};
})(a);
I need to be able to execute this when user click on the radio button (this works fine), and programatically.
I have tried:
$("input[type='radio'][value='myButton']").triggerHandler("click");
$("input[type='radio'][value='myButton']").click();
Both produce the same result: e (the event parameter) does not exist.
$("input[type='radio'][value='myButton']").onclick();
Does not work
Changing the input.onclick to input.click also did not work. When the use click, the function does not get triggered.
Thanks
If you're using jquery already, might as well build the inputs that way:
var input = $('<input value="something">').click(function(){
var elem = $(this); // the element clicked, as a jquery obj
alert(elem.attr('id');
});
$('body').append(input);
$('input').trigger('click');
Adjust the selectors as needed, and you'll need to actually append the elements to the DOM, but it'll work.
try this:
$("input[type='radio'][value='myButton']").bind( "click", function() {
alert( "clicked" );
});
What is passed to the function is a jQuery event, not a native event. You can use the target element to get at the source that was clicked on or use this to reference the properties of the object directly. See fiddle at http://jsfiddle.net/YQh3Q/
<p><input id="foo1" name="foo" type="radio" value="0" checked="checked"> Foo1</p>
<p><input id="foo2" name="foo" type="radio" value="1"> Foo2</p>
(function ($) {
var input = document.getElementById("foo2");
var a = 5;
input.value = "myButton";
input.onclick = (function (a) {
return function (e) {
alert(e.target + '|' + this.id);
};
})(a);
$("input[type='radio'][value='myButton']").each(function() {
$(this).trigger("click");
});
})(jQuery);
Alternatively (and probably better) you can use a pure jQuery solution
$(function() {
var a = 5;
$('input#foo2').on('click', function() {
changeSelectedRadio(this, a);
})
.val('myButton');
$("input[type='radio'][value='myButton']").trigger('click');
});
Its best to use addEventListener() you can add all types of events. example: "click", "mousemove", "mouseover", "mouseout", "resize" and many more. the false at the end is to stop the event from traversing up the dom. If you want parent dom objects to also receive the event just change it to true. also this example requires no javascript libraries. This is just plain old javascript and will work in every browser with nothing extra needed.
Also addEventListener() is better than onClick() as you can add an unlimited number of event listeners to a dom element. If you have an onClick() on an element and then set another onClick() on the same element you have overwritten the first onClick(). Using addEventListener() if i want multiple click events to trigger when i click on an element i can do it with no problem.
If you want data about the element that is triggering the event you can pass the event to the function. You will see in my example function(e) e is the event and you can use e or this to target the element that is being triggered. Using e or this i can also get more data about the triggered event. for example if the event was a mousemove or mouseclick i can get the x and y position of the mouse at the time of the event.
<!DOCTYPE html>
<html>
<head>
<title>exampe</title>
</head>
<body>
<a id="test" href="">test</a>
<script>
document.getElementById("test").addEventListener("click",function(e){
alert('hello world');
alert('my element '+e);
alert('my element '+this);
},false);
</script>
</body>
</html>
if you want to have addEventListener call a function just change the 2nd value to the function name like this.
document.getElementById("test").addEventListener("click",f1,false);
this will execute the function
function f1(){ ... }
When you want to remove an event listener just call target.removeEventListener(type, listener[, useCapture]). Very simple and easy to manage.

Adding onClick event dynamically using jQuery

Due to a plugin being used, I can't add the "onClick" attribute to the HTML form inputs like usual.
A plugin is handling the forms part in my site and it doesn't give an option to do this automatically.
Basically I have this input:
<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
I want to add an onClick to it with jQuery onload for it to be like this:
<input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
How do I go about doing this?
I know this might not be standard practice but seems like the easiest option to do in my situation.
I'm a newbie to jQuery so any help is very much appreciated.
You can use the click event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
http://api.jquery.com/click/
You can use the on event bound to "click" and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on event bound to "click" and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the
selected elements.
http://api.jquery.com/on/
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641
$("#bfCaptchaEntry").click(function(){
myFunction();
});
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");
as #Selvakumar Arumugam suggested, but the function call on registering also
$('#bfCaptchaEntry').on('click', myfunction);,
rather than use
$('#bfCaptchaEntry').on('click', () => { myfunction});

Event at value changed using jquery.val()

I have an <input type="text"> that have you value updated for many other scripts jQuerys, using the method .val("value here"). I need a new script to be run when the value of input has been updated. How to associate an event that'd make it for me?
Here is my code:
$('#PedidoTotalDescontoPadrao').change(function()
{
console.log('test');
});
but it doesn't work
I think you're using the wrong event handler for what you need.
Try this one.
http://api.jquery.com/keyup/
The change() method does not applies to <input type="text"> html tags. you may wan't to do it with keyup().
$('#PedidoTotalDescontoPadrao').keyup(function() {
console.log('test');
// and this is how you'd trigger the other events you want
$('.something').trigger('click');
});

How to apply jQuery function .one() to element through attribute 'onclick'

I want to clear an input field when it's clicked, but only the first time you click. With jQuery, you can achieve it like this: putting the following snippet anywhere in the document (assuming the element with id=inputf has already been loaded):
$('#inputf').one("click", function() {
$(this).val("");
});
As you can see in the above snippet, the input field must have id attribute with value inputf.
But is there a way to move that snippet to the onclick attribute of the input field, like
<input type="text" onclick="$(this)....val('')" />
? It looks like I can't use the function .one(), because that function needs a string containing one or more JavaScript event types. But I just want .one() to be executed each time it is called, without specifying one or more event types.
Only posting this since you requested, I don't advocate inline handlers.
<input type="text" onclick="this.onclick = null; this.value = ''; " />
http://jsfiddle.net/aUmNK/
<input type="text" onclick="if(flagCount === 0){this.value='';flagCount++;}" />
declare the var flagCount = 0 as global variable in the script tag in head.
If you wanted to do it for all text input fields, you could do:
$("input[type=text]").each(function(){
$(this).one("click", function() {$(this).val = "";});
});
...or you can refine the selector to get every input field in a particular div for example:
$("#divId input[type=text]")
You don't need jQuery to do a event like one on the element tag. Just do something like this:
<input onclick="function(event) { /* do something */ this.onclick = function(){}; }" />
Your function will be executed only the first time, then a new void function will be attached to the onclick event callback.
You can just write your own simple jQuery plugin:
(function( $ ) {
$.fn.clearOnce = function() {
this.one("click", function() {
$(this).val("");
});
};
})( jQuery );
After this you can:
<input type="text" onclick="$(this).clearOnce();" />
Wrote in 3 min, not tested ;-)

Categories

Resources