<script>
var itemsAdded = Array();
function moveNumbers(text) {
var i = itemsAdded.indexOf(text)
if ( i >= 0) {
itemsAdded.splice(i,1);
} else {
itemsAdded.push(text);
}
document.getElementById("result1").value=itemsAdded.join(" ");
if ( i >= 0) {
} else{
itemsAdded.push(text);
}
document.getElementById("result2").value=itemsAdded.join(" ");
}
$(function() {
for (i=0;i<10;i++) {
console.log(i);
$("body").append("<input type='checkbox' name='add' value='" + i + "'
onclick='moveNumbers(this.value)'/> Checkbox" + i + "<br/>");
}
});
</script>
<table width="95%" height="24" border="1" align="center">
<tr>
<th><h2>Selected Image 5x7</h2></th>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result1" style="background:#B0D2D7;
width:100%;overflow:auto;resize:none"
readonly></textarea>
</td>
</tr>
<tr><tr>
<th><h2>Selected Image 6x8</h2></th>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result2" style="background:#B0D2D7;
width:100%;overflow:auto;resize:none"
readonly></textarea>
</td></tr>
</table>
Hi all, new at this so I apologize if it's rather messy.
I have this working but when I check the boxes the value's do appear in the text areas, but text it self is all over the place. Also need the check boxes, when unchecked to remove the text from the text area. Any ideas would be great! Hopes this makes sense...
Cheers.
It doesn't have to be so messy as you describe. Besides, I don't know how it is working for you as the structure of html is clearly broken in the current state.
Following is a bit of updated code, which I believe is equivalent to what you are trying to achieve with your snippet. DEMO
JS:
var itemsAdded = Array();
function moveNumbers() {
var text = this.value;
var i = itemsAdded.indexOf(text)
if (i >= 0) itemsAdded.splice(i, 1);
else itemsAdded.push(text);
document.getElementById("result1").value = itemsAdded.join(" ");
if (i < 0) itemsAdded.push(text);
document.getElementById("result2").value = itemsAdded.join(" ");
}
$(function () {
for (i = 0; i < 10; i++)
$("<div>Checkbox" + i + "</div>").appendTo(document.body)
.prepend($("<input type='checkbox' name='add'/>")
.val(i).click(moveNumbers));
});
HTML:
<table width="95%" height="24" border="1" align="center">
<tr>
<th>
<h2>Selected Image 5x7</h2>
</th>
</tr>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result1" readonly></textarea>
</td>
</tr>
<tr>
<th>
<h2>Selected Image 6x8</h2>
</th>
</tr>
<tr>
<td>
<textarea rows="4" cols="70" name="add" id="result2" readonly></textarea>
</td>
</tr>
</table>
CSS:
textarea {
background:#B0D2D7;
width:100%;
overflow:auto;
resize:none
}
Try this http://jsfiddle.net/KCmbm/2/
NOTE: if you are not going to use special tags like [b]: use commented code(but it will replace all occurences of supplied text);
Javscript
var itemsAdded = Array();
function moveNumbers(text) {
console.log(text);
var addedText = '[b' + text + ']' + text + '[/b]';
$('#result1').val($('#result1').val() + addedText);
//$('#result1').val($('#result1').val() + text);
console.log(addedText);
}
function removeText(text){
//$('#result1').val($('#result1').val().replace(new RegExp(text, 'g'), ''));
$('#result1').val($('#result1').val().replace('[b' + text + ']' + text + '[/b]', ''));
}
$(document).ready(function(){
$('.chkAdd').on('change', function(){
$(this).prop('checked') ? moveNumbers($(this).val()) : removeText($(this).val());
});
})
You are not attaching the on click event correctly. They don't even get fired. See this example below. Once the checkboxes are added, attach the click event. You can get the value of the element from this as shown below. JS fiddle
var itemsAdded = Array();
function moveNumbers() {
var i = itemsAdded.indexOf(this.value)
if (i >= 0) {
itemsAdded.splice(i, 1);
} else {
itemsAdded.push(this.value);
}
document.getElementById("result1").value = itemsAdded.join(" ");
if (i < 0) {
itemsAdded.push(this.value);
}
document.getElementById("result2").value = itemsAdded.join(" ");
}
$(function () {
for (i = 0; i < 10; i++) {
console.log(i);
$("body").append("<input type='checkbox' name='add' value='" + i + "'/> Checkbox" + i + "<br/>");
}
$("input:checkbox").click(moveNumbers);
});
Related
the problem here is i don't need input field required when i remove required the table still empty and another problem when i enter (not valid character)
also the table data will be deleted
i need the input field not required and when click add it adds a new row
var myInput = document.getElementById("myInput")
myTable = document.getElementById("myTable")
i = 1
num = 1
tabledata = myTable.innerHTML;
function arr() {
if(myInput.value!=""){
if(/^[a-z]+$/i.test(myInput.value)){
if (num % 2 == 0) {
myTable.innerHTML = myTable.innerHTML + '<tr style="background:#ff8000"><td>' + i + '</td><td>' + myInput.value + "</td></tr>";
myInput.value = "";
i++;
} else {
myTable.innerHTML = myTable.innerHTML + '<tr style="background:#ffb366"><td>' + i + '</td><td>' + myInput.value + "</td></tr>";
myInput.value = "";
i++;
}
num++;
}
else {
alert("Please Enter A Valid Charceter");
}
}else{
alert("This Field Is Reqiured Please Enter Your Name")
}};
function res() {
myTable.innerHTML = "<tr> <th>Id</th> <th>Name</th> </tr>";
i = 1;
num = 1;
}
<h1>Enter Your Name</h1>
<form>
<input type="text" id="myInput" required/>
<button onclick="arr()">Add</button>
</form>
<table id="myTable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
<button onclick ="res()">Reset</button>
I didn't fully understand what you need, but I see here a little bit flaw:
When you click the "Add" button, the form is submitting, so you need to break this.
Try it:
<style>
#myTable tr {
background: #FF8000
}
#myTable tr:nth-child(odd){
background: #FFB366
}
</style>
<h1>Enter Your Name</h1>
<form id="myForm">
<input type="text" id="myInput" required />
<input type="submit" />
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody id="myTable"></tbody>
</table>
<button id="myButton">Reset</button>
<script>
(function(){
"use strict";
var
form = document.getElementById("myForm"),
input = document.getElementById("myInput"),
table = document.getElementById("myTable"),
reset = document.getElementById("myButton");
form.addEventListener("submit", add, true);
function add(event){
event.preventDefault();
if( /^[a-z]+$/i.test(myInput.value) )
table.innerHTML += '<tr><td>' + (table.children.length + 1) + '</td><td>' + input.value + '</td></tr>';
return input.value = '';
}
function reset(){
table.innerHTML = '';
}
})()
</script>
I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?
Here's a jsfiddle http://jsfiddle.net/SuRWn/
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th>
</tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td >
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
Javascript:
<script type="text/javascript">
//<!--
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for ( var i = 0; i < rows.length; i++ ) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if ( fullname ) {
if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
//-->
</script>
checking with chrome console, it seems that innerHtml for the 'fullname' is returning an error:
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
That's because the first tr tag you have is in the thead and it doesn't have any td at all. Changing the start of your loop to 1 will fix that:
for ( var i = 1; i < rows.length; i++ ) { //... and so on
yuvi is correct in his answer. I've incorporated this in a fiddle - http://jsfiddle.net/dBs7d/8/ - that also contains the following changes:
Inputs with course and subject grouped into individual rows.
td tags align underneath th tags.
Code refactored to improve readability.
Instead of checking the html of the td tags I've changed it to check the value attribute of the input tags. This means you can change the value of the input and still search.
I also changed the style alteration to use backgroundColor. This can easily be reverted to display.
See this link.
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th>Course</th>
<th>Subject</th>
<th>COURSE CODE</th>
<th>COURSE NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="course" /></td>
<td><input type="text" value="subject" /></td>
</tr>
<tr>
<td><input type="text" value="course1" /></td>
<td><input type="text" value="subject1" /></td>
</tr>
<tr>
<td><input type="text" value="course2" /></td>
<td><input type="text" value="subject2" /></td>
</tr>
</tbody>
</table>
Search here (with jQuery):<input type="text" size="30" value="" onKeyUp="doSearchJQ(this);" /><br />
Search here:<input type="text" size="30" value="" onKeyUp="doSearch(this);" />
Javascript:
function doSearchJQ(input) {
var value = $(input).val();
if (value.length > 0) {
$("#results tbody tr").css("display", "none");
$('#results input[value^="' + value + '"]').parent().parent().css("display", "table-row");
} else {
$("#results tbody tr").css("display", "table-row");
}
}
function doSearch(input){
var value = input.value;
var table = document.getElementById('results');
var tbody = table.querySelector("tbody");
var rows = tbody.querySelectorAll("tr");
var visible, row, tds, j, td, input;
for (var i = 0; i < rows.length; i++) {
visible = false;
row = rows[i];
tds = row.querySelectorAll("td");
for (j = 0; j < tds.length; j++) {
td = tds[j];
input = td.querySelector("input");
console.log(input.value.indexOf(value));
if (input.value.indexOf(value) > -1) {
visible = true;
break;
}
}
if (visible) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
}
}
With jquery it's more compact function. But you can use clear javascript doSearch.
Why don't you use JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:
The plugin is well-documented, and widely used. It should be very easy to drop in into an existing application, and style it accordingly.
Hope this helps!
Include two IDs into one variable, for example
var optionValue=document.getElementById('Input1' + " " + 'Input2');
That code does not work but is there any similar code that would do this?
JS
function addNewListItem(){
var htmlSelect=document.getElementById('list');
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var optionDisplaytext = value1 + " " + value2;
var selectBoxOption = document.createElement("option");
selectBoxOption.value = optionValue.value;
selectBoxOption.text = optionDisplaytext.value;
htmlSelect.add(selectBoxOption, null);
alert("Option has been added successfully");
return true;
}
HTML
<table border="0" align="left">
<tr>
<td rowspan="2">
<select name="list" id="list" size="10" style="width:150px">
</select>
</td>
<tr>
<td align="right">Option Value</td>
<td align="left"><input name="Input1" type="text" id="Input1" /></td>
</tr>
<tr>
<td align="right">Option Display Text</td>
<td align="left"><input name="Input2" type="text" id="Input2" /></td>
</tr>
<tr>
<td align="right"> </td>
<td align="left"><input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javaScript:addNewListItem();" /></td>
</tr>
</table>
I've tried the above code but it will not add to a listbox?
it just says undefined in the box
Elements are text inputs ? Then somethink like below will work :
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
Further to a comment I left, here's a full example.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('mBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick()
{
var value1 = document.getElementById('Input1').value;
var value2 = document.getElementById('Input2').value;
var optionValue = value1 + " " + value2;
var newOpt = newEl('option');
newOpt.value = optionValue; // this line sets the value given to a form by this option
newOpt.appendChild( newTxt(optionValue) ); // this line adds the text viewable on the page
byId('mSelect').appendChild(newOpt);
}
</script>
<style>
</style>
</head>
<body>
<label>Input 1: <input id='Input1' value='value1'/></label>
<label>Input 2: <input id='Input2' value='value2'/></label>
<br>
<select id='mSelect'></select><button id='mBtn'>Add to list</button>
</body>
</html>
I interpreted your question as follows:
Get n-number of elements by id.
You can do this with the following block:
HTML
<span id="foo">Foo</span>
<span id="bar">Bar</span>
<span id="foo1">Foo</span>
<span id="bar1">Bar</span>
JS
var nodes = document.querySelectorAll('#foo, #bar');
console.log(nodes);
You can then derive any data you want from each matched node.
This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 9 years ago.
I have a table to allow user to do multiple stock entry
<table class="table1" id="table1">
<thread>
<tr>
<th scope="col">Item Name</th>
<th scope="col">Qty</th>
<th scope="col">Rate</th>
<th scope="col">Amount</th>
</tr>
</thread>
<tbody>
<tr>
<td><input type="text"/></td>
<td><input type="text" class="num" id="qty"/></td>
<td><input type="text" class="num" id="rate"/></td>
<td><input type="text" class="num" id="amt"/></td>
</tr>
</tbody>
</table>
<a id="add"><button>Add</button></a>
And this code is to add a new row:
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newrow = $("<tr><td><input type="text"/></td><td><input type=\"text\" id=\"qty\"/></td><td><input type="\text\" id="\rate\"/></td><td><input type="\text\" id="\amt\"/></td></tr>");
newrow.insertAfter('#table1 tbody>tr:last');
return false;
});
$(".num").keyup(function() {
var id = $(this).attr('id');
if (id == 'qty') {
var i = parseFloat($("#rate").val())
if (!isNaN(i)) {
var t = ($(this).val()*$("#rate").val());
$("#amt").val(t.toFixed(2));
} else {
$("#amt").val('');
}
} else if (id == 'rate') {
var i = parseFloat($("#qty").val())
if (!isNaN(i)) {
var t = ($(this).val()*$("#qty").val());
$("#amt").val(t.toFixed(2));
} else {
$("#amt").val('');
}
}
});
});
The calculation is working perfect on the first row of table, but when I am adding a second row the calculation is not working. Where I am wrong?
Use event delegation:
$('body').on('keyup', ".num", function() {
// your code
});
Also you must add class .num to your created elements,
and you can't have the same ID for multiple elements, instead
use another attribute (like data-id, it doesn't matter),
var newrow = $('<tr><td><input type="text" /></td><td><input type="text" class="num" data-id="qty"/></td><td><input type="text" data-id="rate"/></td><td><input type="text" class="num" data-id="amt" /></td></tr>');
And in your function get them with this attribute:
$('body').on('keyup', ".num", function() {
var $row = $(this).closest('tr');
var $amt = $row.find('[data-id="amt"]');
var $qty = $row.find('[data-id="qty"]');
var $rate = $row.find('[data-id="rate"]');
var id = $(this).attr('data-id');
if (id == 'qty') {
// now using `$rate` instead of $('#rate')
var i = parseFloat($rate.val())
// other code
}
// other code
});
Give the new rows the num class (your new inputs don't have it), and use .on:
$(document).on('keyup', '.num', function() {
});
This is required if you want to add an event listener to elements that are not yet in the DOM.
Also, element IDs should be unique. Your new inputs are getting the same ID as the previous row.
try this
<table class="table1" id="table1">
<thread>
<tr>
<th scope="col">Item Name</th>
<th scope="col">Qty</th>
<th scope="col">Rate</th>
<th scope="col">Amount</th>
</tr>
</thread>
<tbody>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" class="num" name="qty" id="qty" />
</td>
<td>
<input type="text" class="num" id="rate" name="rate" />
</td>
<td>
<input type="text" class="num" id="amt" name="amt" />
</td>
</tr>
</tbody>
</table>
<a id="add">
<button>
Add</button></a>
<script type="text/javascript">
$(document).ready(function () {
$("#add").click(function () {
var newrow = $('<tr><td><input type="text"></td><td><input type="text" id="qty" name="qty" class="num"></td><td><input type="text" id="rate" name="rate" class="num"></td><td><input type="text" id="amt" name="amt" class="num"></td></tr>');
newrow.insertAfter('#table1 tbody>tr:last');
$('#table1 tbody>tr:last').find('[name="qty"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="rate"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="rate"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
$('#table1 tbody>tr:last').find('[name="rate"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="qty"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="qty"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
return false;
});
$('[name="qty"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="rate"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="rate"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
$('[name="rate"]').keyup(function () {
var this_tr = $(this).closest('tr');
;
var i = parseFloat(this_tr.find('[name="qty"]').val())
if (!isNaN(i)) {
var t = ($(this).val() * this_tr.find('[name="qty"]').val());
this_tr.find('[name="amt"]').val(t.toFixed(2));
} else {
this_tr.find('[name="amt"]').val('');
}
});
});
</script>
This issue can be solved via event delegation to the existing closet parent like in your case is $('#table1') or $(document) which is the parent of all the elements on a page, so you need to change this:
$(".num").keyup(function() {
to this:
$("#table").on('keyup', '.num', function() {
I just seen your additions you are adding same ids when clicked to add, so that results in a invalid html markup due to ids should be unique in the same page (same ids for multiple elems is invalid).
var newrow = $("<tr><td><input type='text'/></td>"+
"<td><input type='text' id='qty'/></td>"+
"<td><input type='text' id='rate'/></td>"+
"<td><input type='text' id='amt'/></td></tr>");
The above one everytime adds same id for multiple elements when added to the dom. you can try to do this way:
$("#add").click(function () {
var i = $("#table1 tbody>tr:last").index();
var newrow = $("<tr><td><input type='text'/></td>" +
"<td><input type='text' class='num' id='qty" + (i) + "'/></td>" +
"<td><input type='text' class='num' id='rate" + (i) + "'/></td>" +
"<td><input type='text' class='num' id='amt" + (i) + "'/></td>");
newrow.insertAfter('#table1 tbody>tr:last');
return false;
});
I've a multiple number of rows which is generated by a for condition, with 2 icons up and down. On click of up the selected row should move one step up, and on click of down the selected row should move one step down
<html>
<head>
<body>
<form name="myForm">
<table id="mainTable" border="1" width="100%">
<script>
document.write('<tr>')
document.write('<td>')
document.write('row1')
document.write('</td>')
document.write('</tr>')
document.write('<tr>')
document.write('<td>')
document.write('row2')
document.write('</td>')
document.write('</tr>')
document.write('</table>')
document.write('<table>')
document.write('<tr>')
document.write('<td>')
document.write('<input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"</input>')>
document.write('<input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"</input>')>
document.write('</td>')
document.write('</tr>')
document.write('</table>')
</script>
</table>
</form>
</body>
</head>
</html>
<script>
var mainTable = document.getElementById("mainTable");
function getRowIndex(el)
{
while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );
if( el )
alert(el.rowIndex);
return el.rowIndex;
}
function swapRowUp(chosenRow) {
if (chosenRow.rowIndex != 0) {
moveRow(chosenRow, chosenRow.rowIndex-1);
}
}
function swapRowDown(chosenRow) {
if (chosenRow.rowIndex != mainTable.rows.length-1) {
moveRow(chosenRow, chosenRow.rowIndex+1);
}
}
function moveRow(targetRow, newIndex) {
if (newIndex > targetRow.rowIndex) {
newIndex++;
}
var mainTable = document.getElementById('mainTable');
var theCopiedRow = mainTable.insertRow(newIndex);
for (var i=0; i<targetRow.cells.length; i++) {
var oldCell = targetRow.cells[i];
var newCell = document.createElement("TD");
newCell.innerHTML = oldCell.innerHTML;
theCopiedRow.appendChild(newCell);
copyChildNodeValues(targetRow.cells[i], newCell);
}
//delete the old row
mainTable.deleteRow(targetRow.rowIndex);
}
function copyChildNodeValues(sourceNode, targetNode) {
for (var i=0; i < sourceNode.childNodes.length; i++) {
try{
targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
}
catch(e){
}
}
}
</script>
i'm unable to perform the swap operation, i get cellIndex as null
You can use some sensible JavaScript
up.addEventListener("click", function moveRowUp() {
var row = this.parentNode.parentNode,
sibling = row.previousElementSibling,
parent = row.parentNode;
parent.insertBefore(row, sibling);
});
for some sensible HTML
<table>
<tbody>
<tr>
<td> 1 </td>
<td> filler </td>
</tr>
<tr>
<td> 2 </td>
<td> <button id="up">up</button> </td>
</tr>
</tbody>
</table>
Live Example