Jump to content

Defining parameters through js to be sent by html event


Ioan

Recommended Posts

What is the best simple way to get javascript to tell html what value to pass to a function on click?
The elements that hold the click event are created through javascript so I can't simply type in the parameters
The actual goal is to have an "add" button in html that adds a new object with user defines attributes. The objects are automatically stored in an array so I can use loops. Then all the objects are displayed in some type of text field. The user should be able to click on each item in the text field which fills editable text boxes with that object's attributes.
Everything seems to work, except the part when the user clicks on an object to display its attributes
in javascript:
function selected(i){     //this works if I hardcode a number instead of using i     document.getElementById("inName").value = arr_items[i].Name;//puts a name into the value of a textbox with id "inName"}function showAll(){     var i;     var outputName = "";     var l = arr_items.length;//the length of the array that holds objects     var size = 0;     for(i = 0; i < l; i++)//loop through all the items in the array     {          outputName += "<option id="+i+" onClick="+selected(i)+">"+arr_items[i].Name+"</option>";//tell html to create a new option tag, which should call a function with parameter i on click     }     document.getElementById("outName").innerHTML = outputName;//converts the string outputName to HTML code}
in HTML:
<select id="outName" class="out" size="20"></select>

i'm new to this so maybe there are some useful keywords or tags that I don't know?

Edited by Ioan
Link to comment
Share on other sites

Hmmm... selected seems to be a reserved word...

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>title</title><style>form{border:1px solid #bbb;width:200px;margin:10px;}</style><script>window.onerror = function(a, b, c, d){alert('Javascript Error:n'+a+'nURL: '+b+'nLine: '+c+'  Column: '+d);return true;}</script><script>'use strict';var arr_items = [];window.onload = init;function init(){  arr_items = document.getElementById('form1').getElementsByTagName('INPUT');  showAll();}function select(i){     document.getElementById("inName").value = arr_items[i].name;//puts a name into the value of a textbox with id "inName"}function showAll(){     var i;     var outputName = "";     var l = arr_items.length;//the length of the array that holds objects     var size = 0;     for(i = 0; i < l; i++)//loop through all the items in the array     {          outputName += "<option value=""+ i +"" onClick="select("+ i +")">"+ arr_items[i].name +"</option>";     }     document.getElementById("outName").innerHTML = outputName;//converts the string outputName to HTML code}</script></head><body><form id="form1"><input type="text" name="inp01"/><input type="text" name="inp02"/><input type="text" name="inp03"/><input type="text" name="inp04"/></form>inName:<input type="text" id="inName"/><br/><select id="outName" class="out" size="20"></select></body>    </html>
Link to comment
Share on other sites

it's an array filled with objects. When the user presses a button it creates a new object at the end of the array. What's in the object comes from what is currently in the text box

 

<input type="button" class="bt" id="add" onmousedown="add()" value="Add" />

var arr_items = new Array;function obj_item(N) //the object has more than just Name in it but i simplified it here{    this.Name = N;}function add(){	arr_items[arr_items.length] = new obj_item(document.getElementById("inName").value);//comes from a text box in html	showAll();//display everything in arr_items in a clickable text box}
Edited by Ioan
Link to comment
Share on other sites

the first problem I'm seeing here is that inside that forloop on the 1st post is that you're not tying a function to the onClick hander for the option tag, but RUNNING the function and putting the result (null) as the onclick handler for each option tag. next is that if you trying to create actual elements with behaviors its best not to use things like innerHTML or document.write() but things like document.createElement() and appendchild()This is my personal preference as doing so avoids so many bugs stemming from string concatenation confusion, like what you have here. finally your not showing us why your doing the things your doing...like why are you trying to wipe all the properties of an object via obj_item()? here is my implementation using OOP and also reducing overhead

    //tell javascript that we plan to have an object exist in the global space.    // we won't tell whats gonna be inside it yet cause the page needs to load firstvar optionForm={};window.onload = function(){    //after page is loaded you can now access the document.stuff    // so lets construct optionForm	optionForm = {    //lets set the elements that we plan to refer to as properties of the optionForm     // object so that we don't need to re-find them again and again every time we call add().    // plus it encapsulates this data so nothing else in the global space needs to know or    // confuse these variable with something else.		input:document.getElementById("inName"),		select:document.getElementById("outName"),    //for now, this is the ONLY function you need		add:function(){    //create a new option element			var op = document.createElement("option");    // set both the val variable and the option's innerHTML to the current input's value			var val = op.innerHTML = input.value;    //now place the option element inside the document, at the end inside the select element			select.appendChild(op);			op.onClick = function(){    //using closures, whenever the option is clicked on it should be able to grab the same     //name from this closure scope. no need to grab the innerhtml or use an array to store names				input.value = val;			}		}	};}now change the button html's onclich handler...<input type="button" class="bt" onmousedown="optionForm.add()" value="Add" />

See how much string manipulation I used? zero, zip, nada and I was still able to perform the same functionalities which I assume you're after, yet making it easier to expand upon, avoiding a number of potential bugs.now it shouldn't be hard if you continue this work and implement your own remove function.

 

Link to comment
Share on other sites

Ill try to do what Hadien said. It's a bit out of my level to understand but looks simple.

 

This is the page I have so far. I want to be able to select items to make the edit and delete functions. There are also buttons to sort by name, id, rating etc. Then there is a save and load button that sends the arr_items to localStorage so it doesn't dissapear ever time the page is refreshed (those already work).

 

hkJXC.png

Link to comment
Share on other sites

if you think it looks simple or that you can follow it then it shouldn't be out of your level, for some tricks I use in the code I give some comments about them so you can read up on those if they catch your interest. I expanded the code I gave based on what I see in here, though I don't have the time to test it before class. and I'm not sure how you intend "Find Closest" to work

//tell javascript that we plan to have an object exsist in the global space.// we won't tell what gonna be inside it yet cause the page needs to load firstvar optionForm={},Items = [];//Item doesn't mess with the document so we can define it right away and// we'll treat it as a classvar Item=function(ID, NAME, COST, WEIGHT, RATING){	//private variables	var id=null,name=null,cost=null, weight=null,rating=null;	//public variables and methods	var this = {		setId:function(x){if(typeof x === "number"){id = x;}},		id:function(){return id},		setName:function(x){if(typeof x === "string"){name = x;},		name:function(){return name},		setCost:function(x){if(typeof x === "number"){cost = x;}},		cost:function(){return cost},		setWeight:function(x){if(typeof x === "number"){weight = x;}},		weight:function(){return weight},		setRating:function(x){if(typeof x === "number"){rating = x;}},		rating:function(){return rating}	};	this.setId(ID);	this.setName(NAME);	this.setCost(COST);	this.setWeight(WEIGHT);	this.setRating(RATING);	return this;}window.onload = function(){	//after page is loaded you can now access the document.stuff	// so lets construct optionForm	optionForm = {		input:{			id:null, // no element to set the ID			name:document.getElementById("inName"),			cost:document.getElementById("inCost"),			weight:document.getElementById("inWeight"),			rating:document.getElementById("inRating")		},		select:{			id:document.getElementById("outId"),			name:document.getElementById("outName"),			cost:document.getElementById("outCost"),			weight:document.getElementById("outWeight"),			rating:document.getElementById("outRating")		},				sortButton:{			id:document.getElementById("sortId"),			name:document.getElementById("sortName"),			cost:document.getElementById("sortCost"),			weight:document.getElementById("sortWeight"),			rating:document.getElementById("sortRating")		}		//this is the ONLY function you need		add:function(item){			if (typeof item !== "object"){				item =  new Item(					Items.length,					this.input.name.value,					this.input.cost.value+0,					this.input.weight.value+0,					this.input.rating.value+0				);			Items.push(item);			}						for (var index in this.input){							//create a new option element				var op = document.createElement("option");				// set the option's innerHTML to the current item's input type value				op.innerHTML = item[index]();				//now place the option element inside the document, at the end inside the select element				this.select[index].appendChild(op);				//to keep the code pretty clean and so I can still take advantage of closures I use an anonymous function				// call to preserve the closure scope. notice that I wrap the original function inside another function and				// then wrap THAT in parenthesis and run it using that last pair of parenthesis.				op.onClick = (function(){					var self = this, i = index, v = this.input[index].value;					return function(){this.input[i].value = v;};				})();			}		},		edit:function(){			//see if you can write this function		},		remove:function(){			//see if you can write this function		},		clearDisplay:function(){			for (var sel in this.select){				//empty out the input text boxes				if (this.input[i])					this.input[i].value = "";				//empty out everything in the select				while (this.select[sel].firstChild) {				    this.select[sel].removeChild(this.select[sel].firstChild);				}			}			for (var i in this.input){			}		},		sortBy:function(select,asc){			var newSort = [];			var oldItems =Items;			for(var index = 0;oldItems.length>0;index = 0){								for (var oldinx in oldItems){					if(     asc&&(oldItems[oldinx][select]<oldItems[index][select])						|| !asc&&(oldItems[oldinx][select]>oldItems[index][select])){						index = oldinx;					}						}				newSort.push(oldItems.pop(index));			}			Items = newSort;//overwrite Items			this.clearDisplay();//clear the display                        // populate the selects			for (var i in Items){				this.add(Items[i]);			}		},		save:function(){			localStorage.Items = Items;		},		load:function(){			Items = localStorage.Items;                        // populate the selects			for (var i in Items){				this.add(Items[i]);			}		}	};	for (var header in  optionForm.sortButton){		 optionForm.sortButton[header].onclick = (function(){		 	var up = false;		 	return function(){		 	    optionForm.sortBy(header,up!= up);		 	}		 })();	}	// now see if you can put all the other onclick handlers in your application here	// ****    // ****	// hint: except for clearDisplay, each function in optionForm should link to a event handler}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...