How to restore Textbox Data - javascript

I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.

Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});

When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.

I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().

Related

Check whether the selected row has a checked check box

How can I check if the selected row has a column check box checked?
I can get the column innerHTML which says <input type="checkbox"> but how to check if its checked or not.
I want to see if the CB is checked?
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
}
If you can get the checkbox and create a jQuery object out of it, you can use the prop method to find the value of its 'checked' property.
$yourCheckboxElement.prop('checked') will return a boolean, true if it is checked and false if it is not.
You can count checked check boxes with below codes.
var c = $(l_oSelectedRow.cells[l_iCB]).find("input[type='checkbox']:checked").length;
and detect rows had checked check box.
if (c > 0) {
// checked check box is existed.
} else {
// checked check box is now existed.
}
FIDDLE
$('.btn').click(function () {
$('#table').find("input:checkbox:checked").each(function () {
var check = $(this).closest('tr').index();
alert(check);
});
});
Iterate through all the checked checkbox and get the index of the closest tr
FIDDLE
$('.btn').click(function () {
var index =$('.input').val();
var row = $('#table').find('tr:nth-child('+index+')').find('input:checkbox')
if(row.is(':checked')){
alert(index);
}else{
alert('no check box check');
}
});
IF you want to check the row if there is a checked check get the row number use it as selector then check that row if there is a checked checkbox
A better (and easier) way to do this is like this
$("#imageResultsList tr").each(function(){
var cb = $(this).find('input [type="checkbox"]');
if(cb.prop('checked')){
alert('Checked');
} else {
alert('Not Checked');
}
});
Use jQuerys .prop function
See documentation: http://api.jquery.com/prop/
<label for="checkbox">Checkbox</label>
<input id="checkbox" type="checkbox" />
$('input[type="checkbox"]').on('click', function() {
alert($(this).prop('checked'));
});
Example:
https://jsfiddle.net/a26sw7ba/2/
In your case you could do the following with jQuery:
var l_iNoOfRows=$("#imageResultsList tr").length;
for(var i=1;i<=l_iNoOfRows;i++){
var l_oSelectedRow =$("#imageResultsList tr")[i]
var l_sCbColumn =l_oSelectedRow.cells[l_iCB].innerHTML;
alert($(l_sCbColum).prop('checked'));
}
Obviously replacing the alert with what ever statement needed to accomplish your goals.

Unable to attach event listeners to dynamically created elements in IE8

OVERVIEW:
When I click a button i want to
insert a new row at the end of a table
copy the cells and contents from the first row of the table
give unique ids to the elements within the cells
assign a focus event listener to all inputs in the page.
PROBLEM:
The event handlers are not firing on the correct elements in IE8. For example if I focus on the last input in the table, the first input gets highlighted.
CLARIFICATION:
This works in IE10, Chrome.
Does not work in IE8 which is my target browser.
I know of ways
to get around this.My aim is NOT to find a workaround but to
understand what my mistake is, in the given code.
The example code is just a quick simplified version of the problem. I am not asking for code optimization thats not relevant to the question.
Change event does not work too.
CODE:
HTML:
<table width="200" border="1" id="myTable">
<tr>
<td>
<input type='text' id='row0col0' name='row0col0'>
</td>
</tr>
</table>
<button id="addRow">Add Row</button>
JS:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
function addRowWithIncrementedIDs() {
var table = document.getElementById("myTable");
var newRow = table.insertRow(-1);
var row = table.rows[0];
var rowNum = newRow.rowIndex;
for (var d = 0; d < row.cells.length; d++) {
var oldCell = row.cells[d];
newCell = oldCell.cloneNode(true);
newRow.appendChild(newCell);
for (var c = 0; c < newCell.childNodes.length; c++) {
var currElement = newCell.childNodes[c];
var id = "row" + rowNum + "col" + d;
$(currElement).attr('name', id);
$(currElement).attr('id', id);
}
}
}
$(document).ready(function () {
$("#addRow").click(function () {
addRowWithIncrementedIDs();
addFocusListener();
});
});
OTHER APPROACHES THAT WORK:
changing from jQuery binding to regular JS binding. I.e from
$this.focus(function () {....});
to
this.onfocus =function () {....};
Attaching the event handler as they are rendered.
FIDDLE:
http://jsfiddle.net/sajjansarkar/GJvvu/
RELATED LINKS IN SO:
jQuery event listener doesn't work in IE 7/8
EDIT
Sorry, I just noticed your comment that you want to understand the error in your code.
I can quickly tell you one error, and that is mixing jQuery and native DOM methods. If you have dedicated yourself to using a very powerful library, then use all of it's features, not just the ones you understand.
The below code uses event delegation (to fix your focusing problem) and jQuery methods to more simply add a row to the table than with native methods.
If you're going to use jQuery, then you might as well use it all the way:
var t = $('#myTable');
$(document)
.on('focus','#myTable input',function() {
$(this).css('background','red')
})
.on('click','#addRow',function() {
//create a new row
var
newIndex,
r = t.find('tr').eq(0).clone();
//append it to the table
r.appendTo(t);
//update newIndex - use it for later
newIndex = r.index();
//update the name/id of each of the inputs in the new row
r.find('input').each(function() {
var
el = $(this),
id = 'row'+newIndex+'col'+el.closest('td').index();
el.attr('id',id).attr('name',name);
});
});
http://jsfiddle.net/GJvvu/1/
You don't need to loop through your inputs and bind a focus handler to each of them, jQuery automatically collects all DOM elements that match the selector and performs it's focus API function on each of them:
Change this:
function addFocusListener() {
$("input").unbind();
$("input").each(function () {
var $this = $(this);
$this.focus(function () {
var newThis = $(this);
newThis.css('background-color', 'red');
});
});
}
To this
function addFocusListener() {
$('input')
.unbind()
.focus(function(){
$(this).css('background-color','red');
});
}
$("#addRow").live("click", function(){
addRowWithIncrementedIDs();
addFocusListener();
});
Try out above code... this should work..

Multieple CheckBoxes dynamically check uncheck based on selected checkbox + MVC3 + jQuery/Javascript

I have a HTML form with checkboxes as below,
when I select ALL, other check boxes {HR, FINANCE, IT, SALES} should get checked
When I un select ALL, other checkboxes {HR, FINANCE, IT, SALES} should get unchecked
When everything is checked and of one the checkboxes {HR, FINANCE, IT, SALES} is unchecked, ALL should be unchecked
Below is the markup of my HTML.... how can I so it using jQuery/javascript ????
<input type="checkbox" name="Dept" value="ALL"/>
<input type="checkbox" name="Dept" value="HR"/>
<input type="checkbox" name="Dept" value="FINANCE"/>
<input type="checkbox" name="Dept" value="IT"/>
<input type="checkbox" name="Dept" value="SALES"/>
Try this
jQuery > 1.6
// Cache the selectors as they are being multiple times
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
// Set the other inputs property to the all checkbox
$inputs.not(this).prop('checked', this.checked);
});
// Change event for all other inputs
$inputs.not($all).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
// Get the checked checkboxes
var $checked = $others.filter(function () {
return this.checked;
});
// If length is not equal then uncheck the All checkbox
if ($others.length !== $checked.length) {
$all.prop('checked', false);
}
});
jQuery 1.4.4
var $all = $('input[value=ALL]'),
$inputs = $('input');
$all.change(function () {
var allChk = this;
$inputs.each(function() {
this.checked = allChk.checked;
});
});
$inputs.not($('input[value=ALL]')).change(function () {
var $others = $inputs.not($('input[value=ALL]'));
var $checked = $others.filter(function () {
return this.checked;
});
if ($others.length !== $checked.length) {
$all[0].checked = false;
}
});
jQuery > 1.6 Fiddle
jQuery 1.4.4 Fiddle
Try this,
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
where case is the class added to othe check boxes
For online demo visit,
http://viralpatel.net/blogs/multiple-checkbox-select-deselect-jquery-tutorial-example/
DEMO
$('input[type="checkbox"][name="Dept"]').change(function () {
if (this.value == 'ALL') {
$('input[name="Dept"]').prop('checked', this.checked);
}
});
Updated Demo with jQuery 1.5.2
$('input[type="checkbox"][name="Dept"][value="ALL"]').change(function () {
$('input[name="Dept"]').attr('checked', this.checked);
});
$('input[type="checkbox"][name="Dept"]:gt(0)').change(function () {
if (!this.checked) {
$('input[name="Dept"][value="ALL"]').removeAttr('checked');
}
if ($('input[type="checkbox"][name="Dept"]:gt(0)').length == $('input[type="checkbox"][name="Dept"]:gt(0):checked').length) {
$('input[type="checkbox"][name="Dept"][value="ALL"]').attr('checked',true);
}
});
Here's one way to do it:
$(document).ready(function() {
var $cbs = $('input[name="Dept"]').click(function() {
if (this.value==="ALL")
$cbs.prop("checked", this.checked);
else if (!this.checked)
$cbs[0].checked = false;
});
});
Jawdroppingly good demo: http://jsfiddle.net/MNbDw/2/
Note that obviously my code above has a hardcoded assumption that the "ALL" checkbox will be the first one (at the point where I unchecked it using $cbs[0]). You could change the else if case to do this instead:
$cbs.filter('[value="ALL"]').prop("checked",false);
Demo: http://jsfiddle.net/MNbDw/3/
Or change your html to give that particular checkbox an id or whatever.
UPDATE: The .prop() method was introduced in jQuery 1.6. For version 1.5.2 (as mentioned in a comment) use .attr() instead as shown here (though 1.5.2 is so old that jsfiddle doesn't actually offer it as an option so I had to add it under "External Resources"): http://jsfiddle.net/MNbDw/9/

Moving data using Select-All Checkboxes

Currently I have two tables
I have select-all functions on the top left checkboxes, but clicking on one select-all highlights all checkboxes in BOTH tables, whereas I only want all boxes to be selected in the specific 'check-all' clicked.
Also, when I do select all and click one of the directional buttons < or >, it drags all the rows fine but drags the headers with it as shown here:
My JQuery is quite simple at the moment but I'm obviously missing out on something -
$('#select-all').click(function (event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
}
else
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = false;
});
});
Where 'select-all' is the id of the select-all checkbox in the 'tarifs de quittancement'.
Any help is appreciated
EDIT
My JQuery for the > button code is as follows :
$("#move-to-1").on("click", function () {
var selected = $("#table2").find("input:checked");
selected.each(function (idx, elem) {
$(elem).closest("tr").detach().appendTo($("#table1 tbody"));
});
});
This works fine to move all from one table to the other, but I don't want the row containing the select-all checkbox/table headers to move with the rest of the row data. How can this be done?
Thanks again.
Further Edit
Now it's all sorted, except for a small bug where selecting one checkbox row (not select-all) and moving it < or > results in ALL rows being moved.
JQuery in use:
$('#move-to-1').on('click', function () {
var selected = $('#table2').find('input:checked');
selected.each(function (idx, elem) {
$(elem).closest('tbody').find('tr').detach().appendTo($("#table1 tbody"));
$('input[type=checkbox]').attr('checked', false);
});
});
$('#select-all').click(function (event) {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
You only need to modify the checkboxes inside the current table. Since you haven't shown your markup it is extremely hard to guess how the proper selector might look or whether you are using tables at all but try like this:
$('#select-all').click(function (event) {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
UPDATE:
To address your second question, assuming you have separated the headers from the body inside those tables using the <thead> and <tbody> sections which is the correct way, you could adapt your selector:
$('#move-to-1').on('click', function () {
var selected = $('#table2 tbody').find('input:checked');
selected.each(function (idx, elem) {
$(elem).closest('tr').detach().appendTo($("#table1 tbody"));
});
});
$('#select-all').click(function (event) {
// mention the table
var table = $('selector_to_your_table');
if (this.checked) {
// Iterate each checkbox
table.find(':checkbox').each(function () {
this.checked = true;
});
}
else
// Iterate each checkbox
table.find(':checkbox').each(function () {
this.checked = false;
});
});
Note
In latest version of jQuery :checkbox is deprecated. See here..
Instead of :checkbox use input[type=checkbox].
Instead of:
$(':checkbox').each(function () {
this.checked = true;
});
Do:
$('some_sort_of_selector :checkbox').attr('checked', true);
You don't need that each() loop - jQuery does it automatically. You need some kind of selector to limit which checkboxes are changed.
I notice you have #select-all - and yet you say you have two select-all checkboxes. You can't do that. ID's must be unique.

How to build a simple table filter with jQuery?

How can I build a simple table filter with good effect using jQuery? I don't mind about pagination.
list -> select data of database.
I do not want to use a plugin, I prefer the use of short code.
Example:
$('#inputFilter').keyup(function() {
var that = this;
$.each($('tr'),
function(i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('tr').eq(i).hide();
} else {
$('tr').eq(i).show();
}
});
});
CHECH THIS
I don't normally help out with this, but I got bored this morning..
http://jsfiddle.net/hHJxP/
I know it's kinda late but hope this code helps.
<script>
$(document).ready(function(){
$("#yourInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#yourTableId tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
Try testing the innerHTML of the row to the value of the input field, showing / hiding the content depending on the test-result.
$('#test').bind('keyup', function() {
var s = new RegExp(this.value);
$('tr').each(function() {
if(s.test(this.innerHTML)) $(this).show();
else $(this).hide();
});
});
JSFIDDLE with example table and input field.
edit
It might be better to use .text() instead of innerHTML. Performancewise innerHTML would be better, but .text() doesn't accept the html-tags as valid search results. JSFIDDLE #2.

Categories