I have a class who has a method generating 100 input text.
And I want to add another method (to set a instance property for example) in these input text.
Here the code below :
<div id="container"></div>
<script type="text/javascript">
container = document.getElementById("container");
//Class :
function Foo(age)
{
//Attribute :
this.age = age;
//Setter :
this.setAge = function(age)
{
this.age = age;
console.log(this.age);
};
this.displayInputText = function()
{
for(var i = 0; i < 100; i++)
{container.innerHTML += '<input type="text" onkeyup="'+this.setAge(value)+';">';}
};
}
foo1 = new Foo(32);
foo1.displayInputText();
</script>
But onkeyup="'+this.setAge(value)+'" generates javascript error in console, so it doesn't work.
Have you an idea ?
Thank you, cordially.
this.setAge returns undefined, so your line translates to
{container.innerHTML += '<input type="text" onkeyup="undefined">';}
If you want to use whatever value given in this input box to be set as setAge then you need to use addEventListener.
var self = this;
for (var i = 0; i < 10; i++)
{
var inputEl = document.createElement( "input" );
inputEl.addEventListener("keyup", function(){
self.setAge( this.value );
});
container.append( inputEl );
}
Demo
<div id="container"></div>
<script type="text/javascript">
container = document.getElementById("container");
//Class :
function Foo(age) {
//Attribute :
this.age = age;
//Setter :
this.setAge = function(age) {
this.age = age;
console.log(this.age);
};
this.displayInputText = function() {
var self = this;
for (var i = 0; i < 10; i++)
{
var inputEl = document.createElement( "input" );
inputEl.addEventListener("keyup", function(){
self.setAge( this.value );
});
container.append( inputEl );
}
};
}
foo1 = new Foo(32);
foo1.displayInputText();
</script>
Related
I want the random string result(output) to display inside the text box so I can saved the value into my database.
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
output.innerHTML = generator.generate();
}, false);
});
})();
<p><button id="generate">Generate</button></p>
<p><code id="output"></code></p>
NOTE
Any idea on how to fix this? So when every time I click generate button the result will come out in a text box then save the value to my database.
(function() {
function IDGenerator() {
this.length = 4;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "TEST";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
$("#output").val(generator.generate());
}, false);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><button id="generate">Generate</button></p>
<input type="" id="output" name="">
Simply you can replace code tag by input tag
<p><input id="output" type="text" value="" /></p>
and replace output.innerHTML to be
output.value= generator.generate();
Hope that's help
I have to create an input box multiple times, so I call a function like this multiple times:
function __createInputBox(id) {
var input = document.createElement("input");
input.setAttribute('id', id);
input.setAttribute('type', 'number');
input.setAttribute('name', id);
input.setAttribute('value', '0');
input.setAttribute('min', '0');
return input;
}
In my main function, I append it as such:
var box = __createInputBox(id);
element.appendChild(box);
I keep getting this error:
__createInputBox is not defined
So are we allowed to return the value from document.createElement("element")? If its bad to do so, what is the better way to add multiple elements to the page?
This how I declare the function:
function InputSpace(){
this.inputSpace = document.getElementById("inputspace");
this.num = 1;
function __createInputBox(id) {
// function declared here
}
This is the code where I call it:
InputSpace.prototype = {
constructor: InputSpace,
drawInputSpace : function () {
var i = 0,
max;
var table = document.createElement("TABLE");
var table_body = document.createElement("TBODY");
for(max = num; i<num; i++){
var element = document.createElement("TR");
var box = __createInputBox(id);
element.appendChild(box);
table_body.appendChild(element);
}
table.appendChild(table_body);
this.inputSpace.appendChild(table);
}
After reading the comments, we can return document.createElement("element") in from a function. The reason for the function is undefined error, was because I was calling a function outside its scope. The proper way to call an object's private function is shown here
Changing the code to access private functions properly:
function InputSpace(){
// public attributes
this.inputSpace = document.getElementById("inputspace");
this.num = 1;
}
InputSpace.prototype = (function(){
// private functions
var __createInputBox(id){
var input = document.createElement("input");
input.setAttribute('id', id);
input.setAttribute('type', 'number');
input.setAttribute('name', id);
input.setAttribute('value', '0');
input.setAttribute('min', '0');
return input;
};
return {
constructor: InputSpace,
// public functions
drawInputSpace : function () {
var i = 0,
max;
var table = document.createElement("TABLE");
var table_body = document.createElement("TBODY");
for(max = num; i<num; i++){
var element = document.createElement("TR");
var box = __createInputBox(id);
element.appendChild(box);
table_body.appendChild(element);
}
table.appendChild(table_body);
this.inputSpace.appendChild(table);
}
})();
Here is my JavaScript code:
function foo(){
var pagingButtons = document.createElement('div');
for(var j = 0; j < pagingObjects.length; j++ )
{
var pagingBtn = CreateHTMLElement("btnPaging"+j.toString(), "btnPaging", ShowPage, 'button', pagingObjects[j].value);
pagingBtn.setAttribute('data-start', pagingObjects[j].start);
pagingBtn.setAttribute('data-end',pagingObjects[j].end);
pagingButtons.appendChild(pagingBtn);
}
}
pagingArea.appendChild(table).appendChild(pagingButtons);
}
function CreateHTMLElement(id, name, onclick, type, value) {
var HTMLElement = document.createElement('input');
HTMLElement.id = id;
HTMLElement.name = name;
HTMLElement.onclick = onclick;
HTMLElement.type = type;
HTMLElement.value = value;
return HTMLElement;
}
I need to get from pagingArea button with id=btnPaging0.
How can I implement it?
document.getElementById("btnPaging0");
I am working on a javascript library that will work like this: tex("element").print("hi"). Here is the code:
(function (window) {
var regex = {
Id : /^[#]\w+$/,
Class : /^[.]\w+$/,
Tag : /^\w+$/,
validSelector : /^([#]\w+|[.]\w+|\w+)$/
},
tex = function(selector){
//only some of the functions need to select an element
//EX:
// style: tex(selector).style(style);
//one that would not need a selector is the random number function:
// tex().random(from,to);
if (selector){
if (typeof selector === 'string'){
var valid = regex.validSelector.test(selector);
if( valid ){
if(regex.Id.test(selector)){
this = document.getElementById(selector);
}
if(regex.Class.test(selector)){
this = document.getElementByClass(selector);
}
if(regex.Tag.test(selector)){
this = document.getElementByTagName(selector);
}
}
}else if(typeof selector === 'object'){
this = selector;
}
//this = document.querySelector(selector);
// I could make a selector engine byt I only need basic css selectors.
}
};
tex.prototype = {
dit : function(){
this.innerHTML = 'Hi?!?!?!'
}
};
window.tex = tex;
})(window);
When I try to run the code I get an error that says, "Left side of argument is not a reference" referring to this = document.getElementById(selector);
Does anyone know what is wrong with my code?
Because you can not set this.
To do something that you are after, you just return this.
without using a prototype
var foo = function( selector ) {
this.print = function () {
console.group("in print");
console.log(this.elements[0].innerHTML);
console.groupEnd("in print");
return this;
}
this.printAll = function () {
console.group("in printAll");
for (var i=0; i<this.elements.length; i++) {
console.log(this.elements[i].innerHTML);
}
console.groupEnd("in printAll");
return this;
}
this.elements = document.querySelectorAll( selector );
return this;
}
console.group("id");
foo("#foofoo").print();
console.groupEnd("id");
console.group("class");
foo(".bar").printAll().print();
console.groupEnd("class");
JSFiddle
Basic example with prototype
(function () {
var basic = function (selector) {
this.elements = document.querySelectorAll(selector);
return this;
}
basic.prototype.print = function () {
console.group("in print");
console.log(this.elements[0].innerHTML);
console.groupEnd("in print");
return this;
}
basic.prototype.printAll = function () {
console.group("in printAll");
for (var i = 0; i < this.elements.length; i++) {
console.log(this.elements[i].innerHTML);
}
console.groupEnd("in printAll");
return this;
}
var foo = function (selector) {
return new basic(selector);
}
window.foo = foo;
})();
console.group("id");
foo("#foofoo").print();
console.groupEnd("id");
console.group("class");
foo(".bar").printAll().print();
console.groupEnd("class");
JSFiddle
Below is simple angular factory which almost works. I want to reset my model and I tried to add a method called 'resetModel' but it doesn't work as It is not resetting the model properties. Could someone please explain why?
app.factory('programLocationModel', [ "$rootScope", function ($rootScope)
{
var ProgramLocationModel = function()
{
this.name = "All Programmes";
this.description = "";
this.category = "";
this.series = {};
this.channel = {};
this.duration = "";
this.airTime = "";
this.seriesName = "";
this.url = "../assets/images/nhkw_thumbnail.jpg"; //Default client logo
}
ProgramLocationModel.prototype.update = function( data )
{
this.name = data.name;
this.description = data.description;
this.category = data.category;
this.series = data.series;
this.seriesName = data.seriesName;
this.channel = data.channel;
this.duration = data.duration;
this.airTime = data.airTime;
this.url = $rootScope.resturl + '/graph/' + data.id + '/thumbnail?access_token=' + $rootScope.token;
}
ProgramLocationModel.prototype.resetModel = function () {
ProgramLocationModel();
}
return new ProgramLocationModel();
} ] );
Your resetModel function is only calling the constructor and not doing anything to the actual instance the method is called on. Your resetModel function is supposed to modify the properties of this, just like you already do in the constructor and in your update method.
Here is a simple way to do it:
app.factory('programLocationModel', [ "$rootScope", function ($rootScope)
{
var ProgramLocationModel = function()
{
this.resetModel();
}
ProgramLocationModel.prototype.update = function( data )
{
this.name = data.name;
this.description = data.description;
this.category = data.category;
this.series = data.series;
this.seriesName = _seriesName;
this.channel = data.channel;
this.duration = data.duration;
this.airTime = data.airTime;
this.url = $rootScope.resturl + '/graph/' + data.id + '/thumbnail?access_token=' + $rootScope.token;
}
ProgramLocationModel.prototype.resetModel = function () {
this.name = "All Programmes";
this.description = "";
this.category = "";
this.series = {};
this.channel = {};
this.duration = "";
this.airTime = "";
this.seriesName = "";
this.url = "../assets/images/nhkw_thumbnail.jpg"; //Default client logo
}
return new ProgramLocationModel();
} ] );