Table multi column filter - javascript

I want to write a multi column filter for one of my tables. I dont want for now to do it with plugins. I found that and its working but only for 1 column. Do you have any ideas how to modify it for all columns ?
$(".filter").keyup(function(e) { // filter is class
if (e.keyCode == 13) {
var indexColumn = $(this).attr('data-id');
console.log('INDEX ' + indexColumn);
console.log("value=%o", this.value);
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr")
//hide all the rows
if (this.value == "") {
jo.show();
return;
}
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
// console.log(data[d]);
return true;
}
}
return false;
}).show(); //show the rows that match.
updateTotals();
}
});
Fiddle demo

You can use each() jquery method in this case.
$(".filter").each(function() {
$(this).keyup(function(e) {
if (e.keyCode == 13) {
var indexColumn = $(this).attr('data-id');
console.log('INDEX ' + indexColumn);
console.log("value=%o", this.value);
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr")
//hide all the rows
if (this.value == "") {
jo.show();
return;
}
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
// console.log(data[d]);
return true;
}
}
return false;
}).show(); //show the rows that match.
}
})
});
JS Demo

Related

How to remove nth-1 array index in Javascript while doing Excel export

How do I remove Nth-1 rows from an array?
I am trying to export my records in Excel but am getting some html code in my Excel file. The reason for this is I am trying to remove that row but am not able to delete that particular row, because that row is dynamically changing.
I am getting data in an array while checking it in debug mode.
Can anyone help me with how I can remove total length of Array-1? For example, if I have 40 records then I want remove 39th position.
This is my JS Code:
[![$(function () {
var exportFlag = false;
var reportGrid = $(time.report.gridId);
if (reportGrid.length > 0) {
$(time.report.gridId).data("kendoGrid").bind("excelExport",
function(e) {
if (!exportFlag) {
var sheet = e.workbook.sheets\[0\];
var columns = e.sender.columns;
e.preventDefault();
exportFlag = true;
setTimeout(function() {
e.sender.saveAsExcel();
},
1000);
} else {
// e.sender.hideColumn(0);
//e.sender.hideColumn(e.sender.columns.length + 1);
exportFlag = false;
}
});
});][1]][1]
onExcelExport: function (e) {
setTimeout("location.reload(true);", 1000);
e.sender.hideColumn("OutIp");
e.sender.hideColumn("InIp");
var sheet = e.workbook.sheets[0];
var rows = sheet.rows;
var rowIdx, colIdx, cells, cell;
for (rowIdx = 0; rowIdx < rows.length; rowIdx++) {
if (rows[rowIdx].type === "data") {
cells = rows[rowIdx].cells;
var color = "#ffffff";
if (cells[0].value === true) {
color = "#ff0000";
}
for (colIdx = sheet.freezePane.colSplit; colIdx < cells.length; colIdx++) {
cell = cells[colIdx];
cell.background = color;
//cell.value = kendo.toString(cell.value, "c");
if (colIdx === 4) {
cell.value = cell.value.Hours + ":" + cell.value.Minutes;
}
else if (cell.value !== undefined && cell.value !== null && cell.value.Hours !== undefined) {
cell.value = utcTimeToLocalTime(cell.value.Hours + ":" + cell.value.Minutes);
}
else if (cell.value !== undefined && cell.value !== null && cell.value === true) {
cell.value = "Yes";
}
else if (cell.value !== undefined && cell.value !== null && cell.value === false) {
cell.value = "No";
}
}
}
}
},
To remove the last-but-one element of any array you could do:
var numberElements = yourArray.length;
var targetElement = numbElements - 1;
// second parameter is number of elements to remove
yourArray.splice(targetElement, 1);

How to display all child elements in JQuery/Javascript?

I am trying to display multiple child elements in jQuery but only the first child element gets displayed. I can force the browser to show all of them through Inspect and changing the css display from none to block. Can anyone help me find the problem in my code.I use Radio buttons, this is the code :
<script type="text/javascript">
$(document).ready(function () {
$('##radioButtonListSectionId input[type="radio"]
[checked="checked"]').each(function () {
ShowRadioButtonListDependentField(this, false);
});
});
$('##radioButtonListSectionId input[type="radio"]').change(function
() {
var result = $(this).val();
$('##uniqueID-hidden').val(result);
ShowRadioButtonListDependentField(this, false);
});
function ShowRadioButtonListDependentField(element, show) {
debugger;
var fieldKey = $(element).val(), children;
var currentId = element.attributes["currentid"].value;
if (currentId != 0) {
if ($('.main-dialogbox.modal.fade.in').length > 0)
children = $('.modal-body .control-group[parentid=' +
currentId + ']');
else if ($('.idea-task.open').length > 0)
children = $('.idea-task .control-group[parentid=' +
currentId + ']');
else
children = $('.control-group[parentid=' + currentId +
']');
if ($(element).is(":checked") && $(element).is(":visible"))
show = true;
else
show = false;
children.hide();
children.each(function () {
var keys =
this.attributes["parentOptionKey"].value.split("</br>");
var haschildren = this.attributes["haschildren"].value;
for (var i = 0; i < keys.length; i++) {
if (keys[i] == fieldKey) {
if (show) {
$(this).show();
show = false;
$(this.getElementsByClassName("ishidden")).val("False");
} else {
$(this).hide();
$(this.getElementsByClassName("ishidden")).val("True");
if (haschildren.toLowerCase() == "true") {
ShowCheckListDependentField(this,
false);
}
}
}
else {
$(this.getElementsByClassName("ishidden")).val("True");
}
}
});
}
}
</script>

Cant get the session value using javascript in C#

I am trying to get 4 values from the session,while i get two of them,other two are missing.i am still learning so please bear with me if my question is too naive.I have this checkbox and two radio buttons in a tree view.
ASP.NET Code
<div class="control-label col-sm-1">
<asp:TreeView runat="server" ID="tvAi" Font-Bold="true" ShowLines="true" EnableClientScript="true"
ShowExpandCollapse="true" ShowCheckBoxes="All" >
</asp:TreeView>
<asp:HiddenField ID="hdMobile" runat="server" />
</div>
Now when i go to the chrome developer tool and check the values of the radio button the session values are binding well and shows like this.
<input type="radio" checked="checked" id="rad_01-02-00000622" name="rdoC1" value="01-02-00000622_Deposit_1_109861">
Those four values separated by '_' are accountNumber_accountType_officeId_customerId respectively.
The Javascript Code which sets session
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdMobile
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
My Code behind setting the session
[WebMethod]
public static void SetSession()
{
System.Web.HttpContext.Current.Session["AccountMoney"] = "";
}
And binding treeview code
private void BindTreeViewForMobile()
{
_customerId = Convert.ToInt64(Session["CustomerId"]);
if (_customerId > 0)
{
DataTable dtAccount = new DataTable();
dtAccount = BusinessLayer.SMS.SmsSetup.GetActiveAccountListByCustomer(_customerId);
tvAi.Nodes.Clear();
int redindex = 1;
string accNumber = "";
var customerMobileBanking = BusinessLayer.SMS.MobileBankingSetup.GetMobileBankingCustomer(_customerId);
foreach (DataRow dr in dtAccount.Rows)
{
if (customerMobileBanking != null)
{
foreach (Common.SMS.MobileBankingSetup ss in customerMobileBanking)
{
if (ss.AccountNumber == dr["account_number"].ToString())
{
if (ss.FeeCharges)
{
accNumber = ss.AccountNumber;
break;
}
else
{
accNumber = "";
break;
}
}
}
}
TreeNode master = new TreeNode(dr["account_number"].ToString(), dr["account_number"].ToString());
master.ShowCheckBox = true;
tvAi.Nodes.Add(master);
master.SelectAction = TreeNodeSelectAction.None;
string sk = "";
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
master.Checked = true;
}
}
for (int i = 0; i <= 1; i++)
{
TreeNode child = new TreeNode(sk, sk);
child.SelectAction = TreeNodeSelectAction.None;
child.ShowCheckBox = false;
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
child.Text = "<input type='radio' checked='checked' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
}
else
{
child.Text = "<input type='radio' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
master.ChildNodes.Add(child);
}
redindex++;
}
}
}
The problem happens here when i am trying to get the session value in here
var sess = System.Web.HttpContext.Current.Session["AccountMoney"].ToString();
Here i only get the two session value not all 4.What am i doing wrong?Code must be too long for your time.any help appreciated.Thanks
I faced this before and search got me nowhere, went ahead and used cookies for the values I wanna read from JS. it works like a charm! Try it Get Cookies by name JS

Issues in remove comma in javascript

When i entered only one email id, and check in inspecter, it shows like this
I need to remove commas,if i enter only one id and it need to show commas, if i enter one more or multiple id's given it shows comma. Can you please help ?
function GetTextValue() {
$(divValue).empty();
$(divValue).remove(); values = '';
values += this.value + ','
});
document.all.contact_list.value = values;
}
You can do it like that.
function GetTextValue() {
$(divValue).empty();
$(divValue).remove(); values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({
padding:'5px', width:'200px'
});
if (this.value == '') {
// alert('Empty');
} else if (values != '') {
values += ',';
}
values += this.value;
});
document.all.contact_list.value = values;
}
JSFiddle
Hope it will be useful for you.
function GetTextValue() {
$(divValue).empty();
$(divValue).remove();
var values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({
padding:'5px', width:'200px'
});
if(this.value.trim() != ''){
if(values != ''){
values += ',';
}
values += this.value.trim();
}
});
document.all.contact_list.value = values;
}
function GetTextValue() {
$(divValue).empty();
$(divValue).remove();
var values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({padding:'5px', width:'200px'});
if(this.value != '') {
values += this.value;
values += ',';
}
});
document.all.contact_list.value = value.substring(0, value.length - 1);//remove last comma
}

JQuery / JavaScript Keyboard event

I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);

Categories