I have an HTML table with one column having checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
The top 100 rows are displayed on page load. I also have a search functionality where the user can search for specific rows. The user can maneuver throughout different searches and still keep all of the checkboxes checked with session storage. However, when a user hits "Checkout," the body of the email only displays the table rows that are checked and currently visible on the page.
So, if a user searches for a table row and checks it, but then navigates back to the original top 100 rows, that checked row would not display on the email because it is not displayed on the page at that current moment.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
I have been told that I am storing the checkboxes in a session but then going back to the UI to read the list of selected items. However, I am unsure how exactly to fix this and would really appreciate some help! Thanks!
JavaScript that includes code to keep all checkboxes checked throughout session:
$(function(){
$(':checkbox').each(function() {
// Iterate over the checkboxes and set their "check" values based on the session data
var $el = $(this);
//console.log('element id: ',$el.prop('id'),' sessionStorage[id]: ',sessionStorage[$el.prop('id')]);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
if ($el.prop('checked')) {
//show the quantity cell in the column under header with class num
$el.closest('tr').find('td.quantity_num').toggle(this.checked);
var quantity = sessionStorage['value_'+$el.prop('id')];
if (quantity) {
$el.closest("tr").find(".spinner" ).spinner( "value", quantity );
}
}
});
$('input:checkbox').on('change', function() {
// save the individual checkbox in the session inside the `change` event,
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
JavaScript that sends information to email body:
function sendMail() {
var dataItems = [
{ 'clss':'.loc', 'prop':'loc' },
{ 'clss':'.rp-code', 'prop':'rpCode' },
{ 'clss':'.sku', 'prop':'sku' },
{ 'clss':'.special-id', 'prop':'specialId' },
{ 'clss':'.description', 'prop':'description' },
{ 'clss':'.quantity', 'prop':'quantity' },
{ 'clss':'.unit', 'prop':'unit' }
];
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=";
link += $('#merchTable tr input[name="check"]:checked').closest('tr').get().map(function(tr) {
var str = dataItems.map(function(item) {
return encodeURIComponent($(tr).find(item.clss).data(item.prop)) + '\xa0\xa0';
}).join('');
str += encodeURIComponent($(tr).find('.spinner').spinner('value')) + '%0D%0A';
return str;
}).join('') + '%0D%0A';
console.log(link);
window.location.href = link;
}
HTML Table:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input disabled="true" type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>
EDIT:
Function that display the Quantity # column when a row is checked:
$(function () {
$(".check").change(function(){
$(this).closest('tr').find('td.quantity_num').toggle(this.checked);
setupSpinner(this);
console.log('input - checked: ',$('input.check').is(':checked'));
//var quantity = $(this).closest('tr').find('td.quantity').data('quantity');
if($('input.check').is(':checked'))
$(this).closest('table').find('th.num').toggle(true);
else
$(this).closest('table').find('th.num').toggle(false);
});
});
Function for the spinner:
function setupSpinner(checkbox) {
var quantity = $(checkbox).closest('tr').find('td.quantity').data('quantity');
console.log('quantity: ',quantity);
$(checkbox).closest("tr").find(".spinner" ).spinner({
spin: function( event, ui ) {
if ( ui.value > quantity ) {
$( this ).spinner( "value", quantity );
return false;
} else if ( ui.value <= 1 ) {
$( this ).spinner( "value", 1 );
return false;
}
//store value
var test = ui.value;
sessionStorage.setItem('value_'+$(checkbox).prop('id'), JSON.stringify(test));
var testtrue = sessionStorage.getItem('value_'+$(checkbox).prop('id'));
console.log('testtrue: ', JSON.parse(testtrue));
}
});
}
Function that gets values from each cell in checked table row:
$(function () {
$(document).on("click", "#merchTable .check", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function () {
return $(this).find('.check').length === 0;
});
var isValid = true;
var errors = '';
var elements = tds;
if (tds.find('td').length > 0) {
elements = tds.find('td');
}
var dict = {};
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'td') ? $(this).val() : $(this).text();
console.log(type);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "loc ui-widget-content":
dict["Loc"] = value;
break;
case "rp-code ui-widget-content":
dict["Rp-Code"] = value;
break;
case "sku ui-widget-content":
dict["SKU"] = value;
break;
case "special-id ui-widget-content":
dict["Special-ID"] = value;
break;
case "description ui-widget-content":
dict["Description"] = value;
break;
case "quantity ui-widget-content":
dict["Quantity"] = value;
break;
case "unit ui-widget-content":
dict["Unit"] = value;
break;
case "quantity_num ui-widget-content":
dict["spinner"] = value;
break;
}
})
if (isValid) {
console.log(dict);
} else {
alert(errors);
}
});
});
Based on this and earlier questions, I understand that you need something that :
stores the state of checked rows in window.sessionStorage.
restores the state of checked rows after pagination/search.
allows the composition of an email body, reflecting all checked rows whether they are currently displayed or not.
Without discipline the code could get really messy. I recommend a singleton object with a simple API, and ended up with the code below.
$(function($) {
// **************************************************************
// RowData acts as an interface beteween high level
// application code and sessionStorage.
// *************************
// RowData is phrased as a singleton object with private data,
// and a bunch of functions, some of which are exposed as methods.
// *************************
// Inner member `rowData` is a javascript representation of all
// checked rows in the session.
// A JSON-encoded version of `rowData` is stored in sessionStorage.
// **************************************************************
var RowData = (function(storage, storageKey) {
var rowData = readFromSession();
var dataItems = ['loc', 'rp-code', 'sku', 'special-id', 'description', 'quantity', 'unit'];
var emailDelimiters = {
'row': '%0D%0A',
'dataItem': '\xa0\xa0'
};
function readFromSession() {
return JSON.parse(storage.getItem(storageKey) || '{}');
}
function writeToSession() {
storage.setItem(storageKey, JSON.stringify(rowData));
}
function writeRow(tr) {
var $tr = $(tr),
id = $tr.prop('id');
if($tr.find('.check').is(':checked')) {
rowData[id] = {};
for(var i=0; i<dataItems.length; i++) {
rowData[id][dataItems[i]] = $tr.find('.' + dataItems[i]).text();
}
// rowData[id].quantity_num = $tr.find('.spinner').spinner('value'); // if using spinner widget
rowData[id].quantity_num = $tr.find('.spinner').val(); // if using HTML5 <input type="number">
} else {
delete rowData[id];
}
writeToSession();
}
function readRow(tr) {
// restore tr's checkbox and spinner value from stored data
var $tr = $(tr),
id = $tr.prop('id'),
row = rowData[id];
if(row) {
$tr.find('.check').prop('checked', true).end()
// .find('.spinner').spinner('value', row.quantity_num); // if using spinner widget
.find('.spinner').val(row.quantity_num); // if using HTML5 <input type="number">
}
}
function toEmailString() {
return $.map(rowData, function(row, id) {
return $.map(row, window.encodeURIComponent).join(emailDelimiters.dataItem);
}).join(emailDelimiters.row);
}
// selectively expose functions as methods of RowData
return {
'writeRow': writeRow,
'readRow': readRow,
'toEmailString': toEmailString
};
})(window.sessionStorage, 'checkedRowData');
// **********************************************************************************************
// With RowData in place to do the hard stuff, the high level application code is really simple
// **********************************************************************************************
$('#merchTable').on('change', '.check', function() { // on changing a table row ...
RowData.writeRow($(this).closest('tr').get(0)); // ... set the corresponding row object in RowData and sessionStorage
}).on('blur', '.spinner', function() { // on leaving a spinner widget
RowData.writeRow($(this).closest('tr').get(0));
});
$('#checkout').on('click', function() { // on clicking the [Checkout] button
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=" + RowData.toEmailString();
console.log(link);
window.location.href = link;
});
// Call this function on completion of every pagination/search
function restoreVisibleRows() {
$('#merchTable tbody tr').get().forEach(RowData.readRow);
}
// ...
// here, set up table pagination/search, and spinners.
// ...
restoreVisibleRows();
});
minimally tested
Note, everything above relies on table rows being served as follows :
<tr id="<?php echo intval ($row['ID'])?>">
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" /></td>
<td class="loc ui-widget-content"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" align="center"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" align="center" ><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" ><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input disabled="true" type="number" min="1" max="<?php echo $row['Quantity'];?>" step="1" style="width: 100px;" class="spinner" /></td>
</tr>
Here, I :
added id="<?php echo intval ($row['ID'])?>" to the <tr> tag - the RowData interface won't work without it.
removed data-*** and id attributes from the <td> tags - they appear not to be necessary but can be reintroduced if needed for other purposes.
Related
i have a little problem when try do this operation:
This its the crazy code to try do.
$table.="<script>
function sumacant".$idPedido.$idMedidas."(){
var CantidadS".$idPedido.$idMedidas." = $('input[data-inputtype=\"CantidadS".$idPedido.$idMedidas."\"]').val();
var prg = document.getElementById('muestrac').value;
var nu = CantidadS".$idPedido.$idMedidas." + prg;
$('.muestrac').html(nu);
}
sumacant".$idPedido.$idMedidas."();
"; $table.="</script>";
INPUT TO DO :
<input size="3" type="text" data-inputtype="CantidadS'.$idPedido.$idMedidas.'" value="'.$Cant.'"/>
DIV TO SHOW
$table.="<td><div name='muestrac' id='muestrac'>0</div></td>";
ALL CRAZY CODE
<?
$table="<div class='table-responsive' ><table align='center' class='table-responsive-xxl table-bordered border-primary'><thead><tr align='center'><th>Ref</th><th>Imagen</th><th>Peso</th><th>Cantidad</th><th>Total Cantidad</th><th>Precio : <input type='text' size='3' name='GPrecio' id='GPrecio'></th><th>Valor Total</th><th>Observaciones</th></tr></thead>";
$SQLtraedatos="SELECT Pedido.ProductoURL, Pedido.idProducto, Pedido.Peso, Pedido.Referencia,
Pedido.FechaRealiza, Pedido.idPedido
FROM Pedido WHERE EstadoPedido=1 and Clientes_idClientes=$id";
if ($result = mysqli_query($con, $SQLtraedatos)) {
while ($row = mysqli_fetch_row($result)){
$ProductoURL=$row[0];
$idProducto=$row[1];
$Peso=$row[2];
$Referencia=$row[3];
$FechaRealiza=$row[4];
$idPedido=$row[5];
$Categoria="Vacia";
$SQLGetMedidas="SELECT Categoria_idCategoria FROM Productos WHERE idProductos=".$idProducto;
if ($resultGM = mysqli_query($con, $SQLGetMedidas)) {
while ($rowGM = mysqli_fetch_row($resultGM)){
$Categoria=$rowGM[0];
}}
if ($Categoria=="Vacia"){
$products=json_decode(file_get_contents('https://decolombiajoyas.com/joyeriaoroplata/wp-json/wc/v2/products/'.$idProducto.'?consumer_key=xxx=xxxx&status=publish'));
//foreach($products as $product){
$category=$products->categories;
foreach($category as $categories){
$nombrecat=$categories->name;
//var_dump($category);
if ($nombrecat=='Anillos'){
$Categoria=1;
}
}
}
$word="decolombiajoyas.com";
if(strpos($ProductoURL, $word) !== false){
$table.="<tr align='center'><td>$Referencia</td><td><img src='$ProductoURL' style='width: 200px; height: 200px;'>";
}
else {
$table.="<tr align='center'><td>$Referencia</td><td><img src='https://pm.decolombiajoyas.com/PorMayor/files/".$ProductoURL."' style='width: 200px; height: 200px;'>";
}
$table.="</td><td><input type='hidden' name='Peso".$idPedido."' id='Peso' value='$Peso'>$Peso grs</td><td align='center'>";
$SQLtraemedidas="SELECT idMedidas, Nombre FROM Medidas WHERE Categoria=$Categoria ORDER BY Nombre ASC";
if ($resultM = mysqli_query($con, $SQLtraemedidas)) {
while ($rowM = mysqli_fetch_row($resultM)){
$NombreM=$rowM[1];
$idMedidas=$rowM[0];
$SQLInsertaM="INSERT INTO Medidas_has_Pedido(Medidas_idMedidas, Pedido_idPedido, Cantidad) values (".$idMedidas.",".$idPedido.", 0)";
mysqli_query($con, $SQLInsertaM);
$SQLTraeValorQ="SELECT Cantidad FROM Medidas_has_Pedido WHERE Medidas_idMedidas=".$idMedidas." and Pedido_idPedido=".$idPedido;
$SQLTraeValor = mysqli_query($con, $SQLTraeValorQ);
while($res=mysqli_fetch_row($SQLTraeValor)){
$Cant=$res[0];
}
$table.="<script>
function sumacant".$idPedido.$idMedidas."(){
var CantidadS".$idPedido.$idMedidas." = $('input[data-inputtype=\"CantidadS".$idPedido.$idMedidas."\"]').val();
var prg = document.getElementById('muestrac').value;
var nu = CantidadS".$idPedido.$idMedidas." + prg;
$('.muestrac').html(nu);
}
sumacant".$idPedido.$idMedidas."();
"; $table.="</script>";
$table.='<table><tr><td onchange="changeit('.$idPedido.', '.$idMedidas.', this); sumacant'.$idPedido.$idMedidas.'();">Talla : '.$NombreM.' <input size="3" type="text" data-inputtype="CantidadS'.$idPedido.$idMedidas.'" value="'.$Cant.'"/></td></tr></table>';
}}
if($Categoria!=1) {
$table.="<script>
function sumar".$idPedido."(){
var Peso = $('input[name=\"Peso".$idPedido."\"]').val();
var Cantidad = $('input[data-inputtype=\"Cantidad".$idPedido."\"]').val();
//var Cantidad = $('[data-inputtype=\"Cantidad".$idPedido."\"]').val($(this).val());
var Precio = $('input[id=\"Precio".$idPedido."\"]').val();
var total = Peso * Cantidad * Precio;
var n = total.toFixed(2);
$('.result".$idPedido."').html(n);}</script>
<br><input size='2' onchange='sumar".$idPedido."();' type='text' data-inputtype='Cantidad".$idPedido."' name='CantidadI[]' id='CantidadI[]' required> <br>";
}
$table.="<td><div name='muestrac' id='muestrac'>0</div></td>";
$table.="<td>";
$table.="<input type='text' size='3' name='Precio[]' id='Precio".$idPedido."' data-inputtype='Precio' onchange='sumar".$idPedido."()'></td>";
$table.="<td><div class='result".$idPedido."' id='result".$idPedido."'></div></td>";
$table.="</td><td><textarea id='Observaciones[]' name='Observaciones[]' cols='20' rows='5' required></textarea><input type='hidden' id='id' name='idpedido[]' value='".$idPedido."'></td>";
$table.="</tr>";
}}
$table.="</table></div>";
echo $table;
?>
Thanks for the time and help.
Work to separate PHP from the clientside code, you can initialize the values from PHP onto the DOM by setting the values of the inputs (you can also calculate the result of the initial values in PHP and place in your result column).
Then pass control over to js/jquery to do the rest like traversing the DOM by selecting the rows then running over the inputs to update the values on change.
Like the following, sorry not going to rewrite your code, its just too much of a mess.
$(function() {
// make a function
function sum_rows() {
// loop over each class which is .a-row (table rows)
$('.a-row').each(function() {
// init a result value
let result = 0
// within the row find all inputs which have class .input
// .. then loop over them
$(this).find('.inputs input').each(function() {
// get the value of the input
result += Number($(this).val())
})
// within the row find .result
// .. then set its value
$(this).find('td.result').text(result)
})
}
// run function on load
sum_rows()
// run function on input
$('.inputs input').on('input', sum_rows)
})
.inputs {
width: 60px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Inputs</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr class="a-row">
<td class="inputs">
<input value="1">
<input value="1">
<input value="1">
</td>
<td class="result"/>
</tr>
<tr class="a-row">
<td class="inputs">
<input value="1">
<input value="2">
<input value="3">
</td>
<td class="result"/>
</tr>
</tbody>
</table>
Script used :
$(function() {
// make a function
function sum_rows() {
// loop over each class which is .a-row (table rows)
$('.a-row').each(function() {
// init a result value
let result = 0
// within the row find all inputs which have class .input
// .. then loop over them
$(this).find('.inputs input').each(function() {
// get the value of the input
result += Number($(this).val())
})
// within the row find .result
// .. then set its value
$(this).find('td.result').text(result)
})
}
// run function on load
sum_rows()
// run function on input
$('.inputs input').on('input', sum_rows)
})
Table Code for rows
<table><tbody><tr class="a-row"><td class="inputs"><div onchange="changeit(128, 1, this);">Talla : 10 <input size="3" type="text" data-inputtype="CantidadS1281" value="88"></div><script>
function sumacant1281(){
var CantidadS1281 = parseInt($('input[data-inputtype="CantidadS1281"]').val());
//var prg = document.getElementById('muestrac');
var prg = parseInt($('#muestrac').html());
var nu = CantidadS1281 + prg;
$('.muestrac').html(nu);
}
sumacant1281();
</script>
<div onchange="changeit(128, 2, this);">Talla : 11 <input size="3" type="text" data-inputtype="CantidadS1282" value="55"></div><script>
function sumacant1282(){
var CantidadS1282 = parseInt($('input[data-inputtype="CantidadS1282"]').val());
//var prg = document.getElementById('muestrac');
var prg = parseInt($('#muestrac').html());
var nu = CantidadS1282 + prg;
$('.muestrac').html(nu);
}
sumacant1282();
</script>
<div onchange="changeit(128, 3, this);">Talla : 9 <input size="3" type="text" data-inputtype="CantidadS1283" value="333"></div><script>
function sumacant1283(){
var CantidadS1283 = parseInt($('input[data-inputtype="CantidadS1283"]').val());
//var prg = document.getElementById('muestrac');
var prg = parseInt($('#muestrac').html());
var nu = CantidadS1283 + prg;
$('.muestrac').html(nu);
}
sumacant1283();
</script>
<div onchange="changeit(128, 4, this);">Talla : 9.5 <input size="3" type="text" data-inputtype="CantidadS1284" value="888"></div><script>
function sumacant1284(){
var CantidadS1284 = parseInt($('input[data-inputtype="CantidadS1284"]').val());
//var prg = document.getElementById('muestrac');
var prg = parseInt($('#muestrac').html());
var nu = CantidadS1284 + prg;
$('.muestrac').html(nu);
}
sumacant1284();
</script>
</td></tr></tbody></table>
to show
<td class="result"></td>
Have any error ?
Not apper any errors in the console :S
Thank you for the time #Lawrence Cherone
In my code below, when i select a checkbox it displays the name of the item checked. But my problem now is, the table is paginated so when i move to the next page and return, the already checked item goes back unchecked.
The same applies when i check a box and filter using the ajax request, when i return the already checked box will have moved to unchecked state.
How do i hide the table page to resolve this issue?
HTML
<table class="table" id="table" style="background-color:white" >
<thead>
<tr>
<th></th>
<th colspan="5"></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td><input onclick="return results(this)" data-item="{{$item->toJson()}}" type="checkbox" id="{!! $item->id !!}" name="{!! $item->name !!}" value="{!! $item->price !!}" /> </td>
<td>{{$item->name }}</td>
</tr>
#endforeach
</tbody>
</table>
{{$items->links()}}
JS
function results(item){
var major = JSON.parse(item.dataset.item);
if(item.checked == true) {
$('.panel').append(
'<div class="container "> '+
'<table style="width:100%;" class="table" id="tables">'+
'<thead>'+'<thead>'+
'<tbody>'+
'<tr>'+ '<td class="name" >'+major.name+'</td>'+] '</tr>'+
'</tbody>'+'</table>'+'</div>')}
} else {
});
}
}
}
AJAX
success: function (data) {
console.log(data);
$("#table").slideDown('fast');
var table = $("#table tbody");
table.html("");
$.each(data, function(idx, elem){
table.append(
"<tr><td><input type='checkbox' onclick='return results(this)' data-item='"+JSON.stringify(elem)+"' id='"+elem.id+"' name='"+elem.name+"' value='"+elem.price+"' data-id="+elem.id+" /></td><td >"+elem.name+"</td><tr>"
);
});
}
Saving state is possible via "JavaScript - localStorage" functionality.
Today browsers have capability to save information that is more "cleaner" and informative then cookies.
On "checkbox" element I would add event listener that would start function called "saveState()". In this function I would save information about checkbox.
function saveState()
{
localStorage.setItem("checkBoxStatus", "Checked");
}
This information is saved into browser`s storage and won't be deleted until you delete it yourself.
To delete it you have two options:
`localStorage.removeItem("checkBoxStatus");`
`localStorage.clear();`
Then when you re-enter that page again, while you are "constructing" view you can add small function that will set state equal to the "saved" one.
function resumeState()
{
if(localStorage.getItem("checkBoxStatus") === "Checked)
//get check box and check or uncheck
}
HOW STORED DATA CAN BE USED
It's my point of view but I prefer building my HTML views via JavaScript, as I find it more cleaner way and easier also, because today you have frequent communication with "JavaScript/Ajax" functions and need more responsiveness.
so I would build my entire view with JavaScript Dom
**
function buildView()
{
var element = document.createElement("div");
var checkBox = document.createElement("input");
checkBox.settAttribute("type", "checkbox");
//here we will check
localStorage.getItem("checkBoxStatus") === "Checked" ? checkBox.setAttribute("checked", "true") : checkBox.setAttribute("checked", false);
element.appendChild(checkBox);
document.body.appendChild(element);
}
**
or use setTimeout function and stick to "HTML" views:
<body onload='setTimeout(buildView(), 2000);>'
this will wait until all the views are constructed and start after it.
You can set correct timing depending on how much data you are loading during "onload" event. If it's small data you can even wait for 1 second -> 1000
function buildView()
{
var checkBox = document.getElementById("checkBox");
//here we will check
if(localStorage.getItem("checkBoxStatus") === "Checked")
{
checkBox.setAttribute("checked", "true");
}
else
{
checkBox.setAttribute("checked", false);
}
}
Remember that main here is to use localStorage functionality to save data and after that how you will use that data, totally depends on developers imagination and creativity
I made a fiddle for you so that you can improve it in the way that you can use it for your purpose,here is the fiddle and the code:
HTML:
<div class="checkbox-set">
</div>
<div id = "result">
</div>
Js:
var id = "";
for(i=1 ; i<8 ;i++){
id="checkbox_"+i;
$('.checkbox-set').append('<input type="checkbox" id="'+ id +'" value="Click on me"/> <label for="'+id+'">Click on me</label> <br/> ');
}
var selected = [];
if(sessionStorage.selected) {
// selected = sessionStorage.selected;
var checkedIds= sessionStorage.selected.split(",");
$.each(checkedIds,function(i){
$("#" + checkedIds[i]).prop('checked', true);
selected.push(checkedIds[i]);
});
}
$('input[type="checkbox"]').change(function() {
if(this.checked) {
$(this).each(function(){
selected.push($(this).attr('id'));
//$("#result").html(selected);
});
}
if(!this.checked) {
const index = selected.indexOf($(this).attr('id'));
var tt= selected.splice(index, 1);
//$("#result").html(selected);
}
sessionStorage.selected = selected;
$("#result").html(sessionStorage.selected);
})
please confirm if it is helpful
So I have a table where you can check a table row and it will get the values of each cell in that row and also display another column named Quantity #. The Quantity # column contains a type="number" input. After entering a number, a user will be able to refresh the page and the Quantity # column and the value entered into the input will both remain visible. A user can also hit a "Checkout" button and it will post that data to an email body.
That all works great in Safari and Google Chrome. However, in Firefox, if you enter a value into the input and then refresh for example, the value will no longer be in the input. Also, if you hit the Checkout button and it pastes the data to the email, it will not paste the input value either like it does in Safari/Chrome.
Why is this and what can I do to fix this problem in Firefox?
JavaScript:
$(function($) {
var RowData = (function(storage, storageKey) {
var rowData = readFromSession();
var dataItems = ['loc', 'rp-code', 'sku', 'special-id', 'description', 'quantity', 'unit'];
var emailDelimiters = {
'row': '%0D%0A',
'dataItem': '\xa0\xa0'
};
function readFromSession() {
return JSON.parse(storage.getItem(storageKey) || '{}');
}
function writeToSession() {
storage.setItem(storageKey, JSON.stringify(rowData));
}
function writeRow(tr) {
var $tr = $(tr),
id = $tr.prop('id');
if($tr.find('.check').is(':checked')) {
rowData[id] = {};
for(var i=0; i<dataItems.length; i++) {
rowData[id][dataItems[i]] = $tr.find('.' + dataItems[i]).text();
}
rowData[id].quantity_num = $tr.find('.spinner').val();
} else {
delete rowData[id];
}
writeToSession();
}
function readRow(tr) {
// restore tr's checkbox and spinner value from stored data
var $tr = $(tr),
id = $tr.prop('id'),
row = rowData[id];
if(row) {
$tr.find('.check').prop('checked', true).end()
// .find('.spinner').spinner('value', row.quantity_num); // if using spinner widget
.find('.spinner').val(row.quantity_num); // if using HTML5 <input type="number">
}
}
function toEmailString() {
return $.map(rowData, function(row, id) {
return $.map(row, window.encodeURIComponent).join(emailDelimiters.dataItem);
}).join(emailDelimiters.row);
}
// selectively expose functions as methods of RowData
return {
'writeRow': writeRow,
'readRow': readRow,
'toEmailString': toEmailString
};
})(window.sessionStorage, 'checkedRowData');
$('#merchTable').on('change', '.check', function() { // on changing a table row ...
RowData.writeRow($(this).closest('tr').get(0)); // ... set the corresponding row object in RowData and sessionStorage
}).on('blur', '.spinner', function() { // on leaving a spinner widget
RowData.writeRow($(this).closest('tr').get(0));
});
$('#checkout').on('click', function() { // on clicking the [Checkout] button
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=" + RowData.toEmailString();
console.log(link);
window.location.href = link;
});
// Call this function on completion of every pagination/search
function restoreVisibleRows() {
$('#merchTable tbody tr').get().forEach(RowData.readRow);
}
restoreVisibleRows();
});
JavaScript that keeps input value and quantity # column displayed on refresh:
$(function(){
var showQuantityHeader = false;
$(':checkbox').each(function() {
// Iterate over the checkboxes and set their "check" values based on the session data
var $el = $(this);
//console.log('element id: ',$el.prop('id'),' sessionStorage[id]: ',sessionStorage[$el.prop('id')]);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
if ($el.prop('checked')) {
//show the quantity cell in the column under header with class num
$el.closest('tr').find('td.quantity_num').toggle(this.checked);
showQuantityHeader = true;
//setupSpinner(this);
var quantity = sessionStorage['value_'+$el.prop('id')];
}
});
if (showQuantityHeader) {
$('#merchTable').find('th.num').show();
//console.log('header with class num: ',$('#merchTable').find('th.num'));
}
$('input:checkbox').on('change', function() {
// save the individual checkbox in the session inside the `change` event,
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
console.log($el);
});
});
HTML:
<section id="checkout-btn">
<button id="checkout" name="order">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr id="<?php echo intval ($row['ID'])?>">
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input type="number" min="1" max="<?php echo $row['Quantity'];?>" step="1" style="width: 100px;" class="spinner" /></td>
</tr>
<?php } ?>
</tbody>
</table>
EDIT:
#Rataiczak24, it would appear that FF doesn't fire its blur event in exactly the same way as the other browsers.
Storing a row's state is currently done in response quantity_num inputs' blur events. For performance reasons, I was hoping you wouldn't need to do this, but you need to respond to the 'change' event instead of the 'blur' event. Responsiveness of the quantity_num input may suffer.
That should solve both reported problems.
There's some other stuff too :
With my RowData object in place, you shouldn't be interacting with sessionStorage directly (unless of course you use it for other purposes). All interactions should be via the RowData API, and all code outside of RowData() should neither read from nor write to sessionStorage.
If at any point you need confidence that a table row might need to be restored to the state stored in sessionStorage, then call RowData.readRow(tr), or call restoreVisibleRows() to restore all visible rows.
If you follow my instruction "Call this function on completion of every pagination/search", and call restoreVisibleRows(); on page load, then row restoration should not need to be addressed elsewhere.
Almost all of what's in your $(function() { var showQuantityHeader = false; ...; ...; ...; }); above is unnecessary. The only part that's not catered for in RowData is $('#merchTable').find('th.num').show();. For that, you just need to add add a few lines to restoreVisibleRows(), and similarly in response to checkboxes being checked/unchecked.
So, all-in-all, the bottom part of my code suggestion should look like this :
$('#merchTable').on('change', '.check', function() { // on cliking a checkbox
var $this = $(this),
$tr = $this.closest('tr');
$tr.find('td.quantity_num').toggle(this.checked);
$this.closest('table').find('th.num').toggle($('input:checkbox:checked', '#merchTable tbody').length > 0);
RowData.writeRow($tr.get(0)); // store row state
}).on('change', '.spinner', function() { // on changing the value of a "spinner" widget
RowData.writeRow($this.closest('tr').get(0)); // store row state
});
$('#checkout').on('click', function() { // on clicking the [Checkout] button
setTimeout(function() {
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=" + RowData.toEmailString();
console.log(link);
window.location.href = link;
}, 0);
});
function restoreVisibleRows() {
$('#merchTable tbody tr').get().forEach(RowData.readRow);
if($('input:checkbox:checked', '#merchTable tbody').length > 0) {
$('#merchTable').find('th.num').show();
} else {
$('#merchTable').find('th.num').hide();
}
}
Your own $(".check").change(function(){...}) (if it still exists) can be removed.
I need help!
I have a php page that generates a html table from an array(). This array contains all the lines of a csv (no problem with this):
load_csv.php
<?php
function print_array_of_arrays_to_html_table(&$array_by_reference)
{
echo "<br><table border=1 align=center id=tableID>";
for ($i = 0; $i < count($array_by_reference); $i++)
{
echo "<tr>";
for ($j = 0; $j < count($array_by_reference[$i]); $j++)
{
echo "<td align=right title='f:".$i."\nc:".$j."\nv:".($array_by_reference[$i][$j])."'>".($array_by_reference[$i][$j])."</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
My intention is to indicate a column number in a text field, change all values of all cells in that column. The value would be the same for all cells in that column. For example, change all to '0' o whatever.
For now, with 'jquery' I can individually change any cell:
same load_csv.php:
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script language="javascript" type="text/javascript">
$('#tableID').click(function(event){
var original = $(event.target).text().toString();
var original_copy = original;
var retValue = prompt("\nChange value? ", original);
//if not empty and OK is pressed
if (retValue !== '' && retValue !== null)
{
//if not the same that 'original'
if (retValue !== original)
{
$(event.target).text(retValue);
}
else
{
alert("has not been modified" + original);
}
}
else
{
//if click Cancel
alert("has not been modified: " + original_copy);
}
})
</script>
But also want to change a whole column at a time. For example, calling the function onclick() of a button:
same load_csv.php:
<form>
<input type='button' value="Go back" onClick="history.go(-1);return true;"/>
<!-- if onclick button all values of all cells in the column are changed -->
<br>Column:
<input type='text'/>
<input type='button' value="Change all column?" onClick="myfunction()"/>
</form>
output example:
enter link description here
Any tips (yes, all code in same php.page. Sorry for my bad english)?
Thanks in advance.
EDIT: Solution:
I created two selectbox, one showing only the columns I intend to change, and one that allows me to choose to add two values (0 or 1). Then with the button I call the function. This includes the selectbox selected values. Next I check single cells (td) having 0 or 1 and "Pum"! success.
<select name="cols_bool" id="cols_bool">
<option value="not_selected" selected="selected">Choose...</option>
<?php
if (count($col_with_bools) > 0)
{
for ($i = 0; $i < count($col_with_bools); $i++)
{
echo "<option value=".$i.">".$col_with_bools[$i]."</option>";
}
}
?>
</select>
<br>New bool values to insert:
<select name="value_to_replace" id="value_to_replace">
<option value="1" selected="selected">1 (TRUE)</option>
<option value="2">0 (FALSE)</option>
</select>
<input type='button' class="change" value="Change all cells?" onClick="replace()"/>
<script language="javascript" type="text/javascript">
function replace()
{
var column_select = $('#cols_bool option:selected').text();
var value_to_insert = $('#value_to_replace option:selected').text();
$("#tableID").find('tr').each(function(){
var $td = $(this).find('td');
var $td_text = $td.eq(column_select).text();
if ($td_text == '1' || $td_text == '0')
{
$td.eq(column_select).text(value_to_insert.substring(0,1));
}
});
}
</script>
you can simply do like this
function replace(value_to_replace)
{
$("#tableID").find('tr').each(function () {
var $td = $(this).find('td');
$td.eq(3).text(value_to_replace);
});
}
I want it to happen when after user select the userID then the userID show up on first readonly textbox then the onChange event should fire when it show on first readonly textbox so it can copy this userID to second textbox. However it doesn't work, it only worked is the userID show up on first textbox but the onChange doesn't trigger for second texbox.
Here half working codes:
<tr>
<td align="right">
Secondary Owner
</td>
<td>
<input id="Hidden1" type="hidden" />
<asp:TextBox ID="tbAdd_Sowner" runat="server" Enabled="false"></asp:TextBox>
<input id="Hidden2" type="hidden" />
<input id="Hidden3" type="hidden" />
<a href="javascript:void(0)" onclick="GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2,Hidden3)">
Get User ID</a>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sowner"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender8" runat="server" TargetControlID="RequiredFieldValidator7">
</asp:ValidatorCalloutExtender>
</td>
</tr>
<tr>
<td align="right">Secondary Owners</td>
<td>
<asp:TextBox ID="tbAdd_Sphone" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator13" ValidationGroup="g1" runat="server" ErrorMessage="* Required" ControlToValidate="tbAdd_Sphone"> <b style="color:Red;"> * </b></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender9" runat="server" TargetControlID="RequiredFieldValidator13">
</asp:ValidatorCalloutExtender>
</td>
</tr>
Then a javascript codes in <head> to copy first textbox value and put to second textbox:
<script>
function getUserID() {
document.getElementById('tbAdd_Sphone').value = document.getElementById('tbAdd_Sowner').value;
}
document.getElementById('tbAdd_Sowner').onchange = getUserID();
</script>
Edited: I add a GALModalDialog.js codes here because some of you want to see what it like. I also have GALToCCDialong.asp that listed userid to choose and XMLGALListbox.asp that get the userid from ADs.
function PopulateListboxFromString(oListbox,vNames,vUserIDs){
var oArrayUserNames = vNames.value.split(';');
var oArrayUserIDs = vUserIDs.value.split(';');
for (var index=0;index < oArrayUserIDs.length;index++) {
if (oArrayUserNames[index] != ''){
var oOption = document.createElement("OPTION");
oListbox.options.add(oOption);
oOption.innerText = oArrayUserNames[index];
oOption.value = oArrayUserIDs[index];
}
}
};
function GalModalTOCCDialog(oTONames, oTOUserIDs,oCCNames, oCCUserIDs ) {
if (oCCNames != null){
var oInputArray = new Array(oTONames.value,oTOUserIDs.value,oCCNames.value,oCCUserIDs.value);
} else {
var oInputArray = new Array(oTONames.value,oTOUserIDs.value,'','');
}
var oOutputArray = window.showModalDialog('GalAccess/GALToCCDialog.asp', oInputArray, 'dialogWidth:510px;dialogHeight:400px;status:no;help:no;');
// Check if we get something back;
// User might have closed the window without using the buttons
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
if (oCCNames != null){
oTONames.value = oOutputArray[1];
oTOUserIDs.value = oOutputArray[2];
oCCNames.value = oOutputArray[3];
oCCUserIDs.value = oOutputArray[4];
} else {
oTONames.value = oOutputArray[1];
oTOUserIDs.value = oOutputArray[2];
}
}
}
return false;
}
function GalModalDialog(oSelectObject, oUserID) {
if (oUserID == null){
// there is a select object to fill data from
// fill the input array
var oInputArray = new Array(new Array(oSelectObject.options.length),new Array(oSelectObject.options.length));
for (var index=0;index < oInputArray[0].length;index++) {
oInputArray[0][index] = oSelectObject.options[index].innerText;
oInputArray[1][index] = oSelectObject.options[index].value;
};
var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');
// Check if we get something back;
// User might have closed the window without using the buttons
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
//remove existing from end to beginning otherwise not all options are removed.
var length=oSelectObject.options.length;
for (var index=length-1;index >= 0;index--) {
oSelectObject.options[index] = null;
};
// copy the array
for (var index=0;index < oOutputArray[1].length;index++) {
var oOption = document.createElement("OPTION");
oSelectObject.options.add(oOption);
oOption.innerText = oOutputArray[1][index];
oOption.value = oOutputArray[2][index];
};
}
}
} else
{
// there are 2 text objects to fill data from; the first contains the name, the secound the userid.
//if (oSelectObject.value != '' ) {
// var oInputArray = new Array(new Array(1),new Array(1));
//
// oInputArray[0][0] = oSelectObject.value;
// oInputArray[1][0] = oUserID.value;
//} else {
var oInputArray = new Array(new Array(0),new Array(0));
//}
var oOutputArray = window.showModalDialog('../GALDialog/GALModalDialog.asp', oInputArray, 'dialogWidth:500px;dialogHeight:320px;status:no;help:no;');
if (oOutputArray != null){
//first element is true if user clicked OK
if (oOutputArray[0]) {
// copy the data
oSelectObject.value = oOutputArray[1][0];
oUserID.value = oOutputArray[2][0];
}
}
}
return false;
}
Edited: Here is codes of GALToCCDialog.asp. In SubmitOnclick function and else if(vAction == 'OK') is where I click OK button from selected userid to submit to textbox.
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
<!--
function List_onkeydown(oList) {
if( event.keyCode == 46 ){
if ((oList.selectedIndex != -1)&&(oList.options[oList.selectedIndex].value != '')){
oList.options[oList.selectedIndex] = null;
}
}
}
//-->
</SCRIPT>
<script language="jscript">
function InitializeListbox(idXML, idSpan){
// get to the XML specifying the names
var oSelects;
var strXML;
oSelects = idXML.XMLDocument.documentElement.childNodes;
strXML = '';
// Get all the options in 1 string
for (var index=0;index< oSelects.length;index++){
strXML = strXML + oSelects[index].xml;
}
// the error handlingis there if idSpan refers to multiple objects
// Insert the options in the html before the end of the SELECT
// window.alert(strXML);
//idSpan.innerHTML = replace(idSpan.innerHTML,"</SELECT>",strXML & "</SELECT>");
idSpan.innerHTML = '<SELECT id=idUserSelect size=12 style="width:190px">' + strXML + '</SELECT>';
}
function SubmitOnclick(vAction, oObject){
//DistList.action = "DistList.asp?Action=" & vAction ;
if (vAction == 'Add'){
if ((idUserSelect.value!='')&&(idUserSelect.value!='Unknown')){
var oOption = document.createElement("OPTION");
oObject.options.add(oOption);
oOption.innerText = idUserSelect.options[idUserSelect.selectedIndex].text;
oOption.value = idUserSelect.options[idUserSelect.selectedIndex].value;
}
} else if(vAction == 'Find') {
idXMLUsers.src ='XMLGALListbox.asp?Searchstring=' + SearchString.value;
} else if(vAction == 'Remove'){
if ((idMyList.selectedIndex != -1)&&(idMyList.options[idMyList.selectedIndex].value != '')){
idMyList.options[idMyList.selectedIndex] = null;
}
} else if(vAction == 'OK'){
//window.returnValue = cal.day + ' ' + MonthNames[cal.month-1] + ' ' + cal.year ;
// create an array
var TONames = ''
var TOUserIDs = ''
var CCNames = ''
var CCUserIDs = ''
for (var index = 0; index < 1; index++) {
TONames = TONames + idTOList.options[index].innerText;
TOUserIDs = TOUserIDs + idTOList.options[index].value;
};
//Commented out by Nick, use if you want multiple userIDs etc...
//for (var index=0;index < idTOList.options.length;index++) {
// TONames = TONames + idTOList.options[index].innerText ;
// TOUserIDs = TOUserIDs + idTOList.options[index].value ;
//};
//for (var index=0;index < idCCList.options.length;index++) {
//CCNames = CCNames + idCCList.options[index].innerText ;
//CCUserIDs = CCUserIDs + idCCList.options[index].value ;
//};
var oArray = new Array(true,TONames,TOUserIDs,CCNames,CCUserIDs);
window.returnValue = oArray;
//window.alert(TONames);
//window.alert(TOUserIDs);
//window.alert(CCNames);
//window.alert(CCUserIDs);
window.close();
} else if(vAction == 'Cancel'){
var oArray = new Array(false);
window.returnValue = oArray;
window.close();
}
}
function OnBodyLoad() {
//window.alert('test');
//clear all list data
try{
var oArray = window.dialogArguments;
//PopulateListboxFromString(idTOList,oArray[0],oArray[1])
//PopulateListboxFromString(idCCList,oArray[2],oArray[3])
} catch(e)
{
}
};
function PopulateListboxFromString(oListbox,vNames,vUserIDs){
var oArrayUserNames = vNames.split(';');
var oArrayUserIDs = vUserIDs.split(';');
for (var index=0;index < oArrayUserIDs.length;index++) {
if (oArrayUserNames[index] != ''){
var oOption = document.createElement("OPTION");
oListbox.options.add(oOption);
oOption.innerText = oArrayUserNames[index];
oOption.value = oArrayUserIDs[index];
}
}
};
function OnBodyLoad__() {
//window.alert('test');
try{
var oArray = window.dialogArguments;
for (var index=0;index < oArray[0].length;index++) {
var oOption = document.createElement("OPTION");
idMyList.options.add(oOption);
oOption.innerText = oArray[0][index];
oOption.value = oArray[1][index];
};
} catch(e)
{
};
};
</script>
<body class="cellcolorlightest content" onload="OnBodyLoad();">
<xml id="idXMLUsers" src="XMLGALListbox.asp?Searchstring=" ondatasetcomplete="InitializeListbox(idXMLUsers, idUsers);"></xml>
<table class="TableBorderNormal" width="100%" border=0 cellspacing="1" cellpadding="1">
<colgroup>
<col width="50%"></col><col></col><col width="50%"></col>
<thead>
<tr>
<td colspan="3" class="TDvwvInfo" align="left"><STRONG>Find Name</STRONG><br><FONT size=2>Type name and hit "Search"</FONT></td>
</tr>
<tr>
<td class="TDvwvInfo" align="left"><input name="SearchString" style="WIDTH: 190px" size="20"> </td>
<td class="TDvwvInfo" align="middle" valign=top><input type="button" value="Search" name="Find" onclick="SubmitOnclick('Find')"></td>
<td class="TDvwvInfo" align="left"></td>
</tr>
<tr>
<td class="TDvwvInfo" align="left" nowrap><STRONG>Users found</STRONG><br><FONT size=2>Select from list and hit "Select" to add</FONT></td>
<td class="TDvwvInfo" align="middle"></td>
<td class="TDvwvInfo" align="left" valign=top><STRONG>Get User ID</STRONG><br></td>
</tr>
</thead>
<tr>
<td class="TDvwv" align="left" width="33%" rowspan=2 valign=top><span id="idUsers"> </span> </td>
<td class="TDvwvInfo" align="middle" valign=top width="33%">
<input type="button" value="Select >" name="Add" onclick="SubmitOnclick('Add', idTOList);"><br><br>
</td>
<td class="TDvwv" align="left" width="33%" valign=top>
<select id="idTOList" size="5" style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)"> </select><br>
<br />
<b style="color:red">* Only add one user, if you added the wrong user click cancel and try again.</b>
</td>
</tr>
<tr>
<td align=middle valign=top>
<!-- <input type="hidden" value="CC >" name="CC" onclick="SubmitOnclick('Add', idCCList);" disabled="disabled"><br><br> --> <!--INPUT name=Remove onclick="SubmitOnclick('Remove');" type=button value=" < Remove"--></td>
<td align=left valign=top>
<!--<select id=idCCList size=5 style="WIDTH: 190px" LANGUAGE=javascript onkeydown="return List_onkeydown(this)" disabled="disabled" visible="false"></select></td>-->
</tr>
<tr>
<td align="middle" ></td>
<td align=middle></td>
<td align=left>
<input type="button" value="OK" name="OK" onclick="SubmitOnclick('OK',null);">
<input type="button" value="Cancel" name="Cancel" onclick="SubmitOnclick('Cancel',null);"></td>
</tr>
</table>
</body>
</html>
Use
document.getElementById('<%= tbAdd_Sphone.ClientID %>')
instead of
document.getElementById('tbAdd_Sphone')
MSDN Control.ClientID Property
Changing the value of tbAdd_Sowner through JavaScript (I assume through your GalModalTOCCDialog function) isn't going to fire the onchange event.
You can fire that event manually, after you set the value:
document.getElementById('tbAdd_Sowner').onchange();
Though I'm surprised you aren't have problems with getElementById like #IrfanTahirKheli showed, which should've worked fine for you... so there are likely missing pieces of your markup that we need to help you correctly.
Other things you need to strongly consider is to not use inline styling and not use tables for formatting.
Since you seem to have problems with what I added, here is another way. Remove the onChange from your asp:TextBox and just do it all from javascript:
document.getElementById('tbAdd_Sowner').value = 'somevalue';
document.getElementById('tbAdd_Sowner').onchange = getUserID();
You cannot make change event just by setting value from javascript. Here is a sample by using trigger.
<script>
$(document).ready(function () {
$(".tbAdd_Sowner").on('change', function () {
var owner = $('.tbAdd_Sowner').val();
$('.tbAdd_Sphone').val(owner);
});
$(".aGetID").on('click', function () {
var tbOwner = $('.tbAdd_Sowner');
var hidden1 = $('.Hidden1');
var hidden2 = $('.Hidden2');
var hidden3 = $('.Hidden3');
GalModalTOCCDialog(hidden1, tbOwner, hidden2, hidden3);
});
function GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2, Hidden3) {
$(tbAdd_Sowner).val(' ').trigger('change');
}
$('.tbAdd_Sowner').change(function () {
$(this).removeAttr('disabled');
});
});
</script>
Here is your code, removing those validators
<table>
<tr>
<td align="right">Secondary Owner
</td>
<td>
<input id="Hidden1" type="hidden" value="1" class="Hidden1" />
<asp:TextBox ID="tbAdd_Sowner" OnTextChanged="tbAdd_Sowner_TextChanged" CssClass="tbAdd_Sowner" AutoPostBack="true" runat="server" Enabled="false" ></asp:TextBox>
<input id="Hidden2" type="hidden" class="Hidden2" />
<input id="Hidden3" type="hidden" class="Hidden3" />
<a href="javascript:void(0)" id="aGetID" class="aGetID" >Get User ID</a>
</td>
</tr>
<tr>
<td align="right">Secondary Owners</td>
<td>
<asp:TextBox ID="tbAdd_Sphone" runat="server" CssClass="tbAdd_Sphone" ></asp:TextBox>
</td>
</tr>
</table>
Server side.
protected void tbAdd_Sowner_TextChanged(object sender, EventArgs e)
{
tbAdd_Sowner.Text = "123";
}
use this <asp:TextBox ID="TextBox1" runat="server"
onkeypress="document.getElementById('id').Value=this.value;" />
Like others have mentioned in their answers,
<asp:TextBox id="tbAdd_Sphone" runat="server" />
will have a server-side dynamic client-ID prefixed to the generated HTML. If you see the source code of the page (or use the developer tools) in a browser of choice, you will notice you the ID is different than what you are passing in to your method call i.e something like this:
<textarea id="ctl00_OuterASPControlID_tbADD_Sphone"></textarea>
You can keep the className static by using class="tbAdd_Sphone" if the class is dynamically prefixed too. Or, try to get element by ID on
<%=tbAdd_Sphone.ClientID %>
You can either set the ClientID mode to static, or you can try using UniqueID.
Another thing to note, javascript has a special behavior. If you call of a method with a set number of variables passed in correctly in the call, it will only use those values in the functionality. If there is null/undefined data passed into the call, the rest of the parameters are just ignored.
functionName:function(parameter1, parameter2) {
//Default behavior can be overridden if parameter2 is not passed in as expected.
if(parameter2 ==null || parameter2=='undefined') {
parameter2 = "Some value";
}
}
functionName("testPar1"); //Works but parameter2 is not passed in as expected
functionName("testPar1", "testPar2"); //Works
functionName("testPar1", undefined); //Works, but parameter2 is not passed in as expected
If you need to use the id for phone, either do a substring search for getting the element by the actual ID, or use a getElementsByTag in your javascript to search for textboxes, and you can use any other property, say in plain Javascript:
var x = document.getElementsByTag("textbox");
if(x!=null && x.attribute('class') == 'tbAdd_Sphone' ) {
var valueX = x.attribute('value');
}