Paste event not working as expected - javascript

I am trying out this simple code. What I want is that when a paste event is fired on the second input textbox, it should be cleared, after copying its contents, removing the readonly attribute of the previous textbox, and pasting it there. however, nothing is happening.
The paste event is fired alright, because if I replace the code in the timer by a simple alert, it works. Can anyone tell me what's wrong here?
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$(".boo").bind("input paste",function() {
elem = this;
setTimeout(function() {
$(".foo").removeAttr("readonly");
$(".foo").text($(elem).text());
$(elem).text("");
},100);
});
});
</script>
</head>
<body>
<input class = 'foo' type = 'text' /><input class = 'boo' type = 'text' />
</body>
</html>

First of all, you should use .val() instead of .text() with input control.
$(document).ready(function () {
$("input.boo").bind("paste", function () { //also changed the binding too
var elem = $(this);
setTimeout(function () {
$(".foo").val(elem.val());
elem.val("");
}, 100);
});
});
Also, your bound event(s) were fired twice when text is pasted in the control. That's because, you have bound both input and paste events to the element(s) with "boo" class.
So here, instead of:
$(".boo").bind("input paste", function() {});
Use this:
$("input.boo").bind("paste", function() {});
This will bind only the paste event to input elements with "boo" class.
See updated jsFiddle example.

Related

set value to a input and grab it on change or keyup

Check the html code bellow. The id foo input taking a text then cloning to another input id doo. As you can see in jquery code i am simply passing the value from foo to doo. But my problem is when i try to get value of doo on second part of code in jquery i dont get updated value of doo. Thing is that if i write input in foo then it virtually displays in doo but in real this not changing i think. So what i want is- when i pass input in foo it will also trigger in doo value. Since i am also updating doo from foo. Ask question if you want to know anything more. Thanks in advance
jsfiddle link
Jquery:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
});
$("#doo").on("change paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
Html:
<input type="text" id="foo" value=""><br>
<br>
<input type="text" id="doo" value=""><br>
The problem is that the functions are running at the same time and the value of doo hasn’t changed in time for the function. I would change your js code to this:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
$("#doo").on("paste keyup", function () {
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
});
And then obviously run whatever you would run in both places where you have the var tryGetNewValue running
The change event does not get triggered because only input directly from the user into the element can set it off (see https://developer.mozilla.org/en-US/docs/Web/Events/change).
As for a way to allow this to work, you can use a function for each event like so:
$("#foo").keyup(function () {
$('#doo').val($(this).val());
changeEvent();
});
$("#doo").on("change paste keyup", function () {
changeEvent()
});
function changeEvent(){
var tryGetNewValue = $('#doo').val();
console.log(tryGetNewValue);
}
It's better use deligate function of jquery. Both function change both input values.
$(document).on("input paste keyup","#doo,#foo", function (e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});
You can even get same thing like below to
$( "body" ).delegate( "#doo, $foo", "input paste keyup", function(e) {
$("#foo").val($(this).val());
$("#doo").val($(this).val());
var tryGetNewValue = $(this).val();
console.log(tryGetNewValue);
});

jQuery Change Color on click

I am a jQuery beginner and want to achieve the following - whenever I click on any element of the page, I want the color of the text inside it to be changed to red. This is what I have but it doesn't work. Surprisingly the alert statement also prints nothing. But it does executes as I tested it with another alert statement. Thanks.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>Cow</div>
<div>Cat</div>
<p>paragraph</p>
<p>coconut</p>
<script type="text/javascript" src="../Scripts/jquery-2.0.3.js"></script>
<script type="text/javascript">
$(this).click(function () {
var v = $(this).text();
alert(v); // this prints nothing !!!!
$(this).css("color", "red");
});
</script>
</body>
If you attach the click handler to the document, any click that bubbles up to the document will go to the event listener. If you now within the listener look for the event.target, that will be the node that initiated the event:
$(document).click(function (event) {
$(event.target).css("color", "red");
});
example: http://jsfiddle.net/E9H22/
If you specify the body element (in place of this), then it works:
$('body').click(function () {
var v = $(this).text();
alert(v); // this prints something, now.
$(this).css("color", "red");
});
JS Fiddle demo.
You could also, of course, use:
$(this.document.body).click(function () {
var v = $(this).text();
alert(v); // this prints something, now.
$(this).css("color", "red");
});
JS Fiddle demo.
If you want only the clicked-element to have its text turn red:
$('body').click(function (e) {
$(e.target).css("color", "red");
});
JS Fiddle demo.
$(this).click(function () {
This is your problem.
Instead of saying this, you need to use CSS selectors to specify which elements will change color.
For example, you could try
$('div').click(function() { // Will change the color of the divs
var v = $(this).text();
alert(v); // this prints nothing !!!!
$(this).css("color", "red");
});
$('p').click(function() { // Will change the paragraphs
...
});
$('p, div').click(function() { // Will work for either one!
...
});
$('*').click(function() { // Will work for any element on the page
...
});
In your
$(this).click(function () {
"this" doesn't refer to where the <script> tag is located, but rather it refers to window object. So in essence your code does this:
$(window).click(function (){
If you want the cow to turn red, when clicking it, change HTML to:
<div id="cow">Cow</div>
And your script:
// callback needs to be inside $(document).ready(fn) to make sure the DOM is ready when trying to use it
$(document).ready(function () {
// and we need to refer to an explicit element
$('#cow').click(function (){
// now we can refer to "this", since inside the click handler's context is the clicked element
$(this).css({color: 'red'});
});
}
You must specify to which element you wanna add a click event. E.g. this will work for all the div-elements:
$('div').click(function () {
$(this).css("color", "red");
});
You need to wrap that in a document ready statement, and attach the click listener to an actual element:
$(function(){
$("*").click(function () {
$(this).css("color", "red");
});
});
Your selector could look something like $("div, p").click(...) depending on which elements you want to be active.

Onclick button doesn't function

i try to create a button when the page is load.
<!DOCTYPE html>
<html>
<head>
<script>
function createButton(){
var newButton = document.createElement("button");
newButton.onclick="document.write('Tasto premuto')";
var textButton = document.createTextNode("Premi qui");
newButton.appendChild(textButton);
document.body.appendChild(newButton);
}
</script>
</head>
<body onload="createButton()">
</body>
</html>
the button is created succesfully, but the function that I have associated with onClick event doesn't work. any ideas?
onclick expects a function, not a string:
newButton.onclick = function() { document.write('Tasto premuto') };
Please see this jsFiddle
Of course, you should be aware that document.write() completely clears the DOM of all current content, rather than simply appending the string to the existing content.
You're assigning a string to function pointer:
Change:
newButton.onclick="document.write('Tasto premuto')";
To:
newButton.onclick= function(){ document.write('Tasto premuto') };

Maintain focus on an input tag

I'm trying to keep focus on an input element with this code:
<input onblur="this.focus()" />
But it doesn't seem to work.
If we just call .focus() right on blur event, it will restore focus, but actually there will be no text cursor. To handle this we have to let element to lose focus and then return it in few milliseconds. We can use setTimeout() for this.
$('#inp').on('blur',function () {
var blurEl = $(this);
setTimeout(function() {
blurEl.focus()
}, 10);
});
Here's working example. Be careful - you can't leave text field after you enter it =)
EDIT I used jQuery, but it can be easily done without it.
EDIT2 Here's pure JS version fiddle
<input type="text" id="elemID" />
<script type="text/javascript">
document.getElementById('elemID').onblur = function (event) {
var blurEl = this;
setTimeout(function() {
blurEl.focus()
}, 10);
};
</script>

Best way to modify an element that is not yet created

I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.

Categories