how to identify the radio button in javascript - javascript

I am creating a dynamic table in which each row has a group of radio buttons placed in different columns.
I want to change the cell background color when a radio button is clicked.I am constructing the table using the code snippet below. How to identify the radio button in javascript, so that I can set the cell with an appropriate background color.
<table>
<c:forEach>
<tr>
<c:forEach>
<td><input type="radio" value="" /></td>
</c:forEach>
</tr>
</c:forEach>
</table>

Use dojo or jQuery to select the radioButton node, then use CSS filter expressions to set the td tag (parentNode dom node) to whatever color you want.
Example using dojo :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Dojo selectors example</title>
<script type="text/javascript">
var djConfig = {
parseOnLoad: true,
isDebug: true,
locale: 'en-us'
};
</script>
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.4.1/dojo/dojo.xd.js"></script>
<script type="text/javascript">
dojo.addOnLoad(function() {
// Get all the radioButtons that are inside a <td> tag
dojo.query("td > input").forEach(function(node, index, array){
var td = node.parentNode;
dojo.addClass(td, "red");
dojo.connect(td, "onclick", function(){dojo.toggleClass(td, "white");});
});
});
</script>
<style type="text/css">
.red { background-color : red; }
.white { background-color : white; }
</style>
</head>
<body>
<form id="form1">
<table>
<tr>
<td><input type="radio" value="" /></td>
</tr>
<tr>
<td><input type="radio" value="" /></td>
</tr>
<tr>
<td><input type="radio" value="" /></td>
</tr>
</table>
</form>
</body>
</html>
I'll leave it up to you to correct the radiobutton's behaviour...

you should try and set a unique id for the input field when creating it (e.g. id="theradiobutton")
Then you can reference it easily using DOM methods!

You need to set the id or use a fake class name.
Later I should use jquery for accessing and changing them.
http://www.google.es/search?rlz=1C1GGLS_esES361ES361&sourceid=chrome&ie=UTF-8&q=radio+button+jquery

var myform = document.forms['myform'];
for ( var i=0; i < myform.elements; i++ )
if ( myform.elements[i].type == 'radio' ) ...do your stuff
Hope it helps.

It's simple with jQuery. Here's an SSCCE, copy'n'paste'n'run it.
<!doctype html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#tableId input[name=row]').click(function() {
$('#tableId tr').removeClass('selected'); // Reset.
$(this).parents('tr').addClass('selected');
});
});
</script>
<style>
tr.selected {
background: #ffc;
}
</style>
</head>
<body>
<table id="tableId">
<tr><td><input type="radio" name="row" value="row1">row1</td></tr>
<tr><td><input type="radio" name="row" value="row2">row2</td></tr>
<tr><td><input type="radio" name="row" value="row3">row3</td></tr>
</table>
</body>
</html>
Just translate the table back into the dynamic flavor you've had with JSP/JSTL.

Without getting too fussy about it, this is really pretty simple. You don't need to identify the radio button, just call an event handler and pass the instance of the button with it:
<td><input type="radio" value="" onclick="colorMyCell(this)" /></td>
and the handler:
function colorMyCell(inp) {
// get reference to the row
var tr = inp.parentNode.parentNode;
// put the TD children of the row into an array
var cells = tr.getElementsByTagName("TD");
// bgcolor all the other cells in that row white
for (var i=0; i<cells.length; i++) {
cells[i].style.backgroundColor = "#ffffff";
}
// now bgcolor the selected cell differently
inp.parentNode.style.backgroundColor = "#ffffcc";
}
Note that this is just a quick and dirty example of how to do this. You would want to take more care with it (make sure inp.parentNode.parentNode really is a TR, if not find a better way to work your way up the tree to find the actual first-ancestor TR), as well as using CSS classNames instead of directly setting background colors, and so on.

Related

Obtaining value from td in a row where input button was clicked (using jQuery)

I am having troubles getting a value from a td using jQuery.
It keeps saying "undefined" or no result comes out however I edited my code.
I do not know what's wrong...
Here's my code:
(originally, data from mySQL DB should be there in the table. but I omitted them in order to make question briefer)
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var currentrow=$(this).closest('tr');
var item=currentrow.find('.id').text();
alert("delete item number:".item);
});
$(".approve").click(function(){
alert("approve!");
});
$(".edit").click(function(){
alert("edit!");
});
});
</script>
</head>
// Table that contains data
<body>
<table>
<tr>
<td class='id'>
</td>
<td>
</td>
<td>
<input type='button' class='delete' value='Delete'/>
</td>
<td>
<input type='button' class='approve' value='Approve'/>
</td>
<td>
<input type='button' class='edit' value='Edit'/>
</td>
</tr>
</table>
</body>
</html>
find() using a class will return an array of elements. You need to grab the first element and then perform the text lookup, like this:
var item=$(currentrow.find('.id')[0]).text();
Also, in Javascript you concatenate strings using + (and not using . like in PHP)
alert("delete item number:" + item);

JQuery/Ajax function not working for a new row generated

I'm trying to implement a function for a dinamic table, the table starts like this:
<table>
<thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
<tbody id="bodyVender">
<tr>
<td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
</tr>
</tbody>
</table>
And then i'm adding more table rows to the tbody when the JQuery function is called, like this:
$('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');
As you can see, the new row created will have tds and inputs with a new ID determined by the "count" variable, so that input ID could look like: inp0 , inp1, inp2 after each function call.
This works, but just the first time, even when I'm calling the function for that new created ID.
I'm using $(document).on to call the function, and I think that should work for the new row created.
Here's the entire code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Panel de Administración</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="estilo3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(Principal);
function Principal(){
var count = 0; //sell's counter
$(document).on('keydown','#inp'+String(count), function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
function VenderConsulta(Codigo,ntd){
datos={codigo:Codigo}; // the code to send
$.ajax({
url:"bringMeTheData.php",
type: "POST",
data: datos,
success: function(datos){
console.log(datos); //i'm recibing something like [{"Nombre":"A product name","P_venta":"990"}]
count+=1; //next time i'll choose the new input with id="inp1"
$(':focus').blur(); //blur the input
var arr = JSON.parse(datos);
var tdNombre = arr[0].Nombre;
var tdPrecio = arr[0].P_venta;
$('#tdN'+ntd+'').html(tdNombre);
$('#tdC'+ntd+'').val(1);
$('#tdP'+ntd+'').html(tdPrecio);
$('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');
$('#inp'+count).focus(); //setting focus to the new created input
}
});
}
}
</script>
</head>
<body>
<div class="container-fluid">
<section class="tablaVender">
<div class="row">
<div class="table-responsive" style="background:white">
<h3 style="margin-left:15px"> Venta de productos </h3>
<table class='table table-hover table-bordered'>
<thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
<tbody id="bodyVender">
<tr> <!-- This is the input and i'll add more trs like this in the function VenderConsulta -->
<td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Why this works just the first time and then no more? I'm working wrongly with that new row created?
Sorry for my bad english and thanks.
Your selector for the keydown function will only trigger it for the first input. You only call .on() once, and you give it '#inp'+String(count) as the selector. Your variable count is 0 at that point, so it will only work with the input that has the id inp0. You could fix this by using a selector that will work with all input[x] ids. And attribute selector that checks the beginning of the id would work. Like:
$(document).on('keydown','[id^=inp]'function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
It's because this code:
$(document).on('keydown','#inp'+String(count), function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
will only get executed once, and when it does, the value of count is 0. So you're only binding the event to the first element.
Instead, you should probably use a class to target those elements.

How to print table in HTML

Using below code i can able to print table, but i not able to print the value which i was entered. any one can help.....
Here is the code.....
<!doctype html>
<html>
<head>
<script>
function printDiv()
{
var divToPrint=document.getElementById('demo');
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
</script>
</head>
<body class="tundra">
<div>
<table id="demo" >
<tr>
<td><input type="text" ></td>
<td> cell 11 </td>
</tr>
<tr>
<td><input type="text" ></td>
<td> cell 12</td>
</tr>
</table>
</div>
<input type="button" value="Print" onclick="printDiv()" />
</body>
</html>
Demo Fiddle
You can replace all inputs with there value and then can print the table... Doing it completely using javascript is pretty difficult but not impossible.
jQuery
function printDiv() {
$('input[type=text]').each(function () {
var cell = $(this);
cell.replaceWith('<span>' + cell.val() + '</span>');
});
var divToPrint = document.getElementById('demo');
newWin = window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
divToPrint=document.getElementById('demo');
Will take the DOM input elements in the same way they where loaded at first time.
For example, if your input has
value="test"
in your html code, then it will be showed in the print.
The issue here is not the table but the input elements. When the user enters data, it is stored in the value properties of input element nodes in the Document Object Model. But when you write the enclosing div element in another document, only the elements and their HTML attributes are written—the values are discarded.
The solution is to make the data part of the markup, by setting the value attribute according to the value property. For this, you can first clone the div element using the cloneNode method and then the getElementsByTagName method to get all input elements inside it. This means that you would replace the first statement inside the printDiv function by the following:
var divToPrint=document.getElementById('demo').cloneNode(true);
var inputs = divToPrint.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++)
inputs[i].setAttribute('value', inputs[i].value);

document.createElement not working on IE 8 and below

I have this for that lets users upload pictures. I wanted to limit the number of pictures to 4. At first it shows only one input field, then if a user wants to add more they can click on Button-Add-icon.png and another input field appears. When they reach four inputs and they decide to remove one they click on Button-Delete-icon.png.
This whole thing works fine on Firefox, Chrome, Seamonkey and IE9. But it doesn't work on IE8, IE7 and before.
Could someone give a hint on how to get it fixed?
Thanks
<!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=iso-8859-1" />
<title>Document sans titre</title>
<script type="text/javascript">
var totalItems = 0;
function addItems()
{
if(totalItems < 3)
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
totalItems++;
} else {
//Display your message here..
}
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
{
table1.deleteRow(lastRow-1);
totalItems--;
}
}
</script>
</head>
<body>
<table align="center" border="0" id="tab1" >
<tr>
<td width="218" align="center"><input type="file" name="image[]" /></td>
<td width="54" align="center"><img src="images/Button-Add-icon.png"
style="cursor:pointer" onclick="addItems()" />
</td>
<td><img src="images/Button-Delete-icon.png" style="cursor:pointer"
onclick="remItems()" />
</td>
</tr>
</table>
<table align="center" border="0" id="tab2">
</table>
</body>
</html>
You are adding the row as a child to the wrong element.
An HTML table always has a tbody element as a child element, all tr elements go inside this. If you write a piece of HTML including a table with no tbody element it will be created automatically, but when altering the table later on you have to take the tbody element into account.
An easy fix is to write the tbody element explicitly, give it an id, and insert new rows in the tbody element instead of in the table element.
<table>
<tbody id="tb1">
<tr><td></td></tr>
</tbody>
</table>

delete a row in html table using a hidden type and javascript

I have a table with HTML constructed using my servlet class.
When trying to delete a row in this table using a javascript function I must first of all put different id to separate elements.and i resolove it with hidden type like that:
retour.append("<td>");
retour.append("<input type=\"hidden\" id=\"id_"+nomTab+"_"+compteur+"\" value=\""+object.getIdDailyTimeSheet()+"\"/>");
retour.append("<button id=\"del\" name=\"del\" type=\"button\" onClick=DeleteARow('+id_"+nomTab+"_"+compteur+"')>");
retour.append("<img src=icon_delete.gif />");
retour.append("</button>");
retour.append("</td>");
As you can see each element has a delete button. What i want to know how can i delete one row.
thinks.
function deleteRow(r)
{
var i = r.parentNode.parentNode.rowIndex;
document.getElementById('myTable').deleteRow(i);
}
You should check out this dom page:
http://www.w3schools.com/js/js_ex_dom.asp
hope this helps.
I don't understand why you're using the <input type="hidden" />. Instead you should use some DOM scripting. (or jQuery)
Here's an example using DOM scripting:
<!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" xml:lang="en" lang="en">
<head>
<title>Delete a Row Example</title>
<script type="text/javascript">
//<![CDATA[
window.onload = function() {
var table = document.getElementById("the-table");
var buttons = table.getElementsByTagName("input"); // all the <input /> elements which were in the table
for(var i=0; i<buttons.length; i++) { // loop all over the <input /> elements in the table
if(buttons[i].name=="delete-this-row") { // if they are marked as "delete this row" inputs...
buttons[i].onclick = function() { // give them onclick even handlers
var buttonCell = this.parentNode; // now buttonCell is the <td> which contains the <input />
var deleteThisRow = buttonCell.parentNode; // now deleteThisRow is the row we want to delete
deleteThisRow.parentNode.removeChild(deleteThisRow);
}
}
}
}
//]]>
</script>
</head>
<body>
<table id="the-table">
<tbody>
<tr>
<td>0,0</td>
<td>1,0</td>
<td>2,0</td>
<td><input type="button" name="delete-this-row" value="Delete This Row" /></td>
</tr>
<tr>
<td>0,1</td>
<td>1,1</td>
<td>2,1</td>
<td><input type="button" name="delete-this-row" value="Delete This Row" /></td>
</tr>
<tr>
<td>0,2</td>
<td>1,2</td>
<td>2,2</td>
<td><input type="button" name="delete-this-row" value="Delete This Row" /></td>
</tr>
</tbody>
</table>
</body>
</html>
The idea I'm using here is not to use an identifier on the row; instead use the position of the button to determine which row to delete. You delete the row its in.
Since I define the onclick event handler in my javascript (not in an onclick attribute) the function I used can access the clicked element, using the this keyword. From there, I can start climbing up this.parendNodes all the way to my <tr> element.
You should be able to do the same thing I've done with <input type="button" /> elements with a <button> element.
Alternately you could also use deleteRow(...).
The DeleteRow javascript method should have code to loop through the Table element, identify the row you want to delete and then invoke the delete method of the document object.
function DeleteARow(id) {
var row = document.getElementById(id);
if ( row ) {
row.parentNode.removeChild(row);
}
}

Categories