how to pass Id to javascript dynamically - javascript

function jsarea3() { document.getElementById("Txtarea3").title = document.getElementById("Txtarea3").value; }
function jsarea4() { document.getElementById("Txtarea4").title = document.getElementById("Txtarea4").value; }
function jsarea5() { document.getElementById("Txtarea5").title = document.getElementById("Txtarea5").value; }
The code above is to show data in a textbox area on mouse hover.
as you can see the code that run is same for all the 3 function the difference is only the ID
How can I pass ID dynamically
Like I can use the inner code as function as well for all the 3 and how to use it
and what about code like this the code given below
$('#button1').focus(function () {
$('#button1', window.parent.document).css("background-color", "#fcc63b");
}
});

if you are using jquery you can select your textareas like this
$("textarea").focus(function(){
this.title = $(this).val();
});
you can specify the selector to be more specific to the items that you want to manipulate
the function will be running when your textarea gain focus
take a look at jquery it's simplify your code

Since you use the same elements title and value you can store a reference instead of searching for it twice..
function jsarea(anId) {
var elem = document.getElementById(anId);
elem.title = elem.value;
}
and you can call it with jsarea('Txtarea3');
For the second code, it is jQuery code and it seems to change the background color of a button with the same id as the one that gets the focus in the parent window (when you use iframes)

You can use a single function which takes a parameter representing the id of the the element you wish to reference:
function jsarea(elementId) {
document.getElementById(elementId).title = document.getElementById(elementId).value;
}
You can call this like jsarea("Txtarea3"); if you want to affect the element with id "Txtarea3".

Use a parameter.
In addition, you should take a look at jQuery - it can really simplify DOM-manipulating code.

function jsarea(number) { document.getElementById("Txtarea" + number).title = document.getElementById("Txtarea" + number).value; }

Related

Variable not working on div created in jQuery

This is simple code which works fine, but I want to figure it out how to set a variable for novy.fadeIn(2000).
For example one day will my js file had 300 lines and I want to change variable from one place -> fadeIn to fadeOut or something like that.
var novy = $('<div/>', {id:'namaste'});
var text = {textAlign : 'center', color : '#fff', fontSize: 'xx-large'}
// var example = novy.fadeIn(2000) this is not working
novy.appendTo('body').text('this code is .ITCHI.').css(text).hide();
$(document).on('click', function(){
novy.fadeIn(2000); // example;
})
For better view please look here: https://jsfiddle.net/t305qap2/
The example you give is a little far-fetched for me, but to achieve what you are asking, you can do one of two things:
Wrap common code in a dedicated function
var fade = function (element, duration) {
element.fadeIn(duration);
}
This will let you call fade(novy, 2000) and exchange the underlying animation call as you need it.
Store the function, not the result, in a variable
You see, the reason why var example = novy.fadeIn(2000) isn't working is because it stores the result of calling fadeIn on that element, which is the element itself. fadeIn merely has the side-effect of animation. If you want to store a reference to the function instead of the result, JS allows this. See here:
var novyFader = novy.fadeIn // typeof novyFader === 'function' => true
novyFader.call(novy, 2000)
You want to assign the line to a function and store it as a variable. you can then change the function to a different value in the future
so create a clickFunction like this that returns a function
var clickFunction = function() { return function(){novy.fadeIn(2000);} }
Now change your on click to this
$(document).on('click', clickFunction);
At this time your code should work the same.
In the future you can assign clickFunction to some other function like
clickFunction = function() { return function() {novy.fadeOut(2000);} }
But you might also have to set the document.on callback again
HTH

My EventListener to a button continues to fire despite ownership being changed, why? (JavaScript)

I have a function, which at the end of its task assigns a button to a new id.
function altChecker() {
var doc = document,
out = [],
appButton = doc.getElementById('appButton'),
//re = /click-me/gi,
output = doc.createElement('p');
output.setAttribute('id', 'output');
EventUtility.addHandler(appButton, 'click', function(e) {
//I have not included all the function details to concentrate on the question
appButton.id = 'appButtonNextChecker';
var appButtonNextChecker = doc.getElementById('appButtonNextChecker');
nextChecker(appButtonNextChecker);
});
}
function nextChecker(newBtnName) {
EventUtility.addHandler(newBtnName, 'click', function(e) {
$('#output').innerHTML = "";
console.log('next Checker, button!')
});
}
So basically there is one button in the DOM assigned to appButton ID initially, and then I change it doing:
appButton.id = 'appButtonNextChecker';
when the altChecker function fires...
Then I assign the button to a new variable, and pass in the variable to the next function...
var appButtonNextChecker = doc.getElementById('appButtonNextChecker');
nextChecker(appButtonNextChecker);
While I can see the buttons' ID change in the DOM, and I see the console.log fire in the nextChecker function,
$('#output').innerHTML = ""; //doesn't fire
AND the altChecker function fires as well (again)?! Haven't I severed the connection to the click function when I reassigned the new ID?
Any help would be appreciated!
Javascript doesn't remember that you initially attached the event through it's id. The event is attached to the element itself, not the ID. It's not like CSS that way.
In fact your variables are still holding the same element as well, so there's no need to create a new variable after changing the ID, either. Since you're using jQuery you can just type $(appButton).unbind(); to remove the event handler. You may also want to look into .on() and .off()
The problem is that you're trying to use the innerHTML property in a jQuery's object.
That property belongs to Element, and it will not work in the way you're using it.
You can use the document.getElementById method, and it will work fine:
document.getElementById('output').innerHTML = '';
Or you can use jQuery's html method:
$('#output').html('');
And you can even use the first element of the jQuery's array, and use innerHTML again:
$('#output')[0].innerHTML = '';
It's up to you, but the first option will be faster, for sure.

Appending a new file upload button when the previous changes

I have a function that uses jQuery to add in an additional file upload button when a user adds a file. My problem is that I cannot seem to have it either add in proper format or add every time. My current function simply tries added the string directly:
jQuery(document).ready(function($) {
$(function() {
$("input:file").change(function(){
$("input:file").after("</td></tr><tr><td class=\"field_name span4\"><strong></strong></td><td class=\"field_option\"><input type=\"file\" name=\"pictures\">");
});
});
});
You can see a live version of this here: http://1ro.co/salem/?module=insert
The issue with the method shown above is it does not add the first two closing tags: </td></tr>.
I've tried methods such as setting $("input:file"); to a variable, however that doesn't set for every value after the first. For example:
var count = 0;
jQuery(document).ready(function($) {
$(function() {
var input = $("input:file");
input.change(function(){
input.after(input.get(count++));
});
});
});
However this doesn't append at all (in theory would probably append every element), and I cannot use .after() on input.get(count).
In simple terms, I'm looking to improve this and make it so it will append the a new file upload button, and not being formatted improperly. If possible, I would rather use method 2 but at the moment I would like for it to just work.
You'll need to re-add the handler to each new file input, so best to isolate that in a function:
var addfile = function() {
var newRow = $("<tr><td class=\"field_name span4\"><strong></strong></td>" +
"<td class=\"field_option\"><input type=\"file\" name=\"pictures\">").
insertAfter($(this).closest('tr'));
newRow.find('input:file').change(addfile);
};
$("input:file").change( addfile );
I just tried out your live demo and it is inserting something. But it only happens once of course as your event handler is bound only to the first object.
I would try your change function using something like the following:
$('input:file').change(function() {
$(this).closest('tr').after($(this).closest('tr').clone());
});
but your change handler will have to be rebuilt as well.

How can I add a link to dynamically created button?

Once the buttons are created, is there anyway I can add a link or use window.location method like this: `window.location = 'nextpage.html?foo=number'. I currently have this
var typeValue = location.search;
var typeStringValue= typeValue.replace("?type=","");
var containers = typeValue.replace("?type=multi","");
var containersValue = parseInt(containers);
var sampleLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function createButton(buttonName){
var buttonDivBlock = document.getElementById("sampleSets");
var buttonElement = document.createElement("input");
buttonElement.setAttribute("type","button");
buttonElement.setAttribute("name",buttonName);
buttonElement.setAttribute("value","Sample Set"+" "+buttonName);
buttonElement.setAttribute("id",buttonName);
buttonDivBlock.appendChild(buttonElement);
// document.getElementById(sampleLetter[i]).setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
}
function setButtons(numberOfContainers){
for(i=0;i<numberOfContainers;i++){
createButton(sampleLetter[i]);
}
}
window.onload = function(){
setButtons(containersValue);
}
But document.getElementById("'"+sampleLetter[i]+"'").setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
returns a null value.
Well, maybe I can help you along with an example:
function getFive() { return 5;}
callOtherFunction("stringArgument", getFive());
The second argument to callOtherFunction is going to be 5, not the getFive function. In many cases, like adding event listeners and AJAX code, you actually want to pass the function itself as an argument, so it can be called later. But if you don't want to bother declaring that function seperately, it looks like this:
callOtherFunction("stringArgument", function() { return 5; });
To make code look cleaner, you can press Enter after the { and make a multi-line function.
Now, all that in mind, take another look at the line you've commented out. Do you see what's missing? (PS. Apologies for the "egging-on" format - I find people get much better at figuring things out if I help them find the solution, rather than just showing it to them)
The sampleLetter variable is not defined where you are trying to use it (judging by commented code). Use the value you had just set to the id attribute a few lines earlier.
document.getElementById(buttonName).setAttribute( /* ... */ );
Or if you are trying to set it in the loop instead of in the createButton function, do not add the single quotes
document.getElementById(sampleLetter[i]).setAttribute( /* ... */ );

What method do use when adding a jquery collection to a jQuery collection?

So I tried this:
var allItems = jQuery();
function additems(items) {
allItems = allItems.pushStack(items);
}
additems(jQuery("#ul1").find("li").first());
additems(jQuery("#ul2").find("li").first());
additems(jQuery("#ul3").find("li").first());
allItems.each(function() {
jQuery("ul1").append(this);
});
She doesn't work in jsFiddle.
What I need is to keep a collection of some <LI> items hopefully in a jQuery object. And i'd like it to use a function passing in a jQuery object. I also need to add to the collection inside a function like what I have above so it can be done at different times in the code.
i know i can get around it by something like:
function additems(items){
items.each(function(){ allItems.pushStack(this);});
}
or by just sending them as a list of HTML <LI> Elements, but I'd rather do it something like the above and I haven't found a clean and efficient way of doing this.
Thanks!
PS: I'd rather not need a plugin.
UPDATE
let me explain more. I have one function that does something and it has an <ul> element from which i can pull out the <li> elements.
I then want to send these elements to another function to keep them for later.
function doSomething1()
{
//Do something
var ulElement = getFromSomewhere();
additems(jQuery(ulElement).find("li"));
// do something else
return;
}
function additems(items)
{
MyObject.allItems.pushStack(items)
}
the jsFiddle was Simplified compared to my code.
new jsfiddle with "#" fixed http://jsfiddle.net/LPkkT/8/
ANSWER
Upon adding Quincy's answer to my fiddle in a way that didn't remove all my code i got:
var allItems = jQuery();
function additems(items) {
allItems = allItems.add(items);
}
additems(jQuery("#ul1").find("li").first());
additems(jQuery("#ul2").find("li").first());
additems(jQuery("#ul3").find("li").first());
allItems.each(function() {
jQuery("ol").append(this);
});
And this works.
Firstly, if you want to select by id, you have to add a '#' in the selector.
And you can add jquery collections using the add() method
var allItems =
jQuery("#ul1").find("li").first()
.add(jQuery("#ul2").find("li").first())
.add(jQuery("#ul3").find("li").first());
allItems.each(function() {
jQuery("ol").append($(this));
});
http://jsfiddle.net/LPkkT/4/
Can't you get the collection of items just by using a jQuery selector?
If you mark your items with a class you can get a collection with one simple selector

Categories

Resources