Dynamically generating a button using DOM and editing onclick event - javascript

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>

Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​

Try using h.push(...) instead of trying to send to a non created element in the array

var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

dynamically created list item onclick

I am completely new to HTML and JavaScript and I am completely lost.
I am trying to create a to do list where input adds to the top of the list, and when an item in the list is clicked, it is removed.
I am trying to avoid using JQuery or anything outside of pure js.
<!DOCTYPE html>
<html>
<script type="text/JavaScript">
var number_of_items = 0;
var list = [];
var list_container = document.createElement("div");
list_container.id = "container";
function makelist(){
list_container.innerHTML = "";
list.unshift(document.getElementById("todo").value);
++number_of_items;
document.getElementsByTagName("body")[0].appendChild(list_container);
var list_element = document.createElement("ul");
list_container.appendChild(list_element);
for( var i=0 ; i < number_of_items ; ++i){
var list_item = document.createElement("li");
list_item.innerHTML = list[i];
//The problem is here
list_item.onClick = function(){
alert("working");
list.splice(i, 1);
--number_of_items;
makelist();
}
list_element.appendChild(list_item);
}
}
</script>
<body>
Todo: <input type="text" id="todo">
<input type="button" value="Submit" onclick="makelist()" />
</body>
</html>
The problem is, the list_item onclick function never activates. Why?
I apologize in advance for any problems with the way I stated my question.
http://jsbin.com/wicopu/1/edit
use onclick instead of onClick...
or even better ... use event listeners

Show Multiplication Tables with a button

I want to make a page with JavaScript that has a button saying "Multiplication Tables." When I click the button, the multiplication table of 5 will show up in the "p" tag with the id "tables." I want to use a for loop to calculate the tables. Nothing is happening when I click the button.
HTML:
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
JavaScript:
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
table();
Check this snippet by clicking run snippet button below, I think it's working fine
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<html>
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
Your are missing html tag before body and there might be some problem with your javascript inclusion, Also don't run table() function after declaring it.
Place the script either in head tag or before closing the body. Remove table() function calling after declaring it.

Generate input button with onClick function using JavaScript DOM

I use JavaScript to generate form input fields on my page. Everything works fine, except the button. I came across some problems generation the button's onClick function using DOM. You can see the code below, but on my page, there is no the onClick function as the attribute of the input button tag:
n = 1;
function generate() {
var radiomore = document.createElement("input");
radiomore.type = "button";
radiomore.name = "opt[" + n + "]";
radiomore.value = "Add more options";
radiomore.setAttribute = ('onClick',addradiomore);
var div = document.createElement("div");
div.innerHTML = "Op: " + radiomore.outerHTML + "<br/>";
document.getElementById("mydiv").appendChild(div);
n++;
}
function addradiomore() {
//here goes the function code
}
And this is what it generates on my page:
<input type="button" name="opt[1]" value="Add more options">
There is no function?!?!
P.S.
Even if I use like this it doesn't work:
radiomore.onclick = addradiomore();
You should use this:
radiomore.onclick = addradiomore;
DEMO
What about:
radiomore.onclick = function () {
addradiomore();
};

Having a difficulty adding a new form in each new <div>

In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});

Categories