I'm currently starting on a little project
I have this input which will push items to an array. My problem is everytime I push object using the button it will display some duplicate objects inside my table.
var tasks = [];
var count = 0;
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var id = Date.now();
item = {};
item["id"] = id;
item["description"] = desc;
tasks.push(item);
if (!desc) {
item["id"] = "";
alert("Input a description");
}
var tbl = $("<table/>").attr("id", "mytable");
$("#mylist").append(tbl);
for (var i = 0; i < tasks.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + tasks[i]["id"] + "</td>";
var td2 = "<td>" + tasks[i]["description"] + "</td>";
$("#mytable").append(tr + td1 + td2);
};
//clear input field
$('#list-input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input id="list-input" />
<button id="add">Add To List</button>
<button id="delete">Remove From List</button>
</div>
<div class="container">
<h1>Your List</h1>
<div id="mylist">
</div>
<button id="clear">clear</button>
</div>
If you take out the loop and just get the last one in the array you are pushing to, it will solve your problem
EDIT: This way, if you want to use the tasks in some other function, it doesn't clear it out
EDIT 2: Made it to where it would only append the table if no id of that kind was found, makes it cleaner I think
var tasks = [];
var count = 0;
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var id = Date.now();
item = {};
item["id"] = id;
item["description"] = desc;
tasks.push(item);
if (!desc) {
item["id"] = "";
alert("Input a description");
}
if(!$("#mytable").length){ //Checks if mytable id exists
var tbl = $("<table/>").attr("id", "mytable");
$("#mylist").append(tbl);
}
var tr = "<tr>";
var td1 = "<td>" + tasks[tasks.length-1]["id"] + "</td>";
var td2 = "<td>" + tasks[tasks.length-1]["description"] + "</td>";
$("#mytable").append(tr + td1 + td2);
//clear input field
$('#list-input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input id="list-input" />
<button id="add">Add To List</button>
<button id="delete">Remove From List</button>
</div>
<div class="container">
<h1>Your List</h1>
<div id="mylist">
</div>
<button id="clear">clear</button>
</div>
You have the initialisation of the table repeated every time an addition is made.
Try this instead:
var tasks = [];
var count = 0;
$(function(){
var tbl=$("<table/>").attr("id","mytable");
$("#mylist").append(tbl);
for(var i=0;i<tasks.length;i++)
{
var tr="<tr>";
var td1="<td>"+tasks[i]["id"]+"</td>";
var td2="<td>"+tasks[i]["description"]+"</td>";
$("#mytable").append(tr+td1+td2);
};
});
$('#add').click(function(){
var desc = $.trim($('#list-input').val());
var id = Date.now();
item = {};
item ["id"] = id;
item ["description"] = desc;
tasks.push(item);
if (!desc){
item ["id"] = "";
alert("Input a description");
}
var tr="<tr>";
var td1="<td>"+item["id"]+"</td>";
var td2="<td>"+item["description"]+"</td>";
$("#mytable").append(tr+td1+td2);
//clear input field
$('#list-input').val('');
});
<div class="container">
<input id="list-input" />
<button id="add">Add To List</button>
<button id="delete">Remove From List</button>
</div>
<div class="container">
<h1>Your List</h1>
<div id="mylist">
</div>
<button id="clear">clear</button>
</div>
Updated the answer you can avoid using array and can achieve the desired by using some appropriate selectors
var count = 0;
var tbl = $("<table/>").attr("id", "mytable");
$("#mylist").append(tbl);
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var id = Date.now();
if (!desc) {
alert("Input a description");
return false;
}
var tr = "<tr>";
var td1 = "<td>" + id + "</td>";
var td2 = "<td>" + desc + "</td>";
$("#mytable").append(tr + td1 + td2);
//clear input field
$('#list-input').val('');
});
$('#delete').click(function() {
var desc = $.trim($('#list-input').val());
if (!desc) {
alert("Input a description");
return false;
}
var td = $("td").filter(function() {
return $(this).text() == desc;
});
var row = td.parent();
row.remove();
$('#list-input').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input id="list-input" />
<button id="add">Add To List</button>
<button id="delete">Remove From List</button>
</div>
<div class="container">
<h1>Your List</h1>
<div id="mylist">
</div>
<button id="clear">clear</button>
</div>
Related
I have used following code to develop sentence grammar practice. When I click button then order should to maintained. I want it when button clicked then it should hide but after click on top button again show up.
Move sentence to left if there is blank. Also show button again if words clicked again.
Should using only buttons for showing at top also at bottom?
<html>
<head>
<title>
</title>
</head>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for(i=0;i<senArr.length;i++)
{
//alert(senArr[i]);
dashElement += "<div onclick='funDiv(this.id);' style='display: inline'" + "id = dashid" + i + ">" + '__ ' + '</div>';
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
//var dashID = document.getElementById("dashid0").innerHTML;
//var dash1 = document.getElementById("val");
//dash1.innerHTML= dashID;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='fun(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var ii = 0;
function funDiv(clicked){
//alert(clicked);
var inText = document.getElementById(clicked).innerHTML;
document.getElementById(clicked).innerHTML = " __ " ;
ii--;
}
function fun(clicked){
//alert(clicked);
document.getElementById(clicked).style.display = "none";
document.getElementById("dashid" + ii).innerHTML = document.getElementById(clicked).innerHTML + " ";
//document.getElementById(clicked).remove();
ii++;
}
</script>
</script>
</body>
</html>
How about something like this?
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<div id="val"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
for (var i = 0; i < senArr.length; i++) {
dashElement += `<div onclick='dashClick(this.id);' style='display: inline' id=dash${i}> __ </div>`;
}
var dash = document.getElementById("dash");
dash.innerHTML = dashElement;
var htmlElements = "";
for (var i = 0; i < senArr.length; i++) {
htmlElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'>" + senArr[i] + '</button>';
}
var container = document.getElementById("container");
container.innerHTML = htmlElements;
var picked = 0;
function dashClick(clicked) {
const dash = document.getElementById(clicked);
dash.innerHTML = " __ ";
const btn = document.getElementById(`btn${dash.btnId}`);
btn.style.display = "inline";
picked--;
}
function btnClick(clicked) {
var btnId = clicked.replace('btn', '');
document.getElementById(clicked).style.display = "none";
const dash = document.getElementById("dash" + picked)
dash.innerHTML = document.getElementById(clicked).innerHTML + " ";
dash.btnId = btnId;
picked++;
}
</script>
</body>
</html>
I have implemented it using appendChild and remove functions of JavaScript.
<html>
<body>
<div id="sen">I am learning JavaScript by developing a simple project.</div>
<br>
<div id="dash"></div>
<br>
<div id="container"></div>
<script>
var sen = document.getElementById("sen").innerHTML;
var senTrim = sen.trim();
var senArr = senTrim.split(/\s+/);
var dashElement = "";
var btnElements = "";
for (var i = 0; i < senArr.length; i++) {
btnElements += "<button onclick='btnClick(this.id);' id = 'btn" + i + "'> " + senArr[i] + ' </button>';
}
var container = document.getElementById("container");
container.innerHTML = btnElements;
var picked = 0;
function dashClick(clicked) {
//console.log(clicked);
var buttons = document.getElementsByTagName('button');
var dash = document.getElementById("dash");
dashChild = dash.childNodes;
console.log(document.getElementById(clicked).innerText);
for(i=0;i<senArr.length;i++){
if(document.getElementById(clicked).innerText.trim() == buttons[i].innerText.trim()){
//console.log("Match");
buttons[i].style.opacity = "1";
buttons[i].style.pointerEvents = "auto";
}
}
document.getElementById(clicked).remove(); // remove clicked text
}
// Button click
function btnClick(clicked) {
var dashElement = document.createElement("div");
var text = document.getElementById(clicked).innerText;
dashElement.style.display = "inline";
dashElement.innerHTML = "<div style='display: inline' onclick='dashClick(this.id);' id=" + picked +"> " + text + " </div>"; // add text at top of button
document.getElementById("dash").appendChild(dashElement);
picked++;
document.getElementById(clicked).style.opacity = "0"; //hide button that has been clicked
document.getElementById(clicked).style.pointerEvents = "none";
}
</script>
</body>
</html>
I have two functions - one takes a URL in a certain format (e.g. "test.com?action=query&max_results=20") and breaks it down into dynamically generated textboxes for editing. The other puts it back together along with any edits. Both functions are called by clicking a button.
The second function is unable to find the ids of the dynamically generated textboxes - they're coming back as "null". How do I get the function to recognise ids created after the page loads?
Code:
<script>
function Split()
{
//Get table body for insert
var table = document.getElementById("ValueTableBody");
//Clear table of rows
table.innerHTML = '';
//Grab URL
var URLquery = document.getElementById("oldquery").value;
//Split on ? to isolate query
var querysplit = oldquery.split("?");
//Store main url
var mainURL = document.getElementById('mainURL');
mainURL.value=querysplit[0];
//Split on & to isolate variables
var splitagain = querysplit[1].split("&");
var i = 0;
//Loop on number of variables in query
for(i = 0; i < splitagain.length; i++){
//Split on = to isolate variables and values
var splitthird = splitagain[i].split("=");
//Insert new row into table
var row = table.insertRow(i);
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '"/>';
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
}
}
function Unsplit()
{
var mainURL = document.getElementById('mainURL').value;
var completequery = [];
var URLarray = [];
var rowCount = document.getElementById('ValueTableBody').rows.length;
for(i = 0; i <= rowCount; i++){
//Get variable of current row
var value1 = document.getElementById('query' + i).value;
//Get value of current row
var value2 = document.getElementById('queryvalue' + i).value;
if (value1) {
if (value2) {
//If both have value, then push into array
valueArray = [];
valueArray.push(value1);
valueArray.push(value2);
//Merge into one to push into next array
var newvalue = valueArray.join("=");
URLarray.push(newvalue);
}
}
}
//Join all sections of the query together
mergearray = URLarray.join("&");
//Push mainURL
completequery.push(mainURL);
//Push completed query
completequery.push(mergearray);
//Join the query together to make complete new URL
mergearray2 = completequery.join("?");
//Display new URL
var newquery = document.getElementById('newquery');
newquery.value=mergearray2;
//Output new URL to iframe
document.getElementById('webservicedisplay').src = mergearray2;
}
</script>
HTML:
<div style="float:left;">
<h1>Webservice Tester</h1>
<p><label style="font-weight:bold; display:inline-block; vertical-align:top;">Old Webservice Call:</label> <textarea cols="60" rows="4" id="oldquery"></textarea></p>
<input type="submit" name="button" id="splitbutton" onclick="Split()" value="Split!" /> <br><br>
<p><label style="font-weight:bold;">URL:</label> <input type="text" size="50" id="mainURL"></input></p><br>
<table id="ValueTable">
<thead>
<th>Variable</th>
<th>Value</th>
</thead>
<tbody id="ValueTableBody">
</tbody>
</table>
<br>
<p><input type="submit" name="button" id="unsplit" onclick="Unsplit()" value="Unsplit!" /></p> <br><br>
<p><label style="font-weight:bold; vertical-align:top;">New Webservice Call:</label> <textarea cols="60" rows="4" id="newquery"></textarea></p>
</div>
<div style="float:left; padding-left:20px;">
<p><label style="font-weight:bold;">Output:</label></p><br>
<iframe height="450" width="500" id="webservicedisplay" src="">
</iframe>
This was fixed by the author because the 'issue was actually the loop having the "<=" condition - it was looking for one more table row that didn't exist.'
I had suggested to write the JS differently as so:
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '" value="' + splitthird[0] + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '" value="' + splitthird[1] + '"/>';
And remove:
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}
I need to read the value of textbox which is inside the table.
Following is how I create table.
var theader = '<table border = "1" id = "MarksTable">\n';
var tbody = '';
for ( var i = 0; i < total_rows; i++) {
tbody += '<tr>';
for ( var j = 0; j < total_col; j++) {
tbody += '<td name=' + "cell" + i + j + '>';
if (i > 0) {
tbody += '<input type="text" value = "marks" name="inputcell1'+j + '">';
} else {
tbody += '<b>' + subjectList[j] + '</b>';
}
tbody += '</td>';
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader
+ tbody + tfooter ;
and below is my attempt to read text box value:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].innerHTML;
}
}
return marks;
}
Here, row.cells[index].innerHTML gives the output '<input type="text" value = "marks" name="inputcell10">.
Try this:
function readTableData(){
var marks = [];
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var row = table.rows[1];
if(column_count>0){
for(var index = 0; index < column_count;index++){
marks[index] = row.cells[index].getElementsByName('inputcell' + index)[0].value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
return marks;
}
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<div id="tableContainer">
</div>
<br>
<button onclick="myFunction()">Try it</button>
<button onclick="readTableData()"> Read it </button>
<script>
function myFunction() {
var tab = '<table id="MarksTable">';
var counter = 0;
for(i = 0; i< 4; i++){
tab = tab + '<tr><td rowspan = "4"> Dept1 </td><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
tab = tab+'<tr><td> <input type="text" id="inputcell'+counter+'" value="'+i+'"/> </td></tr>';
counter++;
}
tab = tab + '</table>';
document.getElementById("tableContainer").innerHTML = tab;
}
function readTableData(){
var val;
var table = document.getElementById("MarksTable");
var column_count = table.rows[1].cells.length;
var rowcount = table.rows.length;
alert(rowcount);
if(column_count>0){
for(var index = 0; index < rowcount;index++){
var row = table.rows[index];
val = document.getElementById("inputcell"+index);
alert(val.value);
//marks = row.cells[0].getElementsByName('inputcell').value;
//Or marks[index] = document.getElementsByName('inputcell' + index)[0].value;
}
}
alert(val);
}
</script>
</body>
</html>
This is all my code I hope you can see where I'm going wrong.
var $randomnumber1;
var $randomnumber2;
var $answer;
var $counter = 1;
var $data;
function start_game() {
document.getElementById('counternumber').innerHTML = $counter;
document.getElementById('txtbox').value = "";
$randomnumber1 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
$answer = $randomnumber1 + $randomnumber2;
$counter++;
setFocus();
}
function check_answer() {
var $txt = document.getElementById('txtbox');
var $value = $txt.value;
if ($value == $answer) {
alert('You are correct');
}
else {
alert('You are incorrect, the answer was ' + $answer);
}
document.getElementById('txtbox').value = "";
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
$randomnumber1 = Math.floor(Math.random()*11);
$randomnumber2 = Math.floor(Math.random()*11);
document.getElementById('num1').innerHTML = $randomnumber1;
document.getElementById('num2').innerHTML = $randomnumber2;
$answer = $randomnumber1 + $randomnumber2;
document.getElementById('counternumber').innerHTML = $counter;
$counter++;
if ($counter > 4) {
alert ('End of game......Thanks for playing');
$counter = 1;
document.getElementById('num1').innerHTML = "";
document.getElementById('num2').innerHTML = "";
}
function addAnswers() {
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
<div class="container" id="wrapper">
<h3>Games Played = <b id='counternumber'></b> / 3 </h3>
<div id="total">Total: <p id="sumtotal"></p></div>
<div class="left"><h3 id="num1"></h3></div>
<div class="plus"><img src="images/plus.png"></div>
<div class="right"><h3 id="num2"></h3></div>
<button onclick="start_game(); myCountDown()">Start Game</button>
<form id="form">
<input type="text" id="txtbox" />
<input type="button" value="Answer" onclick="check_answer(); setFocus(); ShowResults(); sumResults()" />
</form>
</div>
home page
</div> <!-- /content -->
<div id="aside">
</div>
You could use this:
function addAnswers()
{
var data = $randomnumber1 + " + " + $randomnumber2 + " = " + ($randomnumber1+$randomnumber2)
var newListItem = document.createElement('li');
var newText = document.createTextNode(data);
newListItem.appendChild(newText);
document.getElementById("ans").appendChild(newListItem);
}
Your question is unclear, but this should be something along the lines of what you're looking for. What you have to do is add a <ul> with the id of ans and this function will append li components to it (your answers) every time you run it. The answer itself will be stored into data.
Try it - if you want help customizing it, please update your answer.