I'm beginner in JavaScript, and Stackoverflow, but I have a problem.
Following checkbox looks like this:
All dots, are bitmaps,
When, I checked 3 options, all options have green bitmaps , but when I checked additionally another option, this option will be red bitmap.
And now when I unchecked one green option, red option should be automatic changed to green bitmap, but now when one green option will be unchecked, in checkbox are 2 greens, and 1 red, and should be 3 greens :(
here is my code:
JS function:
function change_src(ch,p){
if(ch.checked == true){
counter++;
alert(counter);
document.getElementById(p).src = "lamp2.png";
if(counter>3){
document.getElementById(p).src = "lamp3.png";
alert(counter);
}
else{
document.getElementById(p).src = "lamp2.png";
}
Here is part my html code:
<body >
<h1 id="title">
Formularz</h1>
<hr />
<h2 id="title2">
change 3 options</h2>
<hr />
<form id="blablal" action="index.htm" >
<table class="center">
<tr>
<td>
<div class='lamp'>
<img id="pic" name="pic1" src="lamp.png" alt="some_text"></div>
</td>
<td>
C
</td>
<td>
<input id="Check_C" type="checkbox" onclick="change_src(this,'pic')" /><br />
</td>
</tr>
<tr>
<td>
<div class='lamp'>
<img id="pic2" name="pic2" src="lamp.png" alt="some_text"></div>
</td>
<td>
C++
</td>
<td>
<input id="Check_Cpp" type="checkbox" onchange="change_src(this,'pic2')"/><br />
</td>
</tr>
<tr>
Here is my jsfiddle.
Check this one buddy. Hope it's helpful. jsfiddle
JAVASCRIPT:
var counter = 0;
var green = [];
var red = [];
function change_src(ch,p){
if(ch.checked == true){
counter++;
if(green.length>=3){
red.push(p);
document.getElementById(p).src = "http://www25.speedyshare.com/8FpkJ/download/lamp3.png";
}else{
green.push(p)
document.getElementById(p).src = "http://www22.speedyshare.com/ec8Da/download/lamp2.png";
}
}
else{
counter--;
var indexGreen = green.indexOf(p);
var indexRed = red.indexOf(p);
if(indexGreen != -1){
green.splice(indexGreen, 1);
}
if(indexRed != -1){
red.splice(indexRed,1);
}
document.getElementById(p).src = "http://www23.speedyshare.com/EHUe9/download/lamp.PNG";
if(green.length<3 && red.length>0){
var item = red[0];
green.push(item);
red.splice(item,1);
document.getElementById(item).src = "http://www22.speedyshare.com/ec8Da/download/lamp2.png";
}
}
alert("green: "+green+ " red: "+red);
}
Related
Here's a jsfiddle: https://jsfiddle.net/m6vxgg0m/15/
The console log shows the output.
I've been trying to get the number of occurrences of a string in an array using jQuery. The loop I'm using to check if the string value is present in each index of the array appears to be correct. I'm not sure why it isn't working correctly. I never get the correct counter value. If I keep the string in the text field and I keep hitting enter, the counter keeps increasing even though I set the counter back to 0 right inside the keyup event. If there are two occurrences of a string in the array, the counter should always display the value of 2. But it doesn't. Very frustrated.
JS:
$(function(){ keywordSearchFeature() });
function keywordSearchFeature(){
// Selector Variables
var inputSel = $('#search-term');
var noticeLblSel = $('.searchInstance');
var contentSel = $('.RadGrid.RadGrid_Default.mydatagrid .rgMasterTable tr');
// Functional Variables
var keywordVal;
var keywordValL; // keywordVal lowercase
var keyCounter = 0; // counter
var cellValues = []; //
var cellValuesL = []; // cellValues lowercase
// Type keyword
inputSel.on('keyup', function(e){
// Reset Counter
keyCounter = 0;
// Keyword Value
keywordVal = $(this).val();
// Keyword Lowercase Value
keywordValL = keywordVal.toLowerCase();
// console.log(keywordValL);
// Clear notice label when retyping
noticeLblSel.text('');
// Enter Key
if (e.which == 13) {
if(keywordValL != null && keywordValL != '' && keywordValL.length > 3){
console.log('ENTER KEY CLICKED: Value entered is: ' + keywordValL);
// Store content in arraykeyinstances[]
contentSel.each(function(i,tr){
var tdLines = $('td',tr).map(function(i,td){
// Get each cell string, and trim whitespace
var tdCellContent = $(td).text().trim();
// console.log(tdCellContent);
// Push each cell value to array
cellValues.push(tdCellContent);
cellValuesL.push(tdCellContent.toLowerCase());
});
});
// console.log(cellValues);
console.log(cellValuesL);
for (var i = 0; i < cellValuesL.length; i++) {
if (cellValuesL[i] == keywordValL) {
keyCounter++;
}
}
console.log(keyCounter);
// Notice label text
if(keyCounter > 0) {
noticeLblSel.text('Instance 1 of ' + keyCounter + ' found on this page.');
} else {
noticeLblSel.text('No instances for "' + keywordVal + '" found.');
}
} else {
noticeLblSel.text('Please enter 4 or more characters.');
}
}
});
// Click Events
//$(document).on('click','.btn-searchnext',function(){});
//$(document).on('click','.btn-searchprev',function(){});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formholder searchkeywordholder">
<div class="form_inner">
<div class="formrow form-col-1" tabindex="0">
<div id="find-in-page">
<div class="fielditem searchfielditem">
<input type="text"
id="search-term"
placeholder="Type in the phrase to search and click Next..."
title="Enter Search Phrase"
class="text searchfield"
aria-label="Search Keyword Field" />
<button id="next"
class="button bttn-clear btn-searchnext"
title="Next"
aria-label="Search Next Button">
Next
</button>
<button id="prev"
class="button bttn-find btn-searchprev"
title="Previous"
aria-label="Search Previous Button">
Previous
</button>
</div>
<label id="labelResult" class="searchInstance"></label>
</div>
</div>
</div>
</div>
<div class="RadGrid RadGrid_Default mydatagrid staticheaders nostripes" id="ctl00_MainContent_customProjectAssets_gridItems" tabindex="0">
<div class="rgDataDiv" id="ctl00_MainContent_customProjectAssets_gridItems_GridData">
<table class="rgMasterTable rgClipCells rgClipCells" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00">
<tbody>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__0">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divChildAssetStyle">
Antenna B1
</div>
</div>
</div>
</td>
<td>
Equipment and Materials
</td>
<td>
C2 Equipment
</td>
<td>
Antenna
</td>
<td>
Basic
</td>
<td>
B1
</td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divRating" title="Asset's Rate">
0.36
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanAssetTag" title="Incident Response/Recovery">IRR</span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxDelete" onclick="$.onCheckDeleteChange('0');" type="checkbox">
</td>
</tr>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__1">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divChildAssetStyle">
Content 1
</div>
</div>
</div>
</td>
<td>
This is content
</td>
<td>
My text
</td>
<td>
lorem ipsum dolor
</td>
<td>
sit amet
</td>
<td></td>
<td>
<div class="rating_general rating_orange" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divRating" title="Asset's Rate">
0.56
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxDelete" onclick="$.onCheckDeleteChange('1');" type="checkbox">
</td>
</tr>
<tr class="rgRow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__2">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div class="iconGridSubordinateArrow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildArrowImage" style="float: left; width: 17px;"></div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildAssetStyle" style="float: left; width: 180px;">
equivalent
</div>
</div>
</div>
</td>
<td>
People
</td>
<td>
Individuals
</td>
<td>
lorem
</td>
<td>
ipsum
</td>
<td></td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divRating" title="Asset's Rate">
0.44
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxDelete" onclick="$.onCheckDeleteChange('2');" type="checkbox">
</td>
</tr>
</tbody>
</table>
</div>
</div>
First, the reason that your keyCounter increases each time you hit enter is because you do not reset cellValuesL to an empty array in your keyup event handler. This means that after the first time you hit enter, the contentSel table is parsed and 36 text values are pushed onto cellValuesL. The next time you hit enter, contentSel is parsed again and the same 36 values are again pushed onto cellValuesL so that cellValuesL.length is now 72. The same 36 values get pushed onto cellValuesL each time you hit the enter key.
One way you can fix this is by moving var cellValuesL = []; to inside the keyup event handler. However, a better solution is to move the code that builds the cellValuesL array (contentSel.each) to outside of the keyup event handler. As the text values in the table never change, it does not make sense to keep fetching the texts from the table and building a new array each time the user presses the enter key.
To your second point about having two occurrences of a string in your cellValuesL array, I think you must be confused about what your code is checking. Your code loops through each value in cellValuesL and for each element in that array that equals the lower-cased user input, keyCounter is incremented. In your example, no two elements in cellValuesL are equal, so it is not possible for the loop to ever produce more than one match. What I assume you must want to is to check whether each element in cellValuesL contains the lower-cased user input. If this is the desired behavior, you will need to update your conditional to the following:
for (var i = 0; i < cellValuesL.length; i++) {
if (cellValuesL[i].indexOf(keywordValL) > -1) {
keyCounter++;
}
}
A more modern and elegant way of achieving the same thing as the code above would be to use Array.prototype.filter and an Arrow Function:
keyCounter = cellValuesL.filter(val => val.indexOf(keywordValL) > -1).length;
Finally, I want to suggest that your JavaScript code can be cleaned-up quite a bit. Here is an example that doesn't use any ES6 language features:
$(function () {
var inputSel = $('#search-term');
var contentSel = $('.RadGrid.RadGrid_Default.mydatagrid .rgMasterTable tr');
var noticeLblSel = $('.searchInstance');
var cellValuesL = $('td', contentSel).map(function () {
return $(this).text().trim().toLowerCase();
}).get();
inputSel.on('keyup', function (e) {
noticeLblSel.text('');
if (e.which !== 13) { return; }
var keywordVal = $(this).val();
var keywordValL = keywordVal.toLowerCase();
if (!keywordValL || keywordValL.length <= 3) {
noticeLblSel.text('Please enter 4 or more characters.');
return;
}
var keyCounter = cellValuesL.filter(function (val) {
return val.indexOf(keywordValL) > -1;
}).length;
if (keyCounter > 0) {
noticeLblSel.text('Instance 1 of ' + keyCounter + ' found on this page.');
} else {
noticeLblSel.text('No instances for "' + keywordVal + '" found.');
}
});
});
I have also created an example fiddle.
I'm trying to modify a JS script to fix a problem for searching for a keyword, and I'm not sure what the issue is. The script works only in Internet Explorer, which is a minor issue.
Here is a JS Fiddle: https://jsfiddle.net/ettt14k7/5/
The purpose of this script is to find a keyword in a datagrid made with <telerik:RadGrid />. When the desired keyword is entered into the search field, the current instance, if any is present, is highlighted using .select().
I'm hoping someone could help me modify the script so that the current instance is wrapped with <span class="searchhighlighted"> ... </span> so that I can then control the highlighting with CSS, as well as also fixing the issue for why it only works in IE. I've already tried applying the following:
instances[currHighlighted].html = '<span class="searchhighlighted">' + instances[currHighlighted].text + '</span>';
But the above does nothing. If I change the above .html to use .text as in the following:
instances[currHighlighted].text = '<span class="searchhighlighted">' + instances[currHighlighted].text + '</span>';
It works. But .text outputs as a string and doesn't render html tags as tags.
Any help is greatly appreciated. Thanks
HTML:
<div class="formholder searchkeywordholder">
<div class="form_inner">
<div class="formrow form-col-1" tabindex="0">
<div id="find-in-page">
<div class="fielditem searchfielditem">
<input type="text"
id="search-term"
placeholder="Type in the phrase to search and click Next..."
title="Enter Search Phrase"
class="text searchfield"
aria-label="Search Keyword Field" />
<button id="next"
class="button bttn-clear btn-searchnext"
title="Next"
aria-label="Search Next Button">
Next
</button>
<button id="prev"
class="button bttn-find btn-searchprev"
title="Previous"
aria-label="Search Previous Button">
Previous
</button>
</div>
<label id="labelResult" class="searchInstance"></label>
</div>
</div>
</div>
</div>
<div class="RadGrid RadGrid_Default mydatagrid staticheaders nostripes" id="ctl00_MainContent_customProjectAssets_gridItems" tabindex="0">
<div class="rgDataDiv" id="ctl00_MainContent_customProjectAssets_gridItems_GridData">
<table class="rgMasterTable rgClipCells rgClipCells" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00">
<tbody>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__0">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divChildAssetStyle">
Antenna B1
</div>
</div>
</div>
</td>
<td>
Equipment and Materials
</td>
<td>
C2 Equipment
</td>
<td>
Antenna
</td>
<td>
Basic
</td>
<td>
B1
</td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divRating" title="Asset's Rate">
0.36
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanAssetTag" title="Incident Response/Recovery">IRR</span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxDelete" onclick="$.onCheckDeleteChange('0');" type="checkbox">
</td>
</tr>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__1">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divChildAssetStyle">
Content 1
</div>
</div>
</div>
</td>
<td>
This is content
</td>
<td>
My text
</td>
<td>
lorem ipsum dolor
</td>
<td>
sit amet
</td>
<td></td>
<td>
<div class="rating_general rating_orange" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divRating" title="Asset's Rate">
0.56
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxDelete" onclick="$.onCheckDeleteChange('1');" type="checkbox">
</td>
</tr>
<tr class="rgRow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__2">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div class="iconGridSubordinateArrow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildArrowImage" style="float: left; width: 17px;"></div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildAssetStyle" style="float: left; width: 180px;">
equivalent
</div>
</div>
</div>
</td>
<td>
People
</td>
<td>
Individuals
</td>
<td>
lorem
</td>
<td>
ipsum
</td>
<td></td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divRating" title="Asset's Rate">
0.44
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxDelete" onclick="$.onCheckDeleteChange('2');" type="checkbox">
</td>
</tr>
</tbody>
</table>
</div>
</div>
JS:
$(document).ready(function () {
$(document).on('click', '.btn-searchnext', findNextInstance);
$(document).on('click', '.btn-searchprev', findPrevInstance);
});
var currHighlighted = null;
var instances = null;
var str = null;
var pageChanged = false;
var isWhiteSpace = false;
var batchEdit = false;
//onkeydown = function (e) {
$(document).on('keydown', '#search-term', function(e) {
var search = $('#search-term');
var active = $(':focus');
if (e.which == 13) { // ENTER key
// fpsb-495: check that focus isn't on radconfirm, pager textbox, and make sure the control is visible
if (
active.hasClass("rwOkBtn") != -1 &&
active.hasClass("rwCancelBtn") &&
active.hasClass("rgPager") == -1 &&
$('#find-in-page').css('display') != 'none' &&
!batchEdit
) {
if (str != search.val()) {
findStrings();
}
findNextInstance();
}
}
});
//}
// returns true if txtRng is within a DIV tag with a classname "divClass"
function isInDivClass(elt, divClass) {
elt = elt.parentElement();
while (elt != null) {
// the button text shouldn't be picked up by the search control
if (elt.className == "rgButtonText") {
return false;
}
if (elt.tagName === "DIV" && elt.className.indexOf(divClass) !== -1) {
return true;
} else {
elt = elt.parentElement;
}
}
return false;
}
// finds all instances of string in textfield on page
function findStrings() {
//str = document.getElementById('search-term').value;
str = $('#search-term').val();
isWhiteSpace = str.trim() == "";
instances = new Array();
currHighlighted = null;
if (str && !isWhiteSpace) {
var strFound = true;
// used so that the next text range will only look forward on page for string
var prevTextRange = null;
while (strFound) {
// creates a text range obj
var currTextRange = self.document.body.createTextRange();
if (prevTextRange != null)
// starts current range at end point of last range, so no duplicate finds
currTextRange.setEndPoint("StartToEnd", prevTextRange);
strFound = currTextRange.findText(str);
var isInDiv = isInDivClass(currTextRange, "RadGrid RadGrid_Default mydatagrid");
if (
strFound &&
isInDiv &&
currTextRange.getClientRects().length > 0
) {
instances.push(currTextRange);
}
prevTextRange = currTextRange;
} // end while
} else { // end if
instances = null;
return;
}
if (instances.length > 0) {
// starts at -1 so it will rollover for Prev, start at 1 for Next
currHighlighted = -1;
}
return;
}
// highlights the next word in instances array for the current search term
function findNextInstance() {
// call findStrings() if page was changed
//if (pageChanged || str != document.getElementById('search-term').value) {
if (pageChanged || str != $('#search-term').val()) {
findStrings();
pageChanged = false;
}
// if nothing in text field or no instances of string on page
if (!instances || instances.length === 0 || !str) {
if (str != null || isWhiteSpace) {
if (str.length == 0 || isWhiteSpace) {
radalert("Please enter a phrase to search!", 250, 110);
$('.searchInstance').text("");
} else {
$('.searchInstance').text("No instances found on this page.");
radalert("Searched string not found on this page!", 250, 110);
}
return;
} else if (str == null) {
//alert("in find next when str i snull: " + str);
//radalert("Please enter a word to search!", 250, 110);
console.log('Field left empty. Nothing to search.');
}
$('.searchInstance').text("");
return;
}
// allows Next to "roll over" from last instance to first instance again
currHighlighted = currHighlighted + 1;
if (currHighlighted == instances.length || currHighlighted == -1) {
currHighlighted = 0;
}
instances[currHighlighted].select();
$('.searchInstance').text("Instance " + (currHighlighted + 1) + " of " + instances.length + " found on this page.");
return false;
}
// highlights the previous word in instances array for the current search term
function findPrevInstance() {
// call findStrings() if page was changed
//if (pageChanged || str != document.getElementById('search-term').value) {
if (pageChanged || str != $('#search-term').val()) {
findStrings();
pageChanged = false;
}
// if nothing in text field or no instances of string on page
if (!instances || instances.length === 0 || !str) {
if (str != null || isWhiteSpace) {
if (str.length == 0 || isWhiteSpace) {
radalert("Please enter a phrase to search!", 250, 110);
$('.searchInstance').text("");
} else {
radalert("Searched string not found on this page!", 250, 110);
$('.searchInstance').text("No instances found on this page.");
}
} else if (str == null) {
radalert("Please enter a phrase to search!", 250, 110);
}
return;
}
// allows Prev to "roll over" from first instance to last instance
if (--currHighlighted < 0)
currHighlighted = instances.length - 1;
instances[currHighlighted].select();
$('.searchInstance').text("Instance " + (currHighlighted + 1) + " of " + instances.length + " found on this page.");
return false;
}
function shouldRefresh() {
// next time Next or Prev is clicked, call findStrings again since grid state is changed
pageChanged = true;
//var searchTerm = document.getElementById('search-term').value;
var searchTerm = $('#search-term').val();
if (searchTerm != null && searchTerm !== '') {
$('.searchInstance').text("Page changed, press Next or Previous to refresh search!");
}
}
function clearSearchField() {
//document.getElementById('search-term').value = "";
$('#search-term').val("");
$('.searchInstance').text("");
instances = null;
isWhiteSpace = false;
}
function ToggleSearchDiv(status) {
// document.getElementById('find-in-page').style.display = status;
if (status == 'none') {
document.getElementsByClassName('searchkeywordholder')[0].style.display = 'none';
} else {
// We want to avoid using display: inline
document.getElementsByClassName('searchkeywordholder')[0].style.display = 'block';
}
}
function ToggleBatchEdit(status) {
batchEdit = status;
}
// END of find in page
I did an example about replacing the input value when the row is deleted but is not working (this is not a static example).
<script src="./edit_files/prototype.js" type="text/javascript"></script>
<script src="./edit_files/application.js" type="text/javascript"></script>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="cristianoronaldo#realmadrid.com"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="ONLY THE INPUT WILL BE test#hotmail.com IF I CLICK ON DELETE"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
Here is the application.js file:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
I tried this code but only works if I remove the first row.
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
$('should_change_value').update("test#hotmail.com");
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
Here is the live example in jsfiddle
Here is the example download on Github but is not replacing the input value correctly
Ok I got it, you want to change the input value when the row is deleted, so do this:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
var element_text2 = $(element).up('.contact').down('.should_change_value',0);
element_text2.className = 'should_change_value';
element_text2.value = 'test#hotmail.com';
if (should_destroy) { $(element).next('.should_destroy').value = 1;}
$(element).up('.contact').hide();
}
I want to do something like this: user selects one radio button (lock,delete or compare).
I want to show to him only the relevant column from the table. (each option has different column). The table is ajax.
I guess i need to change the display style for every cell but i don't know how.
Here is example:
Here i want to change the display of the cells
function ButtonForTbl(value) {
var x=document.getElementById("audithead").rows[0].cells;
if (value == "lock"){
document.getElementById('lock').checked = true;
//something like for(...)lockCell.style.display=''
//something like for(...)deleteCell.style.display='none'
//something like for(...)compareCell.style.display='none'
}
else if(value == "delete"){
document.getElementById('delete').checked = true;
//something like for(...)lockCell.style.display='none'
//something like for(...)deleteCell.style.display=''
//something like for(...)compareCell.style.display='none'
}
else{
document.getElementById('compare').checked = true;
}
}
I guess i need something like that:
for (i = 0; i < deleteCell.length; i++)
deleteCell[i].style.display='' = true ;
The table:
oCell = oRow.insertCell(-1);
oCell.setAttribute('id','comCell' );
oCell.setAttribute('align', 'center');
oCell.innerHTML = "<input type='checkbox' id='com' value='"+ ind + "'name='com[]'>";
oCell = oRow.insertCell(-1);
oCell.setAttribute('id','lockCell' );
oCell.setAttribute('align', 'center');
oCell.innerHTML = "<input type='checkbox' id='lock' value='"+ ind + "'name='lock[]'>";
Radio buttons:
<input type="radio" value="compare" id="compare" name="choose" onclick="ButtonForTbl(this.value)"/> Compare
<input type="radio" value="delete" id="delete" name="choose" onclick="ButtonForTbl(this.value)"/> Delete
<input type="radio" value="lock" id="lock" name="choose" onclick="ButtonForTbl(this.value)"/> Lock<br/>
The table html:
<table class="auditable">
<thead id="audithead">
<tr><td></td></tr>
</thead>
<tbody id="auditTblBody">
</tbody>
</table>
EDIT:
Full row is like that:
<tr>
<td align="center" id="lockCell" style="display: none;">
<input type="checkbox" onclick="" name="lock[]" value="1500" id="lock"></td>
<td align="center" id="delCell" style="display: none;">
<input type="checkbox" name="del[]" value="1500"></td>
<td align="center" id="comCell">
<input type="checkbox" onclick="setChecks(this)" name="com[]" value="1500" id="com"></td>
<td width="65px">100% 1/1</td><td width="105px">2011-01-10 17:47:37</td>
</tr>
Thank you so much!
You can do the same thing with a div or any other element. The javascript would look like:
<script language='javascript'>
<!-- //
function setProperties(obj)
{
if(obj.value == "yes")
{
document.mydiv.style.display = "block";
} else {
document.mydiv.style.display = "none";
}
}
// -->
</script>
And in the body:
<input type=radio name="update" value="yes" checked onclick="setProperties(this)">Yes<br />
<input type=radio name="update" value="no" onclick="setProperties(this)">No<br />
<div id='mydiv'>some text here</div>
I have a table with different places, and implemented some simple buttons that allow you to filter the list. First filter is location (north, east, central, south, west) which is based on postcode. Another filter is on "impress". This shows you only the places that have have 4 or higher value in the column. Filters work great separately, but not together. The result that I am after is when I press "West" is shows me the places in "West, when I then click impress, I expect to see the places in west with a 4 or 5 score for impress.
JSFiddle here
$('.table td.postcode').each(function() {
var cellText = $(this).html();
var locationString = cellText.substring(0,2);
if (locationString.indexOf('W') > -1){
$(this).parent().addClass('west');
}
if (locationString.indexOf('C') > -1){
$(this).parent().addClass('central');
}
if (locationString.indexOf('E') > -1){
$(this).parent().addClass('east');
}
if (locationString.indexOf('S') > -1){
$(this).parent().addClass('south');
}
if (locationString.indexOf('N') > -1){
$(this).parent().addClass('north');
}
});
$("input[name='filterStatus'], select.filter").change(function () {
var classes = [];
$("input[name='filterStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if (classes == "") {
// if no filters selected, show all items
$("#StatusTable tbody tr").show();
} else {
// otherwise, hide everything...
$("#StatusTable tbody tr").hide();
// then show only the matching items
rows = $("#StatusTable tr").filter(classes.length ? classes.join(',') : '*');
if (rows.size() > 0) {
rows.show();
}
}
});
$("input[name='impressStatus']").change(function(){
var classes = [];
$("input[name='impressStatus']").each(function() {
if ($(this).is(":checked")) {
classes.push('.'+$(this).val());
}
});
if(classes == ""){
$("#StatusTable tbody tr").show();
}
else{
$(".table td.impress").each(function(){
if($(this).data("impress") >= 4){
$(this).parent().show();
}
else{
$(this).parent().hide();
}
});
}
});
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--BUTTON FILTERS -->
<div class="btn-toolbar" role="toolbar" aria-label="...">
<div class="btn-group" style="" data-toggle="buttons">
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="north" autocomplete="off">North
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="east" autocomplete="off" class="radio">East
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="central" autocomplete="off" class="radio">Central
</label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="south"autocomplete="off" class="radio">South </label>
<label class="btn btn-primary outline">
<input type="checkbox" name="filterStatus" value="west" autocomplete="off" class="radio">West
</label>
</div><!-- button group -->
<label class="btn btn-primary outline">
<input type="checkbox" name="impressStatus" class="radio" aria-pressed="true" autocomplete="off">Impress her
</label>
</div><!-- btn toolbar-->
<!--TABLE -->
<table class="table" id="StatusTable">
<thead>
<tr>
<th data-sort="string" style="cursor:pointer">name</th>
<!-- <th>Description</th> -->
<th data-sort="string" style="cursor:pointer;">postcode</th>
<th data-sort="int" style="cursor:pointer;">price</th>
<th data-sort="int" style="cursor:pointer;">total</th>
<th data-sort="int" style="cursor:pointer;">impress</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<tr data-link="/places/1">
<td>Name of place 1</td>
<td class="postcode">NW1</td>
<td class="price" data-price='3'>3</td>
<td class="rating" data-rating='69'>69</td>
<td class="impress" data-impress='4'>4</td>
</tr>
<tr data-link="/places/2">
<td>Name of place 2</td>
<td class="postcode">E3</td>
<td class="price" data-price='4'>4</span></td>
<td class="rating" data-rating='89'>89</td>
<td class="impress" data-impress='5'>5</td>
</tr>
<tr data-link="/places/3">
<td>Name of place 3</td>
<td class="postcode">SW3</td>
<td class="price" data-price='2'>2</td>
<td class="rating" data-rating='51'>51</td>
<td class="impress" data-impress='3'>3</td>
</tr>
</tbody>
</table>
Code is probably not the most efficient, but it works :). Once I got this working, I want to add more filters.
(sorry for my bad english)
if these are the only filters you need, you can use two different type of filter:
hide via Javascript
hide via Css
if you use 2 types of filters the filters can work correctly without use a complex javascript code to manage a big number of different cases and combination:
I add a initial (on document load) control that check if a tr has the value impress cell >4, if has it add a new class: is_impress else add an other: no_impress.
$('.table td.impress').each(function(){
var _class = ($(this).data("impress") >= 4) ? "is_impress" : "no_impress";
$(this).parent().addClass(_class);
});
The code of filter by position is the same... but... I edit the filter by impress to add a class to table () when is active and take it off when isn't:
$("input[name='impressStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_impress")
: $("#StatusTable").addClass("active_impress");
});
if the table has the class active_impress a css rules override the inline code of dispaly to hide all the row that haven't an impress >4:
#StatusTable.active_impress tr.no_impress{
display:none !important;
}
This type of filter override any other display modification until the checkbox stay checked.
I edit your fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/1/
USE CSS to more filter
First change on load check, add price:
$('.table tbody tr').each(function(){
var _class = "";
_class += ($(this).find(".price").data("price") >= 2) ? "is_price " : "no_price ";
_class += ($(this).find(".impress").data("impress") >= 4) ? "is_impress " : "no_impress ";
console.log(_class);
$(this).addClass(_class);
});
Add an other handler to new filter:
$("input[name='priceStatus']").change(function(){
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_price")
: $("#StatusTable").addClass("active_price");
});
add new selector to the css rule:
#StatusTable.active_impress tr.no_impress,
#StatusTable.active_price tr.no_price{
display:none !important;
}
This is the result:
https://jsfiddle.net/Frogmouth/gkba343L/3/
Optimize code to add more filter:
HTML filter button:
<label class="btn btn-primary outline">
<input type="checkbox" name="impress" class="cssFilter radio" aria-pressed="true" autocomplete="off">Impress her
</label>
use cssFilter to indicate that is a css filter button and use name attribute to define the name of the filter, than use this namespace into the css class:
.active_{name} .no_{name} .is_{name}
And use a generic handler:
$("input.cssFilter").change(function(){
var _name = $(this).attr("name");
console.log(_name);
(!$(this).is(":checked"))
? $("#StatusTable").removeClass("active_"+_name)
: $("#StatusTable").addClass("active_"+_name);
});
With this you can manage all the filter with an unique handler, remember to add the filter to onload check and the new selector for each new filter.
Fiddle:
https://jsfiddle.net/Frogmouth/gkba343L/4/