This is my HTML code:
<!DOCTYPE html>
<head>
<title>Chemist</title>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
<script src="jquery.js"></script>
<script src="app.js"></script>
</body>
</html>
This is the app.js code:
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
checkAddToMixClick();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
}
}
function checkAddToMixClick(){
for(let i = 0; i < inventoryLength; i++){
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
My problem is that when I run this and click the "+" the click() event fires, but after that nothing happens.
Debugging shows that when I call the checkAddToMixClick() function and click the "+" it works again, but stops working after that.
Any solution this?
Just add checkAddToMixClick(); to your populateInventory() function, and remove checkAddToMixClick() from the top of your code.
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
}
checkAddToMixClick();
}
function checkAddToMixClick(){
for(let i = 0; i < inventoryLength; i++){
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
<!DOCTYPE html>
<head>
<title>Chemist</title>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</body>
</html>
As you can see here you must move your click
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>");
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
$(document).on("click", ".clicker", function() {
var id = $(this).data('id');
inventoryAmounts[id]--;
populateInventory();
});
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td class='clicker' data-id='" + i + "'>+</td></tr>");
}
}
.clicker{}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
I think the previous answers were great. I Just wanted to provide an alternative as it seems you might want to add the data incrementally.
You can use $.on() in order to hook into any of those td's added to the DOM in the future. This allows you to eliminate the wiring of events to each <td id="add_to_mix"_>. So, if needed, you could simply append to the table instead of recreating it all.
I added a css class in order to make the code simple but you can use any selector you wish. I've also used the data tag in order to avoid parsing the id property.
$(document).on("click", ".clicker", function() {
var id = $(this).data('id');
inventoryAmounts[id]--;
populateInventory();
});
http://api.jquery.com/on/
Related
how to create Building HTML with list variable...
this my code error...
html
<div class="demo">
<!-- append code -->
</div>
css
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
jQuery code
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
html = $('<button class="demo_btn_' + cls + '"><span>' + txt + '</span></button>');
$(".demo").append(html);
});
and this output my code
<div class="demo">
<button class="demo_btn_btn1,btn2,btn3">
<span>button1,button2,button3</span></button>
</div>
And i want this...
<div class="demo">
<button class="demo_btn_btn1"><span>Button1</span></button>
<button class="demo_btn_btn2"><span>Button2</span></button>
<button class="demo_btn_btn3"><span>Button3</span></button>
</div>
Please help me, thank you in advance
The thing is, you're putting all the content together into a single button, which is why it's showing up as a single element.
You need to loop over the things and assign each element like below.
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
for (let i = 0; i < 3; i++)
{
html = $('<button class="demo_btn_' + cls[i] + '">' + txt[i] + '</button>');
$(".demo").append(html);
}
});
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
</div>
In order to do what you want, you would have to loop through the array one at a time, so what you can do is:
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
for (var i = 0; i < 3; i++) {
$(".demo").append(
$('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>')
);
}
});
You can simply use .each() to loop through array .. and += to html then use .html() after loop
$(function(){
var html = '';
cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
$.each(cls , function(i){
html += '<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>';
});
$(".demo").html(html);
});
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
<!-- append code -->
</div>
Try using a loop, and create new html elements based on the index of cls and txt. Posting from my phone, so apologies if the formatting is messed up.
$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
for (var i =0; i < cls.length; i++){
var html = $('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i]+ '</span></button>');
$(".demo").append(html);
}
});
I would use for loop for this case.
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'];
for (var i = 0; i < cls.length; i++) {
$(".demo").append('<button class="demo_btn_' + cls[i] + '"><span>' + txt[i] + '</span></button>');
}
.demo_btn_btn1 {
color :red;
}
.demo_btn_btn2 {
color :blue;
}
.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">
<!-- append code -->
</div>
I'm having trouble when i run this code under greasemonkey the last position working and run function.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML = document.getElementById('moje_menu').innerHTML + '<p id="' + arry[i] + '">' + arry[i] + '</p>';
document.getElementById(arry[i]).onclick = delete;
}
On 10 position the last working ... WHY ????
When you replace the innerHTML you remove all previous event handlers.
In plain JS you can detect the click in the div but you need to check the event:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
window.onload=function() {
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '">' + arry[i] + '</p>';
}
document.getElementById('moje_menu').onclick=function(e) {
var event = e?e:window.event,tgt = event.target || event.srcElement;
if (tgt.tagName.toLowerCase()=="p") {
console.log(tgt.id);
}
}
}
<div id="moje_menu"></div>
Alternative is inline since you generate the P anyway
var arry = [];
arry = GM_listValues();
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="delete(this)">' + arry[i] + '</p>';
}
You can the modify delete (poor name for a function since delete is a built-in method) to handle the passed paragraph
Example:
function removeP(p) {
console.log(p.id);
}
var arry = ["a","b","c"];
for ( var i = 0; i < arry.length; i++) {
document.getElementById('moje_menu').innerHTML += '<p id="' + arry[i] + '" onclick="removeP(this)">' + arry[i] + '</p>';
}
<div id="moje_menu"></div>
In jQuery you can easily delegate:
function removeP() {
console.log(this.id);
}
$(function() {
var arry = ["a","b","c"];
var $menu = $('#moje_menu');
for (var i=0; i<arry.length; i++) {
$menu.append($('<p/>',{"id":arry[i], "text":arry[i]}))
}
$menu.on("click","p",removeP);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="moje_menu"></div>
This is my solution i dont like them but works.
var arry = [];
arry = GM_listValues();
for ( var i = 0; i<arry.length; i++) {
// if(arry[i].search('player')==''){
document.getElementById('moje_menu').innerHTML += '<p class="lista_farm" id="'+arry[i]+'">'+arry[i]+'</p>';
//document.getElementById(arry[i]).onclick = usun_farme;
//}
}
var lista_farm = document.getElementsByClassName('lista_farm');
for(var i = 0; i<lista_farm.length; i++){
lista_farm[i].onclick = usun_farme;
}
I want to make a script where i can put my form in the javascript array invoer[] and display the total
It constantly stops working and i searched a lot, i really can't find the right way :D
This is my javascript code
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer[a] = document.getElementByI(strijk[a]).value;
}
var totaal;
for (var a = 0; a < minuten.length; a++) {
totaal += parseint(invoer[a]) * parseint(minuten[a]);
}
document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer != []) {
document.write("totaal aantal minuten" + totaal);
} else {
document.write("geen invoer");
}
}
my html looks likes this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript" >
//my javasccript
</script>
<button id="B1" onclick="invoerstrijk()" >Nieuwe strijk</button>
</body>
</html>
This should work:
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform' onsubmit='return false;'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer.push(document.getElementById(strijk[a]).value);
}
var totaal = 0;
for (var a = 0; a < minuten.length; a++) {
totaal += (parseInt(invoer[a]) * parseInt(minuten[a]));
}
// !!! this is wrong because it is out of for !!!
//document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer.length > 0) {
document.write("totaal aantal minuten " + totaal);
} else {
document.write("geen invoer");
}
}
Some explanation:
onsubmit='return false;' - to not send form and reload page.
invoer.push(document.getElementById(strijk[a]).value); - to put elements into array use push.
var totaal = 0; - init variable 0 bacause it is undefined.
Misspellings: Bad: parseint, Good: parseInt; Bad: getElementByI, Good: getElementById
The line with readonly input is wrong because it is out of for so a variable is not defined.
Plunker example
I'm trying to figure out a way to retrieve and display the value of a div tag that is created with a 2D array using JavaScript. I figured either onclick or onmouseover would work but neither would in this approach. I would like to avoid creating 49 functions that does the same thing (just displaying the 'cell' the mouse is over).
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
// ???
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Thanks!
You can simply get the cell id by passing this.id into the function.
Try this:
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
console.log(cellId);
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Right now you have set up each cell element to call the function displayMe whenever the mouseover event occurs. When you call that function, you are passing the variable cellId as an argument. The problem is when that function is called, cellId is not defined. You can see this error pop up in your browser's developer console ("Uncaught ReferenceError: cellId is not defined").
You probably want to pass the cell element's id property, which you define dynamically here: id='area" + i + j + "'. You can use the id property of an element to look up the element (as you have done already), and get the text it contains via textContent.
To pass the cell element's id property, you need to use the this variable, like so: this.id. this will refer to the element that is triggering the event. So, if you change your onmouseover value of your div element to this: onmouseover='displayMe(this.id)', it will pass the appropriate value to your displayMe function, allowing you to do something like this:
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
With these adjustments, your code will look like this in its entirety:
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
I've found dragtable http://www.danvk.org/wp/dragtable/ but I need a Jquery-based solution. May be I'm missing something?
The plugin jqGrid (latest versions at github repo) has a feature to re-order columns - the documentation is here. It does not appear to have drag/drop support for re-ordering columns however.
Here is a custom working sample of draggable table columns using only jQuery and jQuery UI sortable interaction.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery-ui-1.8.1.custom.css">
<style type="text/css">
th
{
background-color: #e0e0e0;
cursor: pointer;
}
.ui-state-highlight
{
height: 1.5em;
line-height: 1.2em;
}
</style>
<script type="text/javascript">
$(function() {
var $table1 = $('#table1');
var $table1Thead = $table1.find('thead');
var $table1Tbody = $table1.find('tbody');
var maxCols = 10;
var maxRows = 50;
// populate fake data
for (var i = 1; i <= maxCols; i++) {
$table1Thead.append('<th id="column' + i + '">column ' + i + '</th>');
}
var rowHtml;
for (var x = 1; x <= maxRows; x++) {
rowHtml = '<tr>';
for (var i = 1; i <= maxCols; i++) {
//rowHtml += '<td>row ' + x + ', column ' + i + '</td>';
rowHtml += '<td>column ' + i + '</td>';
}
rowHtml += '</tr>';
$table1Tbody.append(rowHtml);
}
// set an index helper on each th element
$table1Thead.find('th').each(function() {
var thElement = $(this);
thElement.data('columnIndex', $table1Thead.find('th').index(thElement));
});
$table1Thead.sortable({
items: 'th',
containment: 'parent',
helper: 'clone',
placeholder: 'ui-state-highlight',
update: function(event, ui) {
var prevPos = ui.item.data('columnIndex');
var newPos = $table1Thead.find('th').index(ui.item);
// adjust all the row elements
$table1Tbody.find('tr').find('td:eq(' + prevPos + ')').each(function() {
var tdElement = $(this);
var tdElementParent = tdElement.parent();
tdElement.remove();
tdElementParent.find('td:eq(' + newPos + ')').before(tdElement);
});
// re-set an helper indexes
$table1Thead.find('th').each(function() {
var thElement = $(this);
thElement.data('columnIndex', $table1Thead.find('th').index(thElement));
});
}
});
});
</script>
</head>
<body>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
This JavaScript does drag-and-drop on columns. As it doesn't uses any framework you can combine it easily with any other framework.
Why do you nee a jQuery based solution when you can have one without the need of a specific framework.
Another approach to reorder columns with Jquery UI Sortable:
http://jsfiddle.net/pg7wH/
Needs
jQuery (tested with 1.7.2 - 2.0)
jQuery UI (tested with 1.8.18 - 1.10.2)
HTML:
<button id="getSorting">Get sorting</button><input id="showSorting" />
<table id="table1">
<thead class="ui-state-default"></thead>
<tbody></tbody>
</table>
JS:
$(function() {
var $table1 = $('#table1');
var $table1Thead = $table1.find('thead');
var $table1Tbody = $table1.find('tbody');
var startPos;
var oldPos;
// populate fake data
var maxCols = 10;
var maxRows = 50;
for (var i = 1; i <= maxCols; i++) {
$table1Thead.append('<th sort="' + i + '" id="column[' + i + ']">column ' + i + '</th>');
}
var rowHtml;
for (var x = 1; x <= maxRows; x++) {
rowHtml = '<tr>';
for (var i = 1; i <= maxCols; i++) {
//rowHtml += '<td>' + i + ' - ' + x + '</td>';
rowHtml += '<td>col ' + i + '</td>';
}
rowHtml += '</tr>';
$table1Tbody.append(rowHtml);
}
// Show sorting
$("button#getSorting").click(function() {
$('#showSorting').val($table1Thead.sortable('toArray', { attribute: "sort" } ))
console.log($table1Thead.sortable('toArray', { attribute: "sort" } ))
})
// The sorting
$table1Thead.sortable({
axis: "x" ,
items: 'th',
containment: 'parent',
cursor: 'move',
helper: 'clone',
distance: 5,
opacity: 0.5,
placeholder: 'ui-state-highlight',
start: function(event, ui) {
startPos = $table1Thead.find('th').index(ui.item);
oldPos = startPos;
},
change: function(event, ui) {
// Get position of the placeholder
var newPos = $table1Thead.find('th').index($table1Thead.find('th.ui-state-highlight'));
// If the position is right of the original position, substract it by one in cause of the hidden th
if(newPos>startPos)newPos--;
// move all the row elements
//console.log('Move: 'oldPos+' -> '+newPos);
$table1Tbody.find('tr').find('td:eq(' + oldPos + ')').each(function() {
var tdElement = $(this);
var tdElementParent = tdElement.parent();
if(newPos>oldPos)// Move it the right
tdElementParent.find('td:eq(' + newPos + ')').after(tdElement);
else// Move it the left
tdElementParent.find('td:eq(' + newPos + ')').before(tdElement);
});
oldPos = newPos;
}
});
});
Thanks to Nate Pinchot for his example.