I have a select element which I’m creating through javascript (DOM)
var cell_stock_id = row.insertCell(0);
var cell_stock_id_sel = document.createElement('select');
I have kept an onchange javascript function for this-
cell_stock_id_sel.setAttribute("onchange","populateOtherFields");
The function gets called when i change the selected option in select.
Is there a way I can pass an argument to this function “populateOtherFields” ?
I have a select box and a lot of text fields in a table row. I want to populate those rows based on the selection. I’m able to access the data which has to be inserted in those fields, but I don’t know how to enter the data in those textfields for that row. I’m thinking of passing a unique number which will identify with the names of the elements in a row, and the javascript will parse that pattern in the names of the elements of the row.
document.forms["0"].elements[i].name.indexOf("pattern").
So is there a way by which i can pass this “pattern”, which is essentially the iteration (no. of rows, row number) number.
select__1, text__1, text2__1
select__2, text__2, text2__2
The ‘__1’ , and the ‘__2’ need to be passed. And they’re not static patterns. Could be any number.
Don’t use
setAttributeto set up event handlers, use direct assignment or (better)addEventListener/attachEventand then you can create a function that will call your function with the desired arguments. (You could do that anyway, of course, but usingsetAttributeyou’d either have to do it inline or create yet another global, named function.)Direct assignment:
Works on all browsers, but you can only have a single
changehandler on the element using this method (as withsetAttribute).addEventListener:This is the standard, but it doesn’t exist on older versions of IE.
attachEvent:This is IE-only (er, mostly, some browsers throw a bone to IE-only sites). It’s Microsoft’s pre-standard way of doing it. In IE8 and above in standards mode, you can use
addEventListenerinstead.Another advantage of all of these methods is that you don’t have to have any global functions, whereas the
setAttributeway, if you use a function name, that function has to be global. The global namespace on browsers is already really crowded, I always recommend avoiding adding to the clutter.Because of the various vagaries between browsers, I tend to recommend using any decent JavaScript browser library such as jQuery, YUI, Closure, or any of several others. These smooth over differences like the
addEventListener/attachEventthing and also provide a lot of helpful utility functionality.