I made a table that you can add text to and edit it inside it.
However if you add more than three rows, It is stuck and not working anymore.
The errors comes from here:
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
It is only adding event listener to the last row added, so if you add more than one row. The not last row won't have a working edit button.
I checked the IDs by inspecting the edit and update buttons elements.
Try adding 3 rows then click on the edit button for one of the row.
you can look at the code here and also https://jsfiddle.net/3e6d4qsv/
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<form id="myForm">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" type="text" placeholder="Your email..."></input>
</form>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
var form = document.getElementById("myForm");
form.reset();
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td id=acvda'+ z + '>' + x + '</td><td id=zcvda' + z + '>' + y + '</td></tr>';
var h = '<button style="margin-left:8px" class="edit" id=vda' + z + '>Edit</button>';
var f = '<div id=zzza'+z+' style=height:10px></div>';
var abc = '<button style="margin-left:-36px" class="update" id="cvda'+z+'">Update</button>';
var total = h + abc + f;
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click', doSomething);
document.getElementById('cvda' + z).addEventListener('click', doSomething2);
document.getElementById('cvda' + z).style.visibility='hidden';
z = z + 1;
}
function doSomething() {
document.getElementById("inptext").value = document.getElementById("ac"+this.id).innerHTML;
document.getElementById("inpadress").value = document.getElementById("zc"+this.id).innerHTML;
document.getElementById(this.id).style.visibility='hidden';
document.getElementById('c'+this.id).style.visibility='visible';
}
function doSomething2() {
document.getElementById("a"+this.id).innerHTML = document.getElementById("inptext").value;
document.getElementById("z"+this.id).innerHTML = document.getElementById("inpadress").value;
document.getElementById(this.id).style.visibility='hidden';
form.reset();
var edit = this.id;
var edit2 = edit.replace("c", "");
document.getElementById(edit2).style.visibility='visible';
}
</script>
</body>
</html>
The following line remove all your listeners:
document.getElementById("buttons").innerHTML =
document.getElementById("buttons").innerHTML + total;
document.getElementById('vda' + z).addEventListener('click',
doSomething);
use this instead:
var div = document.createElement('div');
div.innerHTML = total;
document.getElementById("buttons").appendChild(div);
Related
i have been watching some questions here about the same topic but i cant make my code works with the solutions,
I have a dynamic tr table, what i want to do is when i write on the last input of each row a div "result" overwrite like the values, that because i want to make later a connection that shows me users name on my db, like a data live search
JS
function createTable() {
var a;
var r;
a = document.getElementById('tb1').value;
var length = document.getElementById('table').rows.length;
if (a == "") {
alert("Please enter some numeric value");
} else {
var change = document.getElementById("trow1").style.visibility = 'visible';
//var change = document.getElementById("trow2").style.visibility = 'visible';
var changet = document.getElementById("table").style.visibility = 'visible';
var rows = "";
for (var i = 0; i < a; i++) {
r=i+length;
let tr = document.createElement("tr");
tr.innerHTML = "<td>"+r+"</td><td><input type='text' id='" + "parameter".concat(r) + "'></td><td id='tdlmin'><input type='text' id='" + "lmin".concat(r) + "'></td><td id='tdlmax'><input type='text' id='" + "lmax".concat(r) + "'></td><td><input type='text' id='" + "level".concat(r) + "'></td><td><select id='" + "relcal".concat(r) + "' style='width:100%;'><option value='NA'>NA</option><option value='SI'>SI</option></select></td><td><input type='text' id='" + "comment".concat(r) + "' cols=100></td><td><input type='text' id='" + "procown".concat(r) + "' onkeyUp='document.getElementById('result').innerHTML = this.value;'></div></td>";
document.getElementById("table").appendChild(tr);
}
}
}
HTML
<div class="container-fluid">
<div class="row align-items-start">
<div class="col-9">
Numero de Parametros: <input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Crear</button>
<table id="table" class="order-table table" name="table1" required style="visibility:hidden;">
<tr id="trow1" style="visibility:hidden; text-align: center;"><td>#</td><td>Parametro</td><td colspan="2"><table><tr><td colspan="2">Limite</td></tr><tr><td>Min.</td><td>Max.</td></tr></table></td><td><table style="width: 100%;"><tr><td>Nivel</td></tr><tr><td>1 - 4</td></tr></table></td><td>Relevante Calidad</td><td>Comentario</td><td>Dueño del Proceso</td></tr>
</table>
<button type="button" onclick='subir()'>Subir Parametros</button>
</div>
<div class="col-3">
<div id="result" name="result"></div>
</div>
</div>
</div>
Edit:
This is what i have tried yet:
$('"'+procownid+'"').on("keyup",function(){
var userlike = document.getElementById(procownid).value;
alert(userlike);
});
$("#table tr").on('keyup', procownid, function({
var userlike = document.getElementById(procownid).value;
alert(userlike);
result.innerHTML="<p>"+userlike+"</p>"
});
alert(userlike);
document.getElementById('result').innerHTML="<p>userlike:"+uselike+"</p>";
$.post('getUser',{accion:"ListarUserTPMD",userlike:userlike}, function(data){
result.innerHTML=data;
});
my question is, i can get that when i write on the input it trigger the onkeyup and show me for example the input.value, why i cant make it write on the div?
This question already has answers here:
How to get the selected radio button value using js
(19 answers)
Closed 5 years ago.
I have a set of dynamically generated radio buttons against each data of the list but I am not able to get the checked radio button value. Please help!!
function displayList()
{
var arr=["Apple", "Banana", "Grapes"];
var list
var output="";
var output2="";
var output3="";
var output4="";
for(var i=0; i<arr.length; i++)
{
list=arr[i];
output+= '<input type="checkbox" value='+list+' name="box2">' + ' ' + list+' '+'<br><br>';
output2+= 'yes:<input type="radio" value="yes" name="box2'+i+'">'+'no:<input type="radio" value="yes" name="box2'+i+'">'+'<br><br>';
output3+= '<button type="button" id="myBtn" onclick="displayCardList()" >Add Prompt</button>'+'<br><br>';
//onclick="myfunction()"
output4+= '<button type="button" id="mySaveBtn" onclick="addEntity()" >Save </button>'+'<br><br>';
document.getElementById("List").innerHTML=output;
document.getElementById("radioBtn").innerHTML=output2;
document.getElementById("myBtn").innerHTML=output3;
}
}
<html>
<body onload="displayList()">
<div class="row">
<div class="col-sm-4"><div style="font-size:16px" id="List"> </div></div>
<div class="col-sm-4"><div style="font-size:16px" id="radioBtn"></div></div>
<div class="col-sm-4"><div id="myBtn"></div></div>
</div>
</body>
</html>
But first, let me separate content
I recommend using template tag to separate JavaScript from HTML, as you should always do.
You can then insert as many items using that template, as you wish. As you can see below it's quite tedious using pure JavaScript. I'd recommend using Handlebars.
var getRadioValue = function(name) {
var radios = document.getElementsByName(name);
for (var i = 0, length = radios.length; i < length; ++i) {
if (radios[i].checked) {
return radios[i].value
}
}
return null;
};
var Actions = {
addPrompt: function(i) {
var value = getRadioValue('fruit-fresh-' + i);
if (value == "no") {
prompt('Why is ' + fruits[i] + ' not fresh? Explain:');
}
else if (value == "yes") {
alert('We are glad that ' + fruits[i] + ' is fresh! Good job!');
}
else {
alert('Please, check the corresponding value for ' + fruits[i] + ' freshness!');
}
},
save: function(i) {
alert('Saving: ' + fruits[i]);
},
generateMarkupForFruit: function(i, fruitName) {
var template = document.querySelector('#fruits-template');
var row = document.importNode(template.content, true);
var fruitId = 'fruit-' + i,
fruitField = row.querySelector('.fruit'),
fruitLabel = row.querySelector('.fruit-label');
fruitField.value = fruitName;
fruitField.setAttribute('id', fruitId);
fruitLabel.textContent = fruitName;
fruitLabel.setAttribute('for', fruitId);
var yesId = 'fruit-yes-' + i,
noId = 'fruit-no-' + i,
groupId = 'fruit-fresh-' + i,
yesField = row.querySelector('.yes'),
yesLabel = row.querySelector('.yes-label'),
noField = row.querySelector('.no'),
noLabel = row.querySelector('.no-label');
yesField.setAttribute('name', groupId);
yesField.setAttribute('id', yesId);
yesLabel.setAttribute('for', yesId);
noField.setAttribute('name', groupId);
noField.setAttribute('id', noId);
noLabel.setAttribute('for', noId);
var addPromptBtn = row.querySelector('.add-prompt-btn'),
saveBtn = row.querySelector('.save-btn');
addPromptBtn.addEventListener('click', Actions.addPrompt.bind(null, i));
saveBtn.addEventListener('click', Actions.save.bind(null, i));
return row;
}
};
var fruits = ["Apple", "Banana", "Grapes"];
var table = document.querySelector('#fruits');
for (var i = 0; i < fruits.length; ++i)
{
var row = Actions.generateMarkupForFruit(i, fruits[i]);
table.appendChild(row);
}
#fruits {
width: 100%;
border-collapse: collapse;
}
#fruits td,
#fruits th {
border: solid 1px;
padding: 0.25em;
}
#fruits th {
color: #fff;
background: #000;
}
#fruits .actions {
text-align: center;
}
#fruits .actions .save-btn {
font-weight: bold;
}
<table id="fruits">
<tr>
<th>Fruit</th>
<th>Is fruit fresh?</th>
<th>Actions</th>
</tr>
</table>
<template id="fruits-template">
<tr>
<td>
<input type="checkbox" class="fruit">
<label class="fruit-label"></label>
</td>
<td>
<input type="radio" class="yes" value="yes">
<label class="yes-label">Yes</label>
<input type="radio" class="no" value="no">
<label class="no-label">No</label>
</td>
<td class="actions">
<button type="button" class="add-prompt-btn">Add Prompt</button>
<button type="button" class="save-btn">Save</button>
</td>
</tr>
</template>
I am trying to pass the value of an input a user provides to a bootstrap table. User provides a name and a score. Currently it is being displayed right below the table instead of within it. How would I go about doing this. I've tried to append it using javascript but cant seem to figure it out. Thanks
You have to append data you have in rankings to the table as rows trs using the following line :
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td>'
+ rankings[i].score + ' pts</td></tr>');
Note : Add $('table tbody').empty() before the loop to reset table content.
Hope this helps.
$(document).ready(function() {
var scoreboard;
var rankings = [];
var displayScoreboard = function(rankings) {
var rankPosition = 1;
var tieScore = 0
var previousScore = 0;
$('#rankings').html('')
$('table tbody').empty();
for (var i = 0; i < rankings.length; i++) {
if (i > 0 && rankings[i-1].score !== rankings[i].score) {
rankPosition = rankPosition + tieScore +1;
}
$('table').append('<tr><td>' + rankPosition + '</td><td> ' +rankings[i].name + '</td><td> ' + rankings[i].score + ' pts</td></tr>')
}
}
var sortRankings = function(rankings) {
rankings.sort(function(a, b) {
return b.score-a.score;
});
};
$('#add').on('click', function() {
var playerName = $('#eq-name').val();
var playerScore = $('#eq-score').val();
if (playerName.length > 0 && playerScore.length > 0) {
var playerStats = {name: playerName, score: playerScore};
rankings.push(playerStats);
sortRankings(rankings);
displayScoreboard(rankings);
$('#eq-name').val('');
$('#eq-score').val('');
} else {
alert("Please enter a name and a score");
}
});
$('#clear').on('click', function() {
$('#rankings').html('');
rankings = [];
});
});
.eq-input {
display:block;
text-align:center;
vertical-align:middle;
width:100%;
height:100%;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8">
<title>EverQuoteTest</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.scss">
</head>
<body>
<div class="container eq-input">
<input type="text" id="eq-name" placeholder="Name">
<input type="number" id="eq-score" placeholder="Score" min=0>
<br>
<br>
<button class="btn btn-success" id="add">Add To Rankings</button>
<button class="btn btn-danger" id="clear">Clear Rankings</button>
<a id="add-game" class="btn btn-default ">Add Game</a>
</div>
<div class="container">
<div class="col-md-8 col-md-offset-4">
<h3>Leaderboard</h3>
</div>
<table class="table" border="1">
<thead>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
</table>
<ul class="list-unstyled" id="rankings"></ul>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.0.0/lodash.min.js"></script> -->
<script src="js/main.js"></script>
</body>
</html>
Add this code:
$('.table')
.append('<tr><td>' + rankPosition + '</td><td>' + rankPosition + '</td><td>' +rankings[i].name + ', ' + rankings[i].score + ' pts</tr>');
Fiddle: http://codepen.io/anon/pen/dGdabG
http://jsfiddle.net/3Sd4W/
Reference: The above js fiddle provided by greener.
If the new Entry Button is clicked, there is an layout issue for that new added object.
The text box style is:
file.setAttribute("style", "margin-top: 60px;");
But I want the text box to be in the middle and not at the bottom. I tried myself but it doesn't works for me. Anybody could help me to solve this problem?
Your code is extremely complicated to read, so this may help:
HTML:
<form name="addpoll">
<div id="choices">
</div>
<input id="addchoice" type="button" value="Add New Entry">
</form>
JS:
function addnewDiv(counterAppended) {
counterAppended = parseInt(counterAppended) + 1;
var text = document.createElement("div");
text.innerHTML = '<input type="hidden" class="choicecount" name="choicecount" id="choicecount" value="' + counterAppended + '">\
<input type="file" name="choiceimg' + counterAppended + '" value ="Select" onchange="readURL(this)" style="display:none;">\
<div>\
<div style="width:400px;height:85px;">\
<div id="imgbg" style="float:left;width: 110px;height: 80px;text-align: center;border: 1px solid #CCC;">\
<input type="button" onclick="HandFileButtonClick();" value="Browse" id="firstremove" style="margin-top: 30px;" class="addmultiple">\
</div>\
<div style="float:right;margin-top: 30px;">\
<input type=text name="choicename' + counterAppended + '" id="firstremove2">\
<input type="button" value="Remove" class="remove" id="firstremove3" style="color: red; font-size: 12px; border: 0px; background: none; text-decoration: underline;">\
</div>\
</div>\
<img src="#" name="viewimg' + counterAppended + '" class="addmultiple" id="viewimg' + counterAppended + '" height="70px" width="85px" style="display:none"/>\
<br>\
</div>\
<span id="file"></span>';
text.id = 'choice' + counterAppended;
document.getElementById("choices").appendChild(text);
document.getElementsByClassName("remove")[document.getElementsByClassName("remove").length - 1].addEventListener("click", function() {
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);
});
}
function HandFileButtonClick() {
document.addpoll.choiceimg1.click();
}
function HandleFileButtonClick(val) {
var ss = val.name;
document.forms["addpoll"]
var n = ss.split("choiceimgs");
document.forms["addpoll"]["choiceimg" + n[1]].click();
}
document.getElementById("addchoice").addEventListener("click", function() {
var choicecounts = document.getElementsByClassName('choicecount');
addnewDiv(choicecounts[choicecounts.length - 1].value);
});
addnewDiv(0);
JsFiddle: http://jsfiddle.net/99vhF/1/
The first row uses a wrapper div for the input field with a style attribute containing float: right. The generated row (after clicking 'add new entry' button) does not have a div wrapper with the same attribute around the input.
You add elements to incorrect nodes. Review you "add" part. All of variables take "file" element. It looks odd:
var addfile = document.getElementById("file");
var view = document.getElementById("file");
var remove1 = document.getElementById("file");
var br2 = document.getElementById("file");
var textf1 = document.getElementById("file");
var myimgdiv = document.getElementById("file");
I am busy creating a website where a user has to select some checkboxes from a huge matrix of checkboxes. 100 by 100 = 10 000 boxes to be more specific!
The way I have set out doing this is by creating 100 vertical divs, each with 100 checkboxes in them.
This seems to work OK but it ends up being a HUGE amount of code! So much, that when I hit refresh in Dream Weaver, it crashes!
I'm pretty new at HTML and Javascript. Is there a better way of doing this??
I included a very small basic example of what I have done
<html lang="en"><head><meta name="generator" content="PSPad editor, www.pspad.com">
<title>Checkbox No Vertical Space</title>
<style type="text/css">
#aDiv,
#bDiv,
#cDiv{
float:left;
width:12px;
}
#aDiv input,
#bDiv input,
#cDiv input{
clear:left;
float:left;
margin:0;
padding:0;
width:12px;
height:12px;
}
</style></head><body>
<div id="aDiv">
<input type="checkbox" value="a1">
<input type="checkbox" value="a2">
<input type="checkbox" value="a3">
<input type="checkbox" value="a4">
<input type="checkbox" value="a5">
<input type="checkbox" value="a6">
</div>
<div id="bDiv">
<input type="checkbox" value="b1">
<input type="checkbox" value="b2">
<input type="checkbox" value="b3">
<input type="checkbox" value="b4">
<input type="checkbox" value="b5">
<input type="checkbox" value="b6">
</div>
<div id="cDiv">
<input type="checkbox" value="c1">
<input type="checkbox" value="c2">
<input type="checkbox" value="c3">
<input type="checkbox" value="c4">
<input type="checkbox" value="c5">
<input type="checkbox" value="a6">
</div>
</body></html>
Thanks!
Allan
This code performs well:
var i, j, div, cb, frag;
frag = document.createDocumentFragment();
cb = document.createElement( 'input' );
cb.type = 'checkbox';
for ( i = 0; i < 100; i += 1 ) {
div = document.createElement( 'div' );
for ( j = 0; j < 100; j += 1 ) {
div.appendChild( cb.cloneNode( false ) );
}
frag.appendChild( div );
}
document.body.appendChild( frag );
Live demo: http://jsfiddle.net/Kyswa/1/show/
(although my machine has performance issues when scrolling the page)
I went ahead and made a jQuery version of this, and made sure the width was dynamically calculated to ensure that you have 100x100 checkboxes cross browser. I also added some html5 data attributes to the checkboxes, so you wont have to calculate it every time. Also, there's a single event hooked up to a containing div, so events will perform well. Here's the code:
HTML
<div id="checkboxes">
</div>
CSS
#checkboxes {
line-height: 0;
}
#checkboxes input[type="checkbox"] {
margin: 0px;
padding: 0px;
}
JavaScript + jQuery 1.7
$(function(){
var target = $('#checkboxes');
var x, y, checkbox;
for(x = 0; x < 100; x++)
{
for(y = 0; y < 100; y++)
{
checkbox = $('<input></input>', {
'type': 'checkbox',
'data-x': x,
'data-y': y
});
target.append(checkbox);
}
}
target.width(checkbox.outerWidth() * 100);
target.on('change', 'input:checkbox', function(){
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed (' + x + ', ' + y + '): ' + checked);
});
});
Example
http://jsfiddle.net/xixonia/Uq7CU/1/
Here's a fun version where you can draw by moving your mouse over the checkboxes:
http://jsfiddle.net/xixonia/Uq7CU/2/
This may not be proper HTML or follow recommended guidelines, but you could use a <table></table>. Get rid of your <div></div>'s, make one <div></div> with an id of "grid", and add this to your javascript:
var grid = "";
grid += "<table>";
for (var row = 0; row < 100; row++)
{
grid += "<tr>";
for (var col = 0; col < 100; col++)
{
grid += "<td>";
grid += "<input type='checkbox' value='" + row + "-" + col + "'>";
grid += "</td>";
}
grid += "</tr>";
}
grid += "</table>";
document.getElementById("grid").innerHTML = grid;
Please let me know if this doesn't work or if it has any errors!
Do you have to have checkboxes?
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<style>
table{layout:fixed;width:95%;margin:0 auto;}
td{border:ridge thin gray;width:1%;font-size:8px;color:white;background-color:white;padding:0}
td:hover{background-color:blue}
input{font-size:smaller}
</style>
</head>
<body>
<h1>Boxes<br>
<input type="text" size="20" value=""></h1>
<script>
onload= function(){
document.getElementsByTagName('table')[0].onclick= function(e){
e= e || window.event;
var r= 0, c= 0, row, col,
who= e.target || e.srcElement,
msg= document.getElementsByTagName('input')[0];
if(who.tagName== 'TD'){
who.style.backgroundColor= 'red';
msg.value= who.id.replace('r','row: ').replace('c',' col: ');
}
}
}
var r= 1, c= 1, str= '<table cellspacing="0" cellpadding="0">\n<tbody>';
while(r<101){
str+= '\n<tr>';
c= 1;
while(c<101){
str+= '<td id="r'+r+'c'+c+'">x</td>';
++c;
}
str+= '</tr>';
++r;
}
str+='</tbody>\n</table>\n';
document.write(str);
</script>
<br>
</body>
</html>