why can't I pass jquery objects as arguments in functions? - javascript

I'm trying to pass a jQuery selected object into a function, and the function will do a .html() on it.
Html:
<div id="box">this is a box</div>
Js:
var fillBox = function(box, text) {
box.html(text);
}
(function() {
var box = $("#box");
fillBox(box, "new text");
});
The box stays as "this is a box" and never gets updated, even tho the function is called. I even tried $(box).html(text) inside the function, but that doesn't fix it. Is this do-able?
http://jsbin.com/iqixoj/5/edit

You forgot a $.
$(function() {
var box = $("#box");
fillBox(box, "new text");
});

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

Unable to get the id of an element

The JSFiddle below is a simplified example of what I am trying to accomplish.
My code generates a. anchor element that is passed to a div.
I'd like it to return its id when double clicked but get an undefined instead.
Can anyone tell me what I am doing wrong?
JSFiddle
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(this.id);
}
The value of this depends on how you call the function.
Since you are calling bcd without an explicitly object (foo.bcd()) and are not in strict mode, the value will be equal to window (in a browser).
You are reading the id of the window, not the element.
Look at the e variable instead of this (since you pass it the element from the click event handler).
The parameter you are passing to the alert function is referenced as e, but you then attempt to alert this.id. this refers to the function calling the expression. Try this:
function abc() {
var myString = "<a onclick='bcd(this.id);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e);
}
Note that you also need to update the onclick() event to include the id property
The problem is you are alerting the id of this, which is not equal to e in the scope of the function. Change the function to
function abc() {
var myString = "<a onclick='bcd(this);' id='1'>krokodil</a>";
document.getElementById("output").innerHTML = myString;
}
function bcd(e) {
alert(e.id);
}
<button type="button" id="button" onclick="abc()">ADD</button>
<div id="output">kikker</div>
change
alert(this.id); to
alert(e)

Get Text of clicked link from a function

I want to start off by saying I'm not an expert, maybe not even an intermediate, user of jQuery and any and all help is appreciated.
Here is a simulation of my little problem:
https://jsfiddle.net/c897enhy/
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 2
</a>
<br>
<a id="someRandomID_hypNotifSentTo_0" class="NotifSent2" href = "#">
this is the text i want to get 3
</a>
if ($) {
$(document).ready(function () {
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
var x = $(this).text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
var x = $('#NotifSent2').toString();
alert(x);
var x = $(this).text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});
}
While, I am able to get the text of the active link from the "click" event, I am unable to do so from my second function.
The way the application works, is that the first function call ajax c# file, which then returns a success into the second jquery function with some results from c#.
I need to compare the results that are returned from the c# to what is inside the clicked hyperlink, but am unable to get the clicked text from within that "AjaxSuccess" function.
You're losing the the context of $(this) when you're in the Ajax function ($(this) will no longer refer to the clicked link). Try adding a variable that you can store the context in, like so:
$(document).ready(function () {
var $that;
$("a[id*='_hypNotifSentTo_']").live("click", function ($e) {
// Will post list of recipients to be removed from the file
$that = $(this);
var x = $that.text();
alert(x);
AjaxSuccessPopulateRecipients("restult");
});
function AjaxSuccessPopulateRecipients(result) {
alert("asdf");
//var x = $('#NotifSent2').toString();
//alert(x);
var x = $that.text();
alert(x);
var recipients = $(this).text();
alert("1");
var recipientArr = recipients.split(',');
}
});
$(this) inside the AjaxSuccessPopulateRecipients refers to the Widow object and not the anchor tag that was clicked.
Just send the reference of anchor tag from click event to the second function like this
AjaxSuccessPopulateRecipients("restult", $(this));
Use it as context like this
function AjaxSuccessPopulateRecipients(result, context) { // <--- context refers to the anchor tag
alert("asdf");
var x = $('.NotifSent2').text();
alert(x);
var x = context.text();
alert(x);
var recipients = context.text();
alert("1");
var recipientArr = recipients.split(',');
}
Take a look at Function.prototype.call().
The call() method calls a function with a given this value and
arguments provided individually.
Change:
AjaxSuccessPopulateRecipients("restult");
To:
AjaxSuccessPopulateRecipients.call(this, "restult");
Doing so will pass the correct this value to your function.
You should not able to access data via this $('#NotifSent2') selector as the # selector is JQuery syntax for finding an ID on the page, whereas your elements are constructed with class="NotifSent2".
If you wish to access a variable from a different function, you must ensure that the variable is within the correct scope.
Since your AJAX call and AjaxSuccessPopulateRecipients() function are within the same scope, you do not have access to $(this) across the two.
Simply pass the variable you wish to use to your function, as $(this) AjaxSuccessPopulateRecipients("restult", $(this));

How do I pass local variable value from one function to another?

In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element;
In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:
1) declare global variables and use them in my second function;
2) pass the variable value from first function to the second function and manipulkate this value from the second function
But the question is how to do I correctly pass the variable value from first function to second function:
Here is the code:
<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>
Javascript:
window.onload= function createEl(){
var el = document.createElement('p');
var x = document.getElementById('box');
var text = 'text';
el.appendChild(document.createTextNode(text));
x.appendChild(el);
}
function change(){
x.innerHTML="other text";
}
in general you can write this:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
this will alert "hello".
For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.
window.onload = function()
{
// do your normal stuff with creating elements
var anc = document.getElementById('ID of your a element here');
if(anc.attachEvent)
{
//code for ancient IE
anc.attachEvent('onclick', function(){change(x);});
}
else if(anc.addEventListener)
{
//code for modern browsers
anc.addEventListener('click', function(){change(x);});
}
}
function change(elem)
{
elem.innerHTML='other text';
}
Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.

Why is my jQuery plugin for removing text on focus and re-adding it on blur not working?

I would like the text in the value field of a text box to disappear when that text box gains focus, and then reappear in response to the eventual blur event - but only if the value is empty (that is, if the user hasn't entered anything after putting focus into the text box). So far, I have this:
this.each(function() {
obj = $(this);
var initialText = obj.val();
obj.focus(function () {
if(obj.val() === initialText)
obj.val("");
});
obj.blur(function () {
if(obj.val() ==="")
obj.val(initialText);
});
});
This plugin works if I have only one element in the page.
If I have two elements then it doesn't work. Why would this be?
The obj variable isn't scoped to the function, it's globally scoped, so there will only be one of them -- set to the last one that the plugin is applied to. Use the var keyword to scope the variable to the anonymous function alone so that there will be one for each thing that the plugin is applied to.
You'll want to write your plugin seperate from your code implementation.
Your plugin would look something like this:
(function($) {
$.fn.watermark = function() {
return this.each(function() {
var obj = $(this);
var initialText = obj.val();
obj.focus(function () {
if(obj.val() === initialText)
obj.val("");
});
obj.blur(function () {
if(obj.val() ==="")
obj.val(initialText);
});
});
};
})(jQuery);
Then to use your plugin:
$(document).ready(function() {
$('.watermark').watermark();
});
Additionally as tvanfosson you'll want to include the var keyword on your obj. If you don't have the var keyword on your obj declaration only the last textbox will have the watermark effect.

Categories