Passing values into a external function JQuery - javascript

I tried to create external general function for all my document. That function I want to use "this" method to work inside process of function and that "this" value come from difference buttons. But this code is not working for me. how to solve it out.
jQuery Code:
function myFunction(e){
var inp = $(this).val(), target = e.target, position = target.selectionStart;
inp = inp.replace(/a/g, "A");
inp = inp.replace(/i/g, "I");
inp = inp.replace(/u/g, "U");
inp = inp.replace(/e/g, "E");
$(this).val(inp);
$(this).get(0).setSelectionRange(position, position );
}
Send the value to external function using jQuery
$(document).ready(function(){
$('#Search').keyup(myFunction('#Search'));
});
HTML Code:
<form name="inputform">
<input class="Search" type="text" autofocus name="searchbox" id="Search" style="width:800px; height:200px;">
</form>
If I put directly text box id it is working fine.

Your function is a call back; jQuery passes the event information to your call back.
so when you do: $('#Search').keyup(myFunction('#Search'));
What's happening is (myFunction()('#Search'))(e) which isn't what you want. The e is the event information from the key up event listener that jQuery passes.
If you want to pass in '#Search' you can create a function that throws away this e and passes what you want inside, like this.
$('#Search').keyup(function(e){
myFunction('#Search');
});
But your function isn't listening for a string, its listening for the event information so you can do
$('#Search').keyup(myFuction)

You don't need to pass #Search as argument of myFunction like myFunction('#Search'). You can do it simply like following.
$('#Search').keyup(myFunction);

Related

How to get the value of an input button using this in jQuery

Thanks in advance for helping
Inside a function in a script, I'm trying to get the value of a button when it's clicked.
I just can't figure out the usage of "this" in that case.
There are a certain number of buttons in the page and several functions attached to them so I don't want to do jQuery('.A1').val() in the function each time a button is clicked.
I want the function to detect which button is clicked and its value
<script>
jQuery(document).ready(function(){
$.fn.dosomething = function(){
var currentval = $(this).val();
console.log(currentval);
};
});
</script>
<INPUT type="button" class="A1" value="blabla" onclick="jQuery().dosomething()"/>
The console returns 'undefined'
Thank you for your help
Dom
You need to pass current object this to the function like
<INPUT type="button"
class="A1" value="blabla"
onclick="jQuery(this).dosomething()"/>
DEMO
EDIT
Why are you using inline onclick? You can bind event to element also like
$(".A1").on("click", function () {
jQuery(this).dosomething();
})
DEMO 2
Try using the jquery click function rather than the on click inline HTML call.
http://api.jquery.com/click/
With $.fn.dosomething = function(), you have defined a plugin that can be called on a jquery object, but you pass nothing into jquery to serve as this.
Try:
onclick="jQuery(this).dosomething()"
Try this,
We can bind the function on particualr event for particular element.
jQuery(document).ready(function(){
$.fn.dosomething = function(cthis){
var currentval = $(cthis).val();
alert(currentval);
console.log(currentval);
};
$( "#myId" ).bind( "click", function() {
jQuery().dosomething(this);
})
});
</script>
<INPUT id="myId" type="button" class="A1" value="blabla" />
Demo
I think, the this inside the $.fn.dosomething refers itself rather than clicked button.

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.

onkeypress textbox issue

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/

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

Get the element triggering an onclick event in jquery?

I have a form where i've replaced the submit button with an input (with type=button) with an onclick which calls an existing function:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit();" type="button" value="Send" />
</form>
In the confirmSubmit, i'd like to be able to dynamically get the form object (to submit it), instead of having to hardcode the form's id, or pass it as part of the call to confirmSubmit(). I'd have thought that i could do this by first getting the dom element that was clicked on, ie something like this:
var form = $(this).parents("form");
where $(this) is the object that called the function, ie the input with the onclick. This doesn't work though. I think it would work if i'd set it up with the .click(function(){ syntax. Can i get the element that called the function in a different way?
EDIT - got the answer from #claudio below, for clarity here's the complete function and call:
<form accept-charset="UTF-8" action="/admin/message_campaigns" class="new_message_campaign" id="new_message_campaign" method="post">
<!-- some fields -->
<input onclick="confirmSubmit($(this));" type="button" value="Send" />
</form>
and the function itself. Note that 'jConfirm' is a method of the jquery-alerts plugin (http://abeautifulsite.net/blog/2008/12/jquery-alert-dialogs/) but that's not really relevant to this question - the key thing was just to get the form object, not what's subsequently done with it:
function confirmSubmit(caller) {
var form = caller.parents("form");
jConfirm('Are you sure?', 'Please Confirm', function(result){
if (result) {
form.submit();
} else {
return false;
}
});
}
You can pass the inline handler the this keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:
$('#sendButton').click(function(e){
var SendButton = $(e.target);
var TheForm = SendButton.parents('form');
TheForm.submit();
return false;
});
Try this
<input onclick="confirmSubmit(event);" type="button" value="Send" />
Along with this
function confirmSubmit(event){
var domElement =$(event.target);
console.log(domElement.attr('type'));
}
I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.

Categories

Resources