I was making a calculator for a game and made a button like this:
<button onclick="myFunction()">Calculate</button>
When button is clicked, I want to run the following myFunction() script:
<script>
function myFunction() {
var currDura, maxDura, tempMaxDura, tempDura, totDura, optDura;
var iniCost, repCost;
var smithEffi, smithCharge;
var se, sc;
var totCostTillNow, costPerBattle = 0, minCPB;
var i;
var repCount = 1;
//Assigning the values
currDura=document.getElementById("currDura_").value;
maxDura=document.getElementById("maxDura_").value;
iniCost=document.getElementById("iniCost_").value;
repCost=document.getElementById("repCost_").value;
smithEffi=document.getElementById("smithEffi_").value;
smithCharge=document.getElementById("smithCharge_").value;
se = smithEffi / 100;
sc = smithCharge / 100;
tempMaxDura = maxDura;
tempDura = currDura;
totDura = tempDura;
totCostTillNow = iniCost;
costPerBattle = totCostTillNow / totDura;
minCPB = costPerBattle;
for(i=1; i<=60; i++)
{
totCostTillNow += (double) repCost * sc;
tempDura = tempMaxDura * se;
totDura += tempDura;
costPerBattle = (double) (totCostTillNow / totDura);
tempMaxDura -= 1;
if ( minCPB >= costPerBattle )
{
minCPB = costPerBattle;
optDura = tempMaxDura;
}
}
document.getElementById("result").value = eval(minCPB) + " gold at 0/"+ eval(optDura);
//alert("minimum cost per battle = "+ eval(minCPB)+ "at 0/"+ eval(optDura));
}
</script>
Here result is a label where I want to provide the final answer.
When I click the button, it should run the function myFunction() but it doesn't. Instead it refreshes the page and all the data entered is gone.
Can you help me why this is occurring?
<!DOCTYPE html>
<html>
<head>
<title>
Cost Per Battle Calculator
</title>
</head>
<style>
.smaller{
width: 50px;
padding: 12px 10px;
margin: 0px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.bigger{
width: 110px;
padding: 12px 10px;
margin: 0px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button{
width: 110px;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 0px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #badf6f;
padding:20px;
}
</style>
<body>
<div>
<form>
<!-- <label for="fname" id="fn">First Name</label> -->
<!-- <input type="text" id="fname" name="firstname"> -->
<!-- <button onclick="myFunction()">Calculate</button> -->
<table border="0">
<tr>
<td>
<center><img src="http://trial.6te.net/images/gold.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/wood_s.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/ore_s.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/mercury_s.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/sulphur_S.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/crystal_S.gif"></img></center>
</td>
<td>
<center><img src="http://trial.6te.net/images/gems_S.gif"></img></center>
</td>
</tr>
<tr>
<td>
<input type="text" id="gold_" name="Gold" class="bigger">
</td>
<td>
<input type="text" id="wood_" name="Wood" class="smaller">
</td>
<td>
<input type="text" id="ore_" name="Ore" class="smaller">
</td>
<td>
<input type="text" id="mercury_" name="Mercury" class="smaller">
</td>
<td>
<input type="text" id="sulphur_" name="Sulphur" class="smaller">
</td>
<td>
<input type="text" id="crystals_" name="Crystals" class="smaller">
</td>
<td>
<input type="text" id="gems_" name="Gems" class="smaller">
</td>
</tr>
<tr>
<td>
<input type="text" id="currDura_" name="Current Durability" class="smaller">
</td>
<td>
<input type="text" id="maxDura_" name="Maximum Durability" class="smaller">
</td>
</tr>
<tr>
<td>
<input type="text" id="repCost_" name="Repair Cost" class="bigger">
</td>
</tr>
<tr>
<td>
<input type="text" id="smithEffi_" name="Smith Efficiency" class="smaller">
</td>
<td>
<input type="text" id="smithCharge_" name="Smith Charge" class="smaller">
</td>
</tr>
<tr>
<td colspan="7">
<center><button onclick="myFunction()">Calculate</button></center>
</td>
</tr>
<tr>
<td colspan="7">
<label id="result"></label>
</td>
</tr>
</table>
</form>
</div>
<script>
//Here is the above script
</script>
</body>
</html>
By default the button is submitting the form. To fix it you need to return false;.
onclick="myFunction(); return false;"
Add param e in your function, and the just write e.preventDefault(). More about that.
myFunction(e){
e.preventDefault();
//rest of your code
}
Change your <button> to some other tag like <div> or <span>. It will not look like a button, but functionally it will do what you want. You can style the div with css to look more like button if you want.
<center><span onclick="myFunction()">Calculate</span></center>
Related
I have an issue with my HTML, where when I go to add more than 3 new assets into my table, the buttons below (Add new asset, save and submit) are not being pushed down. Is this a flex issue and how would I go about solving this? I put all of my buttons into a div because I found this aligned my page better. But when I did not have my buttons in a div, it works. I am reframing my code to have more div's to keep everything contained.
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input id='asset_tag_no${count}' type='text' bottom required /></td>
<td><input id='manufacturer_serial_no${count}' type='text' bottom required/></td>
<td><input id='description${count}' type='text'/></td>
<td><input id='cost${count}' type='value'/></td>
<td><input id='po_no${count}' type='text' /></td>
<td><input id='rc_to_credit${count}' type='text'/></td>
<td><input id='remarks${count}' type='text'/></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
})
.header{
text-align: center;
margin-bottom: 50px;
}
h1, h2{
font-size: 1rem;
}
/* table{
font-size: 10pt;
} */
#media screen {
input{
text-align: center;
}
input#date{
width: -webkit-fill-available;
}
.flex {
display: flex;
flex: auto;
height: 100px;
/* border: 1px solid red; */
}
.flex-box {
width: 40px;
height: 1000px;
/* background: pink; */
}
.button{
display: flex;
/* display: inline !important; */
flex: auto;
height: 40px;
gap: 12px;
}
.btn-remove{
padding: 5px;
width: 25px;
height: 25px;
font-size: 0.7rem;
font-weight: bold;
}
}
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<!-- BOOTSTRAP + JQUERY -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="./css/disposal.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="./js/./disposal.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
<div class="wrapper">
<form div class="flex">
<table>
<div class="flex-box"></div>
<tr>
<td align="right" id='date'><b>Date:</b></td>
<td align="left"><input type="date" id="date" /></td>
</tr>
<tr>
<td align="right" id='department'><b>Dept/Division:</b></td>
<td align="left"><input type="text" id="department" /></td>
</tr>
<tr>
<td align="right" id='location'><b>Location:</b></td>
<td align="left"><input type="text" id="location" /></td>
</tr>
<tr>
<td align="right" id='resp'><b>Resp. Ctr:</b></td>
<td align="left"><input type="text" id="resp" /></td>
</tr>
</table>
</div>
<br><br><br><br>
<div class="flex">
<table class='table' id='formTable'>
<div class="flex-box"></div>
<tr>
<th> Asset Tag No.</th>
<th>Manufacturer Serial No.</th>
<th> Description</th>
<th> Cost/ Est. Cost</th>
<th> Method of Disposal</th>
<th> RC to Credit</th>
<th> Remarks</th>
</tr>
</table>
</div>
<br><br><br><br>
<div class="button">
<div class="flex-box"></div>
<button type="button" class="btn btn-outline-primary" id='add' >+ Add New Asset</button>
</div>
<br>
<div class="button">
<div class="flex-box"></div>
<button type="button" class="btn btn-outline-primary" id='save'>SAVE</button>
<button class="btn btn-primary" type="submit" id='submit' >SUBMIT</button>
<button type="button" class="btn btn-secondary" onclick="window.print();return false;"/>EXPORT PDF</button>
</div>
</form>
</div>
</body>
</html>
You had added heights for both .flex and .flex-box. This was forcing them to stay the size they were.
Also, you didn't need the form tags for each row.
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<td><input id='asset_tag_no${count}' type='text' bottom required /></td>
<td><input id='manufacturer_serial_no${count}' type='text' bottom required/></td>
<td><input id='description${count}' type='text'/></td>
<td><input id='cost${count}' type='value'/></td>
<td><input id='po_no${count}' type='text' /></td>
<td><input id='rc_to_credit${count}' type='text'/></td>
<td><input id='remarks${count}' type='text'/></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function() {
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count++;
});
})
.header {
text-align: center;
margin-bottom: 50px;
}
h1,
h2 {
font-size: 1rem;
}
/* table{
font-size: 10pt;
} */
#media screen {
input {
text-align: center;
}
input#date {
width: -webkit-fill-available;
}
.flex {
display: flex;
flex: auto;
}
.flex-box {
width: 40px;
/* background: pink; */
}
.button {
display: flex;
/* display: inline !important; */
flex: auto;
height: 40px;
gap: 12px;
}
.btn-remove {
padding: 5px;
width: 25px;
height: 25px;
font-size: 0.7rem;
font-weight: bold;
}
}
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<!-- BOOTSTRAP + JQUERY -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="./css/disposal.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="./js/./disposal.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
<div class="wrapper">
<form div class="flex">
<table>
<div class="flex-box"></div>
<tr>
<td align="right" id='date'><b>Date:</b></td>
<td align="left"><input type="date" id="date" /></td>
</tr>
<tr>
<td align="right" id='department'><b>Dept/Division:</b></td>
<td align="left"><input type="text" id="department" /></td>
</tr>
<tr>
<td align="right" id='location'><b>Location:</b></td>
<td align="left"><input type="text" id="location" /></td>
</tr>
<tr>
<td align="right" id='resp'><b>Resp. Ctr:</b></td>
<td align="left"><input type="text" id="resp" /></td>
</tr>
</table>
</div>
<br><br><br><br>
<div class="flex">
<table class='table' id='formTable'>
<div class="flex-box"></div>
<tr>
<th> Asset Tag No.</th>
<th>Manufacturer Serial No.</th>
<th> Description</th>
<th> Cost/ Est. Cost</th>
<th> Method of Disposal</th>
<th> RC to Credit</th>
<th> Remarks</th>
</tr>
</table>
</div>
<br><br><br><br>
<div class="button">
<div class="flex-box"></div>
<button type="button" class="btn btn-outline-primary" id='add'>+ Add New Asset</button>
</div>
<br>
<div class="button">
<div class="flex-box"></div>
<button type="button" class="btn btn-outline-primary" id='save'>SAVE</button>
<button class="btn btn-primary" type="submit" id='submit'>SUBMIT</button>
<button type="button" class="btn btn-secondary" onclick="window.print();return false;" />EXPORT PDF</button>
</div>
</form>
</div>
</body>
</html>
The way I've done this in the past is to iterate a row count for each <tr> tag as the table is created. This helps with sorting, and you can easily specify a sort order.
However, since your table is pre-existing, the only answer I can really see is to simply rebuild the entire table and flow it into the correct element (the table element, in your case). No row order required, just put the rows in, in the order you want them.
I hope that helps a little.
I have 10 different tables. one such table is below:
<table id="Vehicle-PS-Software">
<tr>
<td width=10%>
<input type="checkbox" name="option" value="TestID">
</td>
<td width=20%>
Test ID
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="ServiceNow">
</td>
<td>
ServiceNow
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="GIT">
</td>
<td>
Git Hub
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="Jira">
</td>
<td>
Jira
</td>
</tr>
<tr>
<tr>
<td>
<input type="checkbox" name="option" value="Confluence">
</td>
<td>
Confluence
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="BO">
</td>
<td>
BO Access
</td>
<td>
<input type="file" name="sampleFile" />
</td>
</tr>
</table>
I have a drop down as below:
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Teams</button>
<p>please select your team</p>
<div id="myDropdown" class="dropdown-content">
Vehicle PS
Vehicle RTB
Property PS
Property RTB
Commons PS
Commons RTB
Mainframe Team
Testing
</div>
</div>
Now I want to display different tables based on dropdown selection. if I select vehicle PS then Vehicle PS table has to show if I select different option from dropdown corresponding table.
Can any one please help me with this
Tried below code but is not working.
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
dropdowns[i].addEventListener("click", function(){
if(dropdowns[i]=="Vehicle PS")
{
document.getElementById("Vehicle-PS-Software").classList.toggle('show');
}
else{
document.getElementById("Vehicle-PS-Software").classList.remove('show');
}
});
}
You can try code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
#Vehicle-PS-Software1 {display:none}
.show {display: block;}
.hide {display : none}
</style>
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a onclick='dropDown(event)' href="#home">Vehicle PS</a>
About
Contact
</div>
</div>
<table id="Vehicle-PS-Software" class='hide'>
<tr>
<td width=10%>
<input type="checkbox" name="option" value="TestID">
</td>
<td width=20%>
Test ID
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="ServiceNow">
</td>
<td>
ServiceNow
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="GIT">
</td>
<td>
Git Hub
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="Jira">
</td>
<td>
Jira
</td>
</tr>
<tr>
<tr>
<td>
<input type="checkbox" name="option" value="Confluence">
</td>
<td>
Confluence
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="option" value="BO">
</td>
<td>
BO Access
</td>
<td>
<input type="file" name="sampleFile" />
</td>
</tr>
</table>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
dropdowns[i].addEventListener("click", function(event){
document.getElementById("Vehicle-PS-Software").classList.toggle('hide');
if(event.target.innerText=="Vehicle PS")
{
document.getElementById("Vehicle-PS-Software").classList.toggle('show');
document.getElementById("Vehicle-PS-Software").classList.toggle('hide')
}
else {
//document.getElementById("Vehicle-PS-Software").classList.remove('show');
//document.getElementById("Vehicle-PS-Software").classList.toggle('hide');
}
});
}
</script>
</body>
</html>
The correct selector for the dropdown options is
var dropdowns = document.querySelector('.dropdown-content').children
you can debug through rest of the code and check the onClick logic.
try to add this code to JS. also remove myFunction() from html file.
const dropbtn = document.querySelector('.dropbtn');
dropbtn.addEventListener('click',()=>{
var myDropdown = document.querySelector('.dropdown-content');
if (myDropdown.style.display === "block") {
myDropdown.style.display = "none";
} else {
myDropdown.style.display = "block";
}});
<script>
function myFunction() {
var drpoptions = document.getElementById("mySelect").options;
var e = document.getElementById("mySelect");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "Vehicle PS") {
document.getElementById("Vehicle-PS-Software").style.display = "block";
}
else {
document.getElementById("Vehicle-PS-Software").style.display = "none";
}
if (strUser == "Mainframe Team") {
document.getElementById("Mainframe-Team-Software").style.display = "block";
}
else {
document.getElementById("Mainframe-Team-Software").style.display = "none";
}
function myFunction() {
var e = document.getElementById("filterTodate");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "1") {
document.getElementById("range").style.display = "block";
document.getElementById("tillDate").style.display = "none";
}
if (strUser == "2") {
document.getElementById("tillDate").style.display = "block";
document.getElementById("range").style.display = "none";
}
}
I'm creating a basic database that's intended to only be stored in memory as practice in Javascript. Each new row gets it own corresponding delete and edit buttons. My problem now is how to get these delete buttons to work, that when you click on one it deletes it's row. Here is my code at this moment:
Javascript
function onload(){
$("#addbutton").on("click",addRow);
$(".delete").onclick(function(){
$(this).closest('tr').remove();
});
var i = 1;
function addRow(){
var newRow = "<tr rowID='" + i + "'>"+"<td><div>"+$("#namebox").val()+
"</div></td>"+"<td><div>"+$("#surnamebox").val()+"</div></td>"+"<td><div>"+$("#agebox").val()+"<td><div><button id='" + i + "' class='delete' name='delete'type='button'>DELETE</button></div></td>"+"<td><div><button class='edit' name='edit'type='button'>EDIT</button></div></td><td><p>"+ i + "</p></td></tr>"; //Adds the row with content and
// buttons
$(newRow).appendTo("#maintable"); //Append the new row
// to the table
// Next three commands clear the input boxes
$("#namebox").val('');
$("#surnamebox").val('');
$("#agebox").val('');
// Add to the numer of rows in the table
i++;
}// addRow END
};
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Memory-Only Database</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/script.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
</head>
<body onload="onload()">
<div id="header">
<h2>Memory-Only Database</h2>
</div>
<div id="input-table">
<table id="maintable" style="width: 60%">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th id="buttons1">buttons1</th>
<th id="buttons2">buttons2</th>
<th id="counter">counter</th>
</tr>
<tr>
<td>
<input id="namebox" name="name" type="text" value="">
</td>
<td>
<input id="surnamebox" name="surname" type="text" value="">
</td>
<td>
<input id="agebox" name="age" type="number" value="">
</td>
<td>
<button id="addbutton" name="add" type="button">ADD</button>
</td>
</tr>
</table>
</div>
</body>
</html>
CSS
body{
background-color: darkcyan;
}
div#header{
position: relative;
left: 30em;
width: 18em;
text-align: center;
}
div#input-table{
width:50em;
}
table,th,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
td{
text-align: center;
}
th#buttons{
width: inherit;
}
There is no onclick method in jQuery, use click instead.
$(".delete").click(function() {
$(this).closest("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Row 1</td>
<td><button class="delete">Del</button></td>
</tr>
<tr>
<td>Row 2</td>
<td><button class="delete">Del</button></td>
</tr>
<tr>
<td>Row 3</td>
<td><button class="delete">Del</button></td>
</tr>
</table>
You should use event delegation for delete button. since you are adding button dynamically.
$(document).on("click",'.delete',function(){
$(this).closest('tr').remove();
});
function onload(){
$("#addbutton").on("click",addRow);
var i = 1;
function addRow(){
var newRow = "<tr rowID='" + i + "'>"+"<td><div>"+$("#namebox").val()+
"</div></td>"+"<td><div>"+$("#surnamebox").val()+"</div></td>"+"<td><div>"+$("#agebox").val()+"<td><div><button id='" + i + "' class='delete' name='delete'type='button'>DELETE</button></div></td>"+"<td><div><button class='edit' name='edit'type='button'>EDIT</button></div></td><td><p>"+ i + "</p></td></tr>";
//Adds the row with content and
// buttons
$(newRow).appendTo("#maintable"); //Append the new row
// to the table
// Next three commands clear the input boxes
$("#namebox").val('');
$("#surnamebox").val('');
$("#agebox").val('');
// Add to the numer of rows in the table
i++;
}// addRow END
};
$(document).on("click",'.delete',function(){
$(this).closest('tr').remove();
});
body{
background-color: darkcyan;
}
div#header{
position: relative;
left: 30em;
width: 18em;
text-align: center;
}
div#input-table{
width:50em;
}
table,th,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
td{
text-align: center;
}
th#buttons{
width: inherit;
}
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
</head>
<body onload="onload()">
<div id="header">
<h2>Memory-Only Database</h2>
</div>
<div id="input-table">
<table id="maintable" style="width: 60%">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th id="buttons1">buttons1</th>
<th id="buttons2">buttons2</th>
<th id="counter">counter</th>
</tr>
<tr>
<td>
<input id="namebox" name="name" type="text" value="">
</td>
<td>
<input id="surnamebox" name="surname" type="text" value="">
</td>
<td>
<input id="agebox" name="age" type="number" value="">
</td>
<td>
<button id="addbutton" name="add" type="button">ADD</button>
</td>
</tr>
</table>
</div>
Another way you can delete row .... during adding new row give that row an id and call an onclick function during delete.
function deleterow(id){
$("#newrow-"+id+"").remove();
}
function onload(){
$("#addbutton").on("click",addRow);
var i = 1;
function addRow(){
var newRow = "<tr id='newrow-"+i+"'>"+"<td><div>"+$("#namebox").val()+
"</div></td>"+"<td><div>"+$("#surnamebox").val()+"</div></td>"+"<td><div>"+$("#agebox").val()+"<td><div><button id='" + i + "' class='delete' name='delete' type='button' onclick='deleterow("+i+")'>DELETE</button></div></td>"+"<td><div><button class='edit' name='edit'type='button' >EDIT</button></div></td><td><p>"+ i + "</p></td></tr>"; //Adds the row with content and
// buttons
$(newRow).appendTo("#maintable"); //Append the new row
// to the table
// Next three commands clear the input boxes
$("#namebox").val('');
$("#surnamebox").val('');
$("#agebox").val('');
// Add to the numer of rows in the table
i++;
}// addRow END
};
body{
background-color: darkcyan;
}
div#header{
position: relative;
left: 30em;
width: 18em;
text-align: center;
}
div#input-table{
width:50em;
}
table,th,tr,td{
border: 1px solid black;
border-collapse: collapse;
}
td{
text-align: center;
}
th#buttons{
width: inherit;
}
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
</head>
<body onload="onload()">
<div id="header">
<h2>Memory-Only Database</h2>
</div>
<div id="input-table">
<table id="maintable" style="width: 60%">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th id="buttons1">buttons1</th>
<th id="buttons2">buttons2</th>
<th id="counter">counter</th>
</tr>
<tr>
<td>
<input id="namebox" name="name" type="text" value="">
</td>
<td>
<input id="surnamebox" name="surname" type="text" value="">
</td>
<td>
<input id="agebox" name="age" type="number" value="">
</td>
<td>
<button id="addbutton" name="add" type="button">ADD</button>
</td>
</tr>
</table>
</div>
So I have a program which randomly assigns a name to each cell in the first row of my table from a list of names in a text box with the click of a button, what I want to do is assign different names to each of the cells in the textbox in the click of a button so that no two cells have the same name, here is my code so far:
var rnd = function() {
var things;
things = document.getElementById('things').value;
things = things.replace(', ', ',');
things = things.split(',');
setTimeout(function() {
var list = document.querySelectorAll('.js-result');
for (var index = 0; index < list.length; index++) {
var thing = Math.floor(Math.random() * things.length);
list.item(index).innerHTML = things[thing];
}
}, 500);
};
fieldset input {
display: block;
}
.result {
border: solid 1px black;
background: #e0e0e0;
padding: 1em;
margin: 1em 0;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 75%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
text-align: center
}
tr:nth-child(even) {
background-color: #dddddd;
}
<table align="center">
<thead>
<tr>
<th></th>
<th>Black</th>
<th>Blue</th>
<th>B & B</th>
<th>Gold</th>
<th>Green</th>
<th>Gryphons</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form method="get" action="/" onsubmit="return false;">
<fieldset>
<label>
<textarea style="width: 400px;height: 35px;" name="things" id="things">Forrest Gump, Tim Thomas, Pamila Henryson, Lotus Hobbes, Jerry Sparks, Kenneth Ingham</textarea>
</label>
</fieldset>
<p>
<input type="button" value="Pick one!" onclick="rnd();">
</p>
</form>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
</tr>
</tbody>
</table>
Instead of accessing the array element you can very well mutate it using things.splice(thing,1) - see demo below:
var rnd = function() {
var things;
things = document.getElementById('things').value;
things = things.replace(', ', ',');
things = things.split(',');
setTimeout(function() {
var list = document.querySelectorAll('.js-result');
for (var index = 0; index < list.length; index++) {
var thing = Math.floor(Math.random() * things.length);
list.item(index).innerHTML = things.splice(thing,1);
}
}, 500);
};
fieldset input {
display: block;
}
.result {
border: solid 1px black;
background: #e0e0e0;
padding: 1em;
margin: 1em 0;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 75%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
text-align: center
}
tr:nth-child(even) {
background-color: #dddddd;
}
<table align="center">
<thead>
<tr>
<th></th>
<th>Black</th>
<th>Blue</th>
<th>B & B</th>
<th>Gold</th>
<th>Green</th>
<th>Gryphons</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form method="get" action="/" onsubmit="return false;">
<fieldset>
<label>
<textarea style="width: 400px;height: 35px;" name="things" id="things">Forrest Gump, Tim Thomas, Pamila Henryson, Lotus Hobbes, Jerry Sparks, Kenneth Ingham</textarea>
</label>
</fieldset>
<p>
<input type="button" value="Pick one!" onclick="rnd();">
</p>
</form>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
<td>
<div class="js-result result"></div>
</td>
</tr>
</tbody>
</table>
One way to do this is using the unique things array. This can be done by using the filter function on the array and passing in a predicate which checks for the uniqueness.
let uniqueThings = things.filter((currentValue, index, array) => array.indexOf(currentValue) === index); ;
list.item(index).innerHTML = uniqueThings[index];
Complete Code:
var rnd = function () {
var things;
things = document.getElementById('things').value;
things = things.replace(', ', ',');
things = things.split(',');
setTimeout(function () {
var list = document.querySelectorAll('.js-result');
for (var index = 0; index < list.length; index++) {
var thing = Math.floor(Math.random() * things.length);
let uniqueThings = things.filter((currentValue, index, array) => array.indexOf(currentValue) === index); ;
list.item(index).innerHTML = uniqueThings[index];
}
}, 500);
};
margin: 1em 0;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 75%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
text-align: center
}
tr:nth-child(even) {
background-color: #dddddd;
}
<table align="center">
<thead>
<tr>
<th></th>
<th>Black</th>
<th>Blue</th>
<th>B & B</th>
<th>Gold</th>
<th>Green</th>
<th>Gryphons</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form method="get" action="/" onsubmit="return false;">
<fieldset>
<label>
<textarea style="width: 400px;height: 35px;" name="things" id="things">Forrest Gump, Tim Thomas, Pamila Henryson, Lotus Hobbes, Jerry Sparks, Kenneth Ingham</textarea>
</label>
</fieldset>
<p>
<input type="button" value="Pick one!" onclick="rnd();">
</p>
</form>
</td>
<td><div class="js-result result"></div></td>
<td><div class="js-result result"></div></td>
<td><div class="js-result result"></div></td>
<td><div class="js-result result"></div></td>
<td><div class="js-result result"></div></td>
<td><div class="js-result result"></div></td>
</tr>
</tbody>
</table>
Is there any good and minimal plugin which fix <thead> or first row? And dont add <tbody> automatically.
When i am using <thead> to wrap the first row (directly in HTML Table) , then everything is working right as it should for my table. But when i am adding <thead> to wrap the first row (not HTML but through jquery) $("tr").first().wrap("<thead></thead>"); then it is working but not displaying as it should, because first its wrapping the whole table in <tbody> automatically then adding <thead> in first row.
Please tell me how to solve this because my tables don't have <thead> in HTML. But I need it to fix the first row when scrolling, because it is requirement in all jQuery Plugins to have <thead> to fix first row, please help
Working: http://jsfiddle.net/seky66cb/ (adding <thead> with HTML)
Not Working For Me: http://jsfiddle.net/seky66cb/1/ (adding <thead> with jQuery)
CODE (Not Working As Expected):
Library: jQuery: 2.1.3
HTML:
<table class="gridView" id="table2">
<tr>
<th> Culture Name </th>
<th> Display Name </th>
<th> Culture Code </th>
<th> ISO 639x </th>
</tr>
<tr class="grid">
<td> af-ZA </td>
<td> Afrikaans - South Africa </td>
<td> 0x0436 </td>
<td> AFK </td>
</tr>
<tr class="gridAlternada">
<td> sq-AL </td>
<td> Albanian - Albania </td>
<td> 0x041C </td>
<td> SQI </td>
</tr>
<tr class="grid">
<td> ar-DZ </td>
<td> Arabic - Algeria </td>
<td> 0x1401 </td>
<td> ARG </td>
</tr>
<tr class="gridAlternada">
<td> ar-BH </td>
<td> Arabic - Bahrain </td>
<td> 0x3C01 </td>
<td> ARH </td>
</tr>
<tr class="grid">
<td> ar-EG </td>
<td> Arabic - Egypt </td>
<td> 0x0C01 </td>
<td> ARE </td>
</tr>
<tr class="gridAlternada">
<td> ar-IQ </td>
<td> Arabic - Iraq </td>
<td> 0x0801 </td>
<td> ARI </td>
</tr>
<tr class="grid">
<td> ar-JO </td>
<td> Arabic - Jordan </td>
<td> 0x2C01 </td>
<td> ARJ </td>
</tr>
<tr class="gridAlternada">
<td> ar-KW </td>
<td> Arabic - Kuwait </td>
<td> 0x3401 </td>
<td> ARK </td>
</tr>
<tr class="grid">
<td> ar-LB </td>
<td> Arabic - Lebanon </td>
<td> 0x3001 </td>
<td> ARB </td>
</tr>
<tr class="gridAlternada">
<td> ar-LY </td>
<td> Arabic - Libya </td>
<td> 0x1001 </td>
<td> ARL </td>
</tr>
<tr class="grid">
<td> ar-MA </td>
<td> Arabic - Morocco </td>
<td> 0x1801 </td>
<td> ARM </td>
</tr>
<tr class="gridAlternada">
<td> ar-OM </td>
<td> Arabic - Oman </td>
<td> 0x2001 </td>
<td> ARO </td>
</tr>
<tr class="grid">
<td> ar-QA </td>
<td> Arabic - Qatar </td>
<td> 0x4001 </td>
<td> ARQ </td>
</tr>
<tr class="gridAlternada">
<td> ar-SA </td>
<td> Arabic - Saudi Arabia </td>
<td> 0x0401 </td>
<td> ARA </td>
</tr>
<tr class="grid">
<td> ar-SY </td>
<td> Arabic - Syria </td>
<td> 0x2801 </td>
<td> ARS </td>
</tr>
<tr class="gridAlternada">
<td> ar-TN </td>
<td> Arabic - Tunisia </td>
<td> 0x1C01 </td>
<td> ART </td>
</tr>
<tr class="grid">
<td> ar-AE </td>
<td> Arabic - United Arab Emirates </td>
<td> 0x3801 </td>
<td> ARU </td>
</tr>
<tr class="gridAlternada">
<td> ar-YE </td>
<td> Arabic - Yemen </td>
<td> 0x2401 </td>
<td> ARY </td>
</tr>
<tr class="grid">
<td> hy-AM </td>
<td> Armenian - Armenia </td>
<td> 0x042B </td>
<td> </td>
</tr>
<tr class="gridAlternada">
<td> Cy-az-AZ </td>
<td> Azeri (Cyrillic) - Azerbaijan </td>
<td> 0x082C </td>
<td> </td>
</tr>
<tr class="grid">
<td> Lt-az-AZ </td>
<td> Azeri (Latin) - Azerbaijan </td>
<td> 0x042C </td>
<td> </td>
</tr>
<tr class="gridAlternada">
<td> eu-ES </td>
<td> Basque - Basque </td>
<td> 0x042D </td>
<td> EUQ </td>
</tr>
<tr class="grid">
<td> be-BY </td>
<td> Belarusian - Belarus </td>
<td> 0x0423 </td>
<td> BEL </td>
</tr>
<tr class="gridAlternada">
<td> bg-BG </td>
<td> Bulgarian - Bulgaria </td>
<td> 0x0402 </td>
<td> BGR </td>
</tr>
<tr class="grid">
<td> ca-ES </td>
<td> Catalan - Catalan </td>
<td> 0x0403 </td>
<td> CAT </td>
</tr>
<tr class="gridAlternada">
<td> zh-CN </td>
<td> Chinese - China </td>
<td> 0x0804 </td>
<td> CHS </td>
</tr>
<tr class="grid">
<td> zh-HK </td>
<td> Chinese - Hong Kong SAR </td>
<td> 0x0C04 </td>
<td> ZHH </td>
</tr>
<tr class="gridAlternada">
<td> zh-MO </td>
<td> Chinese - Macau SAR </td>
<td> 0x1404 </td>
<td> </td>
</tr>
<tr class="grid">
<td> zh-SG </td>
<td> Chinese - Singapore </td>
<td> 0x1004 </td>
<td> ZHI </td>
</tr>
<tr class="gridAlternada">
<td> zh-TW </td>
<td> Chinese - Taiwan </td>
<td> 0x0404 </td>
<td> CHT </td>
</tr>
<tr class="grid">
<td> zh-CHS </td>
<td> Chinese (Simplified) </td>
<td> 0x0004 </td>
<td> </td>
</tr>
<tr class="gridAlternada">
<td> zh-CHT </td>
<td> Chinese (Traditional) </td>
<td> 0x7C04 </td>
<td> </td>
</tr>
<tr class="grid">
<td> hr-HR </td>
<td> Croatian - Croatia </td>
<td> 0x041A </td>
<td> HRV </td>
</tr>
<tr class="gridAlternada">
<td> cs-CZ </td>
<td> Czech - Czech Republic </td>
<td> 0x0405 </td>
<td> CSY </td>
</tr>
<tr class="grid">
<td> da-DK </td>
<td> Danish - Denmark </td>
<td> 0x0406 </td>
<td> DAN </td>
</tr>
<tr class="gridAlternada">
<td> div-MV </td>
<td> Dhivehi - Maldives </td>
<td> 0x0465 </td>
<td> </td>
</tr>
<tr class="grid">
<td> nl-BE </td>
<td> Dutch - Belgium </td>
<td> 0x0813 </td>
<td> NLB </td>
</tr>
</table>
jQuery:
$( "tr" ).first().wrap( "<thead></thead>" );
(function ($) {
$.fn.freezeHeader = function (params) {
var copiedHeader = false;
var idObj = this.selector.replace('#', '');
var container;
var grid;
var conteudoHeader;
var openDivScroll = '';
var closeDivScroll = '';
if (params && params.height !== undefined) {
divScroll = '<div id="hdScroll' + idObj + '" style="height: ' + params.height + '; overflow-y: scroll">';
closeDivScroll = '</div>';
}
grid = $('table[id$="' + idObj + '"]');
conteudoHeader = grid.find('thead');
if (params && params.height !== undefined) {
if ($('#hdScroll' + idObj).length == 0) {
grid.wrapAll(divScroll);
}
}
var obj = params && params.height !== undefined
? $('#hdScroll' + idObj)
: $(window);
if ($('#hd' + idObj).length == 0) {
grid.before('<div id="hd' + idObj + '"></div>');
}
obj.scroll(function () { freezeHeader(); })
function freezeHeader() {
if ($('table[id$="' + idObj + '"]').length > 0) {
container = $('#hd' + idObj);
if (conteudoHeader.offset() != null) {
if (limiteAlcancado(params)) {
if (!copiedHeader) {
cloneHeaderRow(grid);
copiedHeader = true;
}
}
else {
if (($(document).scrollTop() > conteudoHeader.offset().top)) {
container.css("position", "absolute");
container.css("top", (grid.find("tr:last").offset().top - conteudoHeader.height()) + "px");
}
else {
container.css("visibility", "hidden");
container.css("top", "0px");
container.width(0);
}
copiedHeader = false;
}
}
}
}
function limiteAlcancado(params) {
if (params && params.height !== undefined) {
return (conteudoHeader.offset().top <= obj.offset().top);
}
else {
return ($(document).scrollTop() > conteudoHeader.offset().top && $(document).scrollTop() < (grid.height() - conteudoHeader.height() - grid.find("tr:last").height()) + conteudoHeader.offset().top);
}
}
function cloneHeaderRow() {
container.html('');
container.val('');
var tabela = $('<table style="margin: 0 0;"></table>');
var atributos = grid.prop("attributes");
$.each(atributos, function () {
if (this.name != "id") {
tabela.attr(this.name, this.value);
}
});
tabela.append('<thead>' + conteudoHeader.html() + '</thead>');
container.append(tabela);
container.width(conteudoHeader.width());
container.height(conteudoHeader.height);
container.find('th').each(function (index) {
var cellWidth = grid.find('th').eq(index).width();
$(this).css('width', cellWidth);
});
container.css("visibility", "visible");
if (params && params.height !== undefined) {
container.css("top", obj.offset().top + "px");
container.css("position", "absolute");
} else {
container.css("top", "0px");
container.css("position", "fixed");
}
}
};
})(jQuery);
$(document).ready(function () {
$("#table1").freezeHeader({ 'height': '300px' });
$("#table2").freezeHeader();
$("#tbex1").freezeHeader();
$("#tbex2").freezeHeader();
$("#tbex3").freezeHeader();
$("#tbex4").freezeHeader();
})
CSS:
#jquery-script-menu {
position: fixed;
height: 90px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #316594;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
padding: 10px 0;
-webkit-box-sizing:content-box;
-moz-box-sizing:content-box;
box-sizing:content-box;
}
.jquery-script-center {
width: 960px;
margin: 0 auto;
}
.jquery-script-center ul {
width: 212px;
float:left;
line-height:45px;
margin:0;
padding:0;
list-style:none;
}
.jquery-script-center a {
text-decoration:none;
}
.jquery-script-ads {
width: 728px;
height:90px;
float:right;
}
.jquery-script-clear {
clear:both;
height:0;
}
*{
margin:0;
padding:0;
}
body{
font-family:"Trebuchet MS", "Myriad Pro", Arial, sans-serif;
font-size:14px;
background:#fefefe;
color:#333;
text-shadow:1px 1px 1px #fff;
overflow-x:hidden;
}
h1{
font-size:30px;
color:#666;
}
h2{
font-size:20px;
padding:10px 0px 10px 0px;
margin:15px 0px 20px 0px;
}
a{
color:#555;
text-decoration:none;
}
a:hover{
color:#222;
}
p{
padding:5px 0px;
}
.wrapper{
width:960px;
margin:20px auto;
}
.clear{
clear:both;
}
/* ----------->>> GridView <<<----------*/
.gridView
{
width: 100%;
clear: both;
margin: 10px 0;
border: medium none !important;
border-collapse: collapse;
}
.gridView tr td
{
border: 1px solid #aaa;
vertical-align: top;
}
.gridView thead tr, .footer
{
font: bold 11px Arial;
vertical-align: middle;
text-decoration: none;
text-align: center;
}
/* --->>> HeaderStyle (cabeçalho) <<<---*/
.gridView thead tr
{
color: #333;
background: #fff url(../images/bg-header-grid.png) bottom repeat-x;
vertical-align: middle;
height: 25px;
}
.gridView thead tr th
{
border: 1px solid #E2E6E6;
border-bottom: 3px solid #E5E5E5;
vertical-align: middle;
}
.gridView thead tr a
{
font: bold 11px Arial, Verdana;
color: #333;
padding: 0 0 0 10px;
text-decoration: underline;
background: url(../images/Icones/ico-ordem.gif) left no-repeat;
vertical-align: middle;
}
.gridView thead tr a:hover
{
color: #06c;
background: url(../images/Icones/ico-ordem-hover.gif) left no-repeat;
}
/* ---->>> FooterStyle (rodapé) <<<------*/
.footer
{
height: 20px;
width: auto;
margin: 0 auto;
text-align: center;
padding: 5px;
}
/*PagerStyle*/
.footer a, .footer span
{
color: #555;
padding: 2px 6px 2px 6px;
border: 1px solid #bcbcbc;
background: #F1F1F1 url(../images/bg-pg.png) bottom repeat-x;
text-decoration: none;
}
.footer a:hover
{
color: #C40B17;
background-color: #fff;
background-image: none;
border: 1px solid #890812;
}
.footer span
{
color: #fff;
background: #D7403F url(../images/bg-pg-focus.png) bottom repeat-x;
border: 1px solid #890812;
}
/* ------------>>> Grid <<<--------------*/
.grid, .gridAlternada, .gridDestacada
{
font: 11px Arial,Verdana;
text-align: left;
text-align: center;
vertical-align: middle;
}
.grid:hover, .gridAlternada:hover, .gridDestacada:hover
{
color: #000;
background: #D4E5F6 url(../images/bg-dia.png) 0 0 repeat-x;
}
.grid
{
background-color: #fff;
}
/*RowStyle*/
.gridAlternada
{
background-color: #eee;
}
/*AlternatingRowStyle*/
.gridDestacada
{
background-color: #FFE082;
color: #333;
}
/*SelectedRowStyle / EditRowStyle*/
/* -------->>> Link Grid's <<<-----------*/
.grid a, .gridAlternada a, .gridDestacada a
{
color: #384249;
text-decoration: none;
}
.grid a:hover, .gridAlternada a:hover, .gridDestacada a:hover
{
color: #000;
text-decoration: underline;
}
A simple solution is after wrapping the first row in the <thead>, move the <thead> out of the <tbody> and prepend it to the table.
$( "tr" ).first().wrap( "<thead></thead>" ).parent().prependTo('.gridView');
Updated fiddle