How do I add parameters to an event handler in javascript? - javascript

and thanks for looking.
Currently I am implementing code from this example. In my aspx file, I have Label1 and Textbox1 defined. In my aspx.cs file, I am setting the Label1.Text property to a random string in the Page_Load method.
In the .js file I have included, I have:
var Label1, TextBox1;
Sys.Application.add_init(AppInit);
function AppInit(sender) {
Label1 = $get('Label1');
TextBox1 = $get('TextBox1');
$addHandler(Label1, "click", Label1_Click);
$addHandler(TextBox1, "blur", TextBox1_Blur);
$addHandler(TextBox1, "keydown", TextBox1_KeyDown);
}
Now, I want to add more labels (and corresponding textboxes), but I do not want the overhead of defining separate handlers for each of the additional events, i.e. I want to avoid this:
$addHandler(Label1, "click", Label1_Click);
$addHandler(TextBox1, "blur", TextBox1_Blur);
$addHandler(TextBox1, "keydown", TextBox1_KeyDown);
$addHandler(Label2, "click", Label2_Click);
$addHandler(TextBox2, "blur", TextBox2_Blur);
$addHandler(TextBox2, "keydown", TextBox2_KeyDown);
...
How can I pass a parameter to the handler that will identify the sender accurately, and have the handler use 'this' or something. Also of note, I want to be able to identify the index of the Label (1,2,3...) because I have to edit the corresponding textbox as well. FOr instance, the current implementation of Label1_Click looks like this:
function Label1_Click() {
TextBox1.value = Label1.innerHTML;
Label1.style.display = 'none';
TextBox1.style.display = '';
TextBox1.focus();
TextBox1.select();
}
Thanks, you guys.

Well, $addHandlers can help speed up the process of adding handlers... also, in JS you can attach miscellaneous data to objects by doing: Label1["somenewproperty"] = value; and so you can attach certain attributes and check in the event handlers... that does take up resources though, so be careful how much you do this...
On some level, how is JS supposed to know the objects you want to listen to and what order the objects are in, to reduce the amount of code? Maybe storing an array of textboxes and labels, and referring to those objects by index, but on some level, you can't get away from certain plumbing code.
HTH.

You can try creating a delegate. For example with your labels:
function AppInit(sender) {
$addHandler(Label1, "click", Function.createDelegate(this, LabelClick());
$addHandler(Label2, "click", Function.createDelegate(this, LabelClick());
}
function LabelClick(sender)
{
/..
}

I know this is an old question but yesterday I faced this very same problem and here is the solution I came of with.
I don't like it a lot but haven't found an easier way: I use a custom CssClass for every label I want to be linked with a textbox by this method (and the same for the textbox).
Then I iterate them and attach the corresponding handler depending on if it is a label or a button.
var labels;
var texts;
Sys.Application.add_init(AppInit);
function AppInit(sender) {
labels = document.getElementsByClassName('lblDynamic');
texts = document.getElementsByClassName('txtDynamic');
for (i = 0; i < labels.length; i++)
{
$addHandler(labels[i], "click", Label1_Click);
}
for (i = 0; i < texts.length; i++) {
$addHandler(texts[i], "blur", TextBox1_Blur);
$addHandler(texts[i], "keydown", TextBox1_KeyDown);
}
}
The next step is to access the generic control inside the method handler. This is quite easy with the this reference. Example:
function TextBox1_KeyDown(event) {
if (event.keyCode == 13) {
event.preventDefault();
this.blur();
}
}
But there is a problem here: How do I know that a certain label pairs with a certain textbox? I use a very similar id for both controls. ASP will add it's viewstate weird nomenclature after rendering the page so I need to use very dirty tricks to get rid of the extra text. Then I iterate the textbox controls and if one matches the label on the handled event then I can work with them like in the example you posted:
function Label1_Click()
{
var offset = this.id.indexOf('lbl') + 3;
for (j = 0; j < texts.length; j++)
{
if (texts[j].id.substring(offset) == this.id.substring(offset))
{
texts[j].value = this.innerHTML;
this.style.display = 'none';
texts[j].style.display = '';
texts[j].focus();
}
}
}
In this case my label and textbox are declared this way. Note the very similar nomenclature:
<asp:Label runat="server" CssClass="lblDynamic" ID="lblExerciseName">My Text</asp:Label>
<asp:TextBox runat="server" CssClass="txtDynamic" ID="txtExerciseName" Style="display: none;" />
Hope it helps :)

there are many ways, but this one works perfectly in any browser and you don't need a library.
I append an onclick handler to every input on this page and give it 2 parameters, that I get from a 2-dimensional array. I used a closure to make sure the handler still has access to the given parameters. I also made me a global object (p from page), so I don't clutter the global namespace with variables.
<!DOCTYPE html>
<html>
<head>
<script>
var p = {
onload: function() {
var btns = document.getElementsByTagName("input");
var parameters = [["btn1 p1", "btn1 p2"], ["btn2 p1", "btn2 p2"]];
for(var i = 0, ceiling = btns.length; i < ceiling; i++) {
btns[i].onclick = function(par1, par2) {
return function() {
p.btnOnclick(par1, par2);
};
}(parameters[i][0], parameters[i][1]);
}
},
btnOnclick: function(par1, par2) {
alert("par1: " + par1 + " | par2: " + par2);
}
};
</script>
</head>
<body onload="p.onload()">
<input type="button" value="button1"/>
<input type="button" value="button2"/>
</body>
</html>

Related

Javascript - remove button and parent

Hi I am just learning Javascript and after following some tutorials I thought it would be nice to practise some Javascript by making stuff.
So now I am trying to make a very easy to-do-list. Just for practise, but I get stuck.
I managed to add items with a remove-button to an UL with JS. But, BUT:
How do I make it so; when you click on the removeMe button, that only that Li will be removed?
What should I use?
Here's my code:
var buttonAdd = document.getElementById('but1');
var buttonRemove = document.getElementById('but2');
var ul = document.getElementById('myUl');
function addLi() {
var newLi = document.createElement('li');
var removeThis = document.createElement('button');
var textInput = document.getElementById('inputText').value;
if(textInput === ""){
alert('Add text');
}else{
newLi.innerHTML = textInput;
newLi.appendChild(removeThis);
removeThis.innerHTML = "Remove me";
removeThis.setAttribute("onClick", "removeMe(this);");
ul.appendChild(newLi);
}
}
buttonAdd.onclick = function() {
addLi();
};
buttonRemove.onclick = function() {
ul.innerHTML = "";
};
function removeMe(item){
//get called when clicked on the remove button
}
and my HTML:
<body>
<ul id="myUl"></ul>
<input id="inputText" type="text"><br />
<button id="but1">Add stuff</button><br />
<button id="but2">Remove all</button>
</body>
Thanks
The function remove() is a brand new DOM 4 method and not very widely supported yet. The clunky, but bulletproof way would be:
function removeMe(item){
item.parentElement.parentElement.removeChild(item.parentElement);
}
or with a bit more elegance:
function removeMe(item){
var parent = item.parentElement;
parent.parentElement.removeChild(parent);
}
http://jsfiddle.net/BtbR4/
Also be careful with this:
removeThis.setAttribute("onClick", "removeMe(this);");
Handing a function reference as a string is always a bad idea for several reasons (eval'ing the string, messing up the scope). There are several better options:
removeThis.onclick = removeMe;
or if you need to hand over parameters
removeThis.onclick = function(){removeMe(your,parameters)};
The best option however is to attach eventhandlers always like this:
Element.addEventListener("type-of-event",functionReference);
You just need to remove the parent node (the li), as I've shown using jsbin.
function removeMe(item){
item.parentNode.remove();
}
Please note Blue Skies's comment that this may not work across all browsers, an alternative is:
var par = item.parentNode; par.parentNode.removeChild(par);
a cleaner way to do things is to add
removeThis.onclick = removeMe;
and
function removeMe(mouseEvent){
this.parentNode.remove();
}
This is consistent with how you add the other onclick functions in your code. Since you said you are learning js, it is a good idea to learn how events and functions work. So, the take away from this is that the 'this' of a function that is attached to an object is the object itself (the removeThis object in this case), and event handlers give you access to the event that invoked them (mouseEvent) in the argument list.
JSfiddle: http://jsfiddle.net/QT4E3/

Adding target="blank" to links with javascript

I'm attempting to add target="_blank" to links on a page depending on a checkbox click.
On the javascript side I have:
function newTab(v) {
if(v.tab.checked == true) {
document.getElementsByTagName('a').setAttribute('target', '_blank');
} else {
document.getElementsByTagName('a').setAttribute('target', '_self');
}
} //end function
And on the HTML side I have:
<form>
<input type="checkbox" name="tab" onclick="newTab(this.form)" />
<label>Open Links In New Tab?</label>
</form>
Gmail
Naturally it isn't as simple as I thought it would be, so it doesn't work.
The page contains over a dozen links so I need the checkbox to apply to all links on the page - why I used getElementsByTagName(). Any help appreciated!
EDIT:
Code that works is as follows:
function newTab(f) {
var els = document.getElementsByTagName('a'); //read anchor elements into variable
if(f.tab.checked == true) { //If the box is checked.
for (var i in els) {
els[i].setAttribute('target', '_blank'); //Add 'target="blank"' to the HTML
}
} else { // not checked...
for (var i in els) {
els[i].setAttribute('target', '_self'); //Add 'target="self" to HTML
}
}
} //end function.
getElementsByTagName() returns a nodeset. You need to iterate over it and apply the change to each one in turn. What you currently have is more like jQuery syntax, which handles this internally for you.
This would have shown up in the console. With JS issues, always check the console before wondering what's wrong.
var els = document.getElementsByTagName('p');
for (var i=0, len = els.length; i<len; i++)
els[i].setAttribute('name', 'value');
Also, with checkboxes use change, not click events, as someone might toggle them via the keyboard, not mouse. Lastly, you should look into handling your events centrally, not inline DOM-zero events specified in the HTML. Numerous reasons for this that are beyond the scope of this question.

How to remove style one click event?

How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.

AJAX: Applying effect to CSS class

I have a snippet of code that applies a highlighting effect to list items in a menu (due to the fact that the menu items are just POST), to give users feedback. I have created a second step to the menu and would like to apply it to any element with a class of .highlight. Can't get it to work though, here's my current code:
[deleted old code]
The obvious work-around is to create a new id (say, '#highlighter2) and just copy and paste the code. But I'm curious if there's a more efficient way to apply the effect to a class instead of ID?
UPDATE (here is my updated code):
The script above DOES work on the first ul. The second ul, which appears via jquery (perhaps that's the issue, it's initially set to hidden). Here's relevant HTML (sort of a lot to understand, but note the hidden second div. I think this might be the culprit. Like I said, first list works flawlessly, highlights and all. But the second list does nothing.)?
//Do something when the DOM is ready:
<script type="text/javascript">
$(document).ready(function() {
$('#foo li, #foo2 li').click(function() {
// do ajax stuff
$(this).siblings('li').removeClass('highlight');
$(this).addClass('highlight');
});
//When a link in div is clicked, do something:
$('#selectCompany a').click(function() {
//Fade in second box:
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getFileInfo.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectCompanyUser').html(msg)
$('#selectCompanyUser').fadeIn(400);
}
});
});
});
</script>
<div id="selectCompany" class="panelNormal">
<ul id="foo">
<?
// see if any rows were returned
if (mysql_num_rows($membersresult) > 0) {
// yes
// print them one after another
while($row = mysql_fetch_object($membersresult)) {
echo "<li>"."".$row->company.""."</li>";
}
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($membersresult);
// close connection
mysql_close($link);
?>
</ul>
</div>
<!-- Second Box: initially hidden with CSS "display: none;" -->
<div id="selectCompanyUser" class="panelNormal" style="display: none;">
<div class="splitter"></div>
</div>
You could just create #highlighter2 and make your code block into a function that takes the ID value and then just call it twice:
function hookupHighlight(id) {
var context = document.getElementById(id);
var items = context.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
items[i].addEventListener('click', function() {
// do AJAX stuff
// remove the "highlight" class from all list items
for (var j = 0; j < items.length; j++) {
var classname = items[j].className;
items[j].className = classname.replace(/\bhighlight\b/i, '');
}
// set the "highlight" class on the clicked item
this.className += ' highlight';
}, false);
}
}
hookupHighlight("highliter1");
hookupHighlight("highliter2");
jQuery would make this easier in a lot of ways as that entire block would collapse to this:
$("#highlighter1 li, #highlighter2 li").click(function() {
// do ajax stuff
$(this).siblings('li').removeClass('highlight');
$(this).addClass('highlight');
});
If any of the objects you want to click on are not initially present when you run this jQuery code, then you would have to use this instead:
$("#highlighter1 li, #highlighter2 li").live("click", function() {
// do ajax stuff
$(this).siblings('li').removeClass('highlight');
$(this).addClass('highlight');
});
change the replace in /highlight/ig, it works on http://jsfiddle.net/8RArn/
var context = document.getElementById('highlighter');
var items = context.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
items[i].addEventListener('click', function() {
// do AJAX stuff
// remove the "highlight" class from all list items
for (var j = 0; j < items.length; j++) {
var classname = items[j].className;
items[j].className = classname.replace(/highlight/ig, '');
}
// set the "highlight" class on the clicked item
this.className += ' highlight';
}, false);
}
So all those guys that are saying just use jQuery are handing out bad advice. It might be a quick fix for now, but its no replacement for actually learning Javascript.
There is a very powerful feature in Javascript called closures that will solve this problem for you in a jiffy:
var addTheListeners = function (its) {
var itemPtr;
var listener = function () {
// do AJAX stuff
// just need to visit one item now
if (itemPtr) {
var classname = itemPtr.className;
itemPtr.className = classname.replace(/\bhighlight\b/i, '');
}
// set the "highlight" class on the clicked item
this.className += ' highlight';
itemPtr = this;
}
for (var i = 0; i < its.length; i++) {
its[i].addEventListener ('click', listener, false);
}
}
and then:
var context = document.getElementById ('highlighter');
var items = context.getElementsByTagName ('li');
addTheListeners (items);
And you can call add the listeners for distinct sets of doc elements as many times as you want.
addTheListeners works by defining one var to store the list's currently selected item each time it is called and then all of the listener functions defined below it have shared access to this variable even after addTheListeners has returned (this is the closure part).
This code is also much more efficient than yours for two reasons:
You no longer iterate through all the items just to remove a class from one of them
You aren't defining functions inside of a for loop (you should never do this, not only for efficiency reasons but one day you are going to be tempted to use that i variable and its going to cause you some problems because of the closures thing I mentioned above)

Script to enable/disable input elements?

I'm wondering if it's possible for a script to enable/disable all input elements on the page with some sort of toggle button.
I googled it but didn't find anything too useful except for this:
http://www.codetoad.com/javascript/enable_disable_form_element.asp
but I'm not sure how to edit it for the toggle.
Something like this would work:
var inputs=document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=true;
}
A working example:
$().ready(function() {
$('#clicker').click(function() {
$('input').each(function() {
if ($(this).attr('disabled')) {
$(this).removeAttr('disabled');
}
else {
$(this).attr({
'disabled': 'disabled'
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type='text'></input>
<input type='text'></input>
<input type='text'></input>
<div id='clicker' style='background-color:#FF0000; height:40px; width:100px;'></div>
Here is a function to toggle all inputs on the page:
function toggle_inputs() {
var inputs = document.getElementsByTagName('input');
for (var i = inputs.length, n = 0; n < i; n++) {
inputs[n].disabled = !inputs[n].disabled;
}
}
It works by using the logical NOT operator (the exclamation point), which returns the opposite of the operand. For example, !true will return false. So by using !inputs[n].disabled, it will return the opposite of what it's currently set to, thereby toggling it.
If you need code to bind the click event to the button:
document.getElementById('your_button_id').onclick = toggle_inputs;
You can also use addEventListener, but see the linked page for more information, including compatibility with Internet Explorer. The code I gave above should work across all browsers with no trouble.
for (var i = 0; i < document.getElementyByTagName('input').length; i++) {
document.getElementsByTagName('input')[i].disabled = 'disabled';
}
http://code.google.com/p/getelementsbyclassname/
^^Robert Nyman has a "get elements by class" script. Basically you'd just assign all those input elements to the same class, and then do something like:
//Collapse all the nodes
function collapseNodesByClass(theClass){
var nodes = getElementsByClassName(theClass);
for(i = 0; i < nodes.length; i++){
nodes[i].style.display='none';
}
}
This is a piece of code I'm actually currently using to collapse everything with a given class name (it uses the script I mentioned above). But in any case I think the key to your problem is being able to refer to multiple elements at once, which that script will help you with.
Also the link in your question didn't work for me :(.

Categories

Resources