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

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

Related

Passing values into a external function JQuery

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

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.

Toggle state of textbox with javascript using a button

I have a form as follows:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
And javascript code:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
What I basically want to do is to check what state (enabled/disabled) the textbox is in, and then toggle the state accordingly. I don't know if the javascript portion even uses the correct syntax to check if the textbox is disabled, but it's what I could think of.
Thanks in advance!
EDIT: Reason as to why I've chosen to use onmousedown instead of onclick to execute the event with the button:
I have chosen to use onmousedown instead of onclick as it makes the app I'm building feel less clunky due to the presence of this feature with onclick: When you click on a button and then drag the cursor away from the button while holding the mouse button down, and subsequently lift your finger off the mouse button when the cursor is in an area away from the button on the webpage, the event will not be executed. Hence, I've chosen to use onmousedown as this is overcome.
Use .prop(), Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element
$("#input").prop('disabled',!$("#input").prop('disabled'))
DEMO
I am not sure why you are using onMouseDown. Use click instead
$("#lock").on("click", function() {
$("#input").prop('disabled',!$("#input").prop('disabled'))
});
DEMO with click
To do it with jQuery try this:
$("#input").prop("disabled", function(i, v) { return !v; });
Your existing code doesn't work because DOM elements have a .disabled property, but jQuery objects do not.
I'm not sure why you're using onmousedown instead of onclick for the button, but either way if you're going to use jQuery I'd recommend removing the inline event attribute in favour of binding the handler with jQuery:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(You'd need to include that code either in a script block at the end of the body or in a document ready handler.)
Demo: http://jsfiddle.net/a7f8v/
You should append the event handler with jQuery instead of an onMouseDown event. The syntax could look like this:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
Example

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/

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