On mouseenter, if a checkbox is checked, do X, else do Y - javascript

I am trying to have a checkbox on a page to show/hide passwords in password boxes. If they are hidden, then they will instead show on hover of that item.
The only thing I am struggling with is that the var is saved on page load along with when the rest of the jquery loads. How can I, on every mouseenter/leave, make sure that the checkbox is checked or not?
jsfiddle
window.hide_passwords = $('#hide_passwords').attr('checked');
if(hide_passwords) {
$("main table tbody tr").on({
mouseenter: function() {
$(this).children('td:first-child').children('input').attr('type', 'text');
},
mouseleave: function() {
$(this).children('td:first-child').children('input').attr('type', 'password');
}
});
} else {
$('input[type="password"]').attr('type', 'text');
}
$('#hide_passwords').click(function() {
if($(this).prop('checked')) {
window.hide_passwords = false;
} else {
window.hide_passwords = true;
}
});

Use .is(":checked") to check whether the checkbox is checked or not.
window.hide_passwords = $('#hide_passwords').attr('checked');
$("main table tbody tr").on({
mouseenter: function () {
if ($("#hide_passwords").is(":checked")) {
$(this).children('td:first-child').children('input').attr('type', 'text');
}
},
mouseleave: function () {
if ($("#hide_passwords").is(":checked")) {
$(this).children('td:first-child').children('input').attr('type', 'password');
}
}
});
Demo

var window.hide_passwords = document.getElementById("hide_passwords");
window.hide_passwords = window.hide_passwords.checked
var container = document.querySelectorAll("main table tbody tr");
var i = 0, length = container.length;
for (i; i < length; i++) {
container[i].addEventListener("mouseover", function() {
if (window.hide_passwords) {
// Your stuff here
} else {
}
}
}
I only work in Native JS, so sorry about the disconnect.

You can use bind and unbind methods for same behavior.
window.hide_passwords = $('#hide_passwords').attr('checked');
showPass();
function showPass() {
$("main table tbody tr").on({
mouseenter: function () {
$(this).children('td:first-child').children('input').attr('type', 'text');
},
mouseleave: function () {
$(this).children('td:first-child').children('input').attr('type', 'password');
}
});
}
$('#hide_passwords').click(function () {
if ($(this).prop('checked')) {
showPass();
} else {
$('input[type="password"]').attr('type', 'password');
$("main table tbody tr").unbind();
}
});
Demo

Related

Multiple filter for an especific table

I have this code working for any table.
$(document).ready(function () {
$('.CalendarFilter').click(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
});
It filters good, the problem I have is with an special table that is not working. I have the ID of the table but I don't know how to implement the code for work exclusively for this table ID. I tried modifying this part filter('#TABLEID > tbody > tr', values); but is nor working.
Goal: modify the code to work only with an specific table (specifically one with ID posts-table-1, see jsfiddle below), because the code, which supposedly works for any table, doesn't work
Here is an example: https://jsfiddle.net/mdomfu/gzLktpmw/3/

Combining click and dbclick

How I am supposed to combine the below ones into one single working script?
When is clicked once a color picked-up by user appears,click again the color turns in white and when double-clicked appears aqua. It is too long code, I tried to combine them, but I made mistake.
//single click
$('#pixel_canvas').on('click', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'white');
}
});
//double click
$('#pixel_canvas').on('dblclick', 'td', function () {
var color = $('#colorPicker').val();
if ($(this).hasClass("blank") == true) {
$(this).css('background-color', color);
$(this).removeClass('blank');
}
else {
$(this).addClass('blank');
$(this).css('background-color', 'aqua');
}
});
I'd go something like this:
// Take your actual 'core' code and turn it into a jQuery function:
$.fn.setColor(colorOff){
if( $(this).hasClass("blank") ){
$(this)
.css('background-color', $('#colorPicker').val())
.removeClass('blank');
} else{
$(this)
.addClass('blank')
.css('background-color',colorOff);
}
}
// Now bind the events to the element and pass the color needed for the events:
$('#pixel_canvas')
.on('click','td',function(){
$(this).setColor('white')
})
.on('dblclick','td',function(){
$(this).setColor('aqua')
});
This may help.
function doClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','white');
}
}
function doDoubleClickAction() {
var color=$('#colorPicker').val();
if($(this).hasClass("blank")==true){
$(this).css('background-color',color);
$(this).removeClass('blank');
}
else{
$(this).addClass('blank');
$(this).css('background-color','aqua');
}
}
var timer = 0;
var delay = 200;
var prevent = false;
$("#pixel_canvas")
.on("click", function() {
timer = setTimeout(function() {
if (!prevent) {
doClickAction();
}
prevent = false;
}, delay);
})
.on("dblclick", function() {
clearTimeout(timer);
prevent = true;
doDoubleClickAction();
});

Jquery message only on first row

I'm having a problem: when clicking on edit buttom, the message of the successful/error alert is displayed only on the first row even if i click on the second.
This is the js
var ROUTE = new function () {
var oGlobal = this;
this.sSaveUrl = '';
this.setSaveUrl = function (_sUrl) {
this.sSaveUrl = _sUrl;
}
this.setEventSubmit = function () {
$('[id^="route_update"]').each(function () {
$(this).click(function () {
var oData = $(this).closest('tr').find('input').serializeArray();
var oRow = $(this).closest('tr');
console.log(oData);
oReq = $.post(oGlobal.sSaveUrl, oData, function (data) {
if (data['valid'] != "true") {
//console.log('error');
//Fade in
oRow.closest('#comment').html('Error').css('display', 'block').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
} else {
//console.log('success');
//Fade in
$('#comment').html('Insert Success').fadeIn(1000);
//Fade out
setTimeout(function () {
$('#comment').html('').fadeOut(1000);
}, 1500);
//fade in
$('#comment')
}
return false;
}, 'json');
return false;
});
});
}
this.init = function () {
this.setEventSubmit();
}
}
What do I wrong?
Thanks in advance

suitable substitution in jquery

With the help of jquery I've done the following for changing the color of the row on clicking a checkbox,all the checkbox is having same class name, the code is working fine, but the requirement in one of our project was to do this using simple pure javascript (no library)
can anyone please tell me some solution for this
$(".cbxSelect").click(function (e) {
if (!$(this).closest('tr').hasClass("myclass")) {
$(this).closest('tr').css('background-color', 'yellow');
$(this).closest('tr').addClass("myclass");
} else {
$(this).closest('tr').css('background-color', 'white');
$(this).closest('tr').removeClass("myclass");
}
});
http://jsfiddle.net/Kph8M/8/
var boxes = document.querySelectorAll('.cbxSelect');
for (var i=boxes.length; i--;) {
boxes[i].addEventListener('change', handler, false);
}
function handler() {
var el = this;
while (el.parentNode) {
el = el.parentNode;
if (el.tagName.toLowerCase() === 'tr') {
break;
}
}
if (el.getAttribute('data-color') != 'yellow') {
el.style.backgroundColor = 'yellow';
el.setAttribute('data-color', 'yellow');
}else{
el.style.backgroundColor = 'white';
el.setAttribute('data-color', 'white');
}
}
FIDDLE
Since you already toggle myclass it makes sense to use it for background color:
.myclass {
background: yellow;
}
and JS:
var checks = document.querySelectorAll('.cbxSelect');
for (var i = 0; i < checks.length; i++) {
checks[i].onchange = function() {
var tr = this.parentNode.parentNode;
if (/\bmyclass\b/.test(tr.className)) {
tr.className = tr.className.replace(/\bmyclass\b/g, '');
}
else {
tr.className += ' myclass';
}
};
}
Demo: http://jsfiddle.net/dfsq/Kph8M/12/

jQuery improve table iterator

I have a table containing in every row one cell inside which is checkbox and label for that checkbox.
What I'm trying to do it to hide rows based on inputed text.
Basically this is list on names and I want to filter/hide those that don't contain entered text.
This is my function:
$(function () {
$('#user_name').keyup(function () {
if ($.trim($('input#user_name').val()) == '') {
$('table.myList >tbody >tr').each(function (index, value) {
$(this).css("display", "block");
});
} else {
$('table.myList >tbody >tr').each(function (index, value) {
if ($(this).find('td > label').length > 0) {
if ($(this).find('td > label').html().toLowerCase().indexOf($.trim($('input#user_name').val()).toLowerCase()) >= 0) {
$(this).css("display", "block");
} else {
$(this).css("display", "none");
}
}
});
}
});
});
This code works, if my table has 40 records its fast, but when I increment list to 500 it slows down and crashes my browser after time.
I'm looking for a way to improve this code to work faster.
Here is link to mock-up code: http://jsfiddle.net/gGxcS/
==UPDATE==
Here is my final solution based on answers of #scessor and #nnnnnn:
$(function () {
var $tableRows = $('table.myList tr');
var lastInput = '';
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if(lastInput==sValue) return;
if (sValue == '') {
$tableRows.show();
} else {
$tableRows.each(function () {
var oLabel = $(this).find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
}
});
lastInput=sValue;
}
});
$('img.removeSelections').click(function () {
$('table.myList input[type="checkbox"]').prop("checked", false);
})
});
Can you test this code (with lot of elements)?
$(function () {
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if (sValue == '') {
$('table.myList tr').show();
} else {
$('table.myList tr').each(function() {
var jThis = $(this);
var oLabel = jThis.find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
jThis.show();
} else {
jThis.hide();
}
}
});
}
});
});
Don't call functions with same parameters twice (e.g. $.trim($('input#user_name').val());).
Use short selectors.
Use jquery each only if necessarry (e.g. don't needed here: $('table.myList >tbody >tr').each(function (index, value) {).
=== UPDATE ===
If somebody holds backspace to long, it will set all trs visible again and again. To prevent this you could check, if the last value is equal to the current value. If true, do nothing.
=== UPDATE ===
To uncheck all checkboxes, it depends on your jQuery version.
With jQuery 1.6 and higher:
$('table.myList input[type="checkbox"]').prop("checked", false);
Before:
$('table.myList input[type="checkbox"]').attr("checked", false);
I'd suggest that you cache your jQuery objects - given that you want to process on every keystroke I'd cache the table rows object outside of the keyup handler. Also, don't call functions inside the .each() loop when you can call them once outside - e.g., no need to be calling $.trim($('input#user_name').val()).toLowerCase() on every .each() iteration.
$(function () {
var $tableRows = $('table.myList >tbody >tr');
$('#user_name').keyup(function () {
var searchStr = $.trim($('input#user_name').val()).toLowerCase();
if (searchStr === '') {
$tableRows.css("display", "block");
} else {
$tableRows.each(function (index, value) {
var $this = $(this),
$label =$this.find('td > label');
if ($label.length > 0) {
if ($label.html().toLowerCase().indexOf(searchStr) >= 0) {
$this.css("display", "block");
} else {
$this.css("display", "none");
}
}
});
}
});
});
Demo: http://jsfiddle.net/gGxcS/3/

Categories

Resources