How to fix issue with .select() not working - javascript

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

Related

How I get values updating/refreshing related input areas in Javascript?

I have a form and when I press the Try button it returns values for the 3rd and 6th input fields of the form according to the values entered in 1,2 and 5.6. Also, the 7th input field combines the 3rd and 6th results.
My question is how can I get the result values from input fields 3 and 6 without clicking the Try It button and also update the input field 7 without refreshing the page?
My code is in JSFiddle UPDATED !!
My Javascript are:
<script type="text/javascript">
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
function join_names() {
var input_name_first = document.getElementsByName('ht')[0].value;
var input_name_last = document.getElementsByName('ft')[0].value;
var input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(input_name_first, input_name_last, true);
input_name_full.value = var_name_full;
}
</script>
<script type="text/javascript">
function myFunctionFt() {
var home = document.getElementById("home_score").value;
var away = document.getElementById("away_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ft").value = results;
}
</script>
<script type="text/javascript">
function myFunctionHt() {
var home = document.getElementById("home_ht_score").value;
var away = document.getElementById("away_ht_score").value;
var results;
if (home > away) {
results = "1";
} else if (home < away) {
results = "2";
} else if (home = away) {
results = "X";
}
document.getElementById("ht").value = results;
}
</script>
I have removed all the previous answers from this answer and added a new answer in place. I have read your last comment and you said that my code was not working for the Home Team HT Score and Away Team HT Score. Well, I had made the logic to behave this way because it makes more sense to put the result in HT Result once both of the teams have played or in other words when we have both of the inputs. In sports, it rarely happens that only one team plays. Right. So outputting the result in HT result based on one of the inputs makes no sense. But if this is what you want, you simply have to change the logic from if (!input_home || !input_away) return; to if (!input_home && !input_away) return; and it will start working the way you want. Basically in the first logic statement with "||" we are saying unless both of the inputs are available don't out into HT result and in the second statement with && we are saying id doesn't matter if one of them is not present, just take whatever is present and output it in HT result. The same thing is happening for FT. You just have to change || to &&.
Here is the final working code:
//FT and HT Result//
let name_first = document.getElementById('ht');
let name_last = document.getElementById('ft');
let input_name_first = name_first.value;
let input_name_last = name_last.value;
//HT Home//
let home = document.getElementById("home_ht_score");
let away = document.getElementById("away_ht_score");
home_ht_score.addEventListener("input", myFunctionHt);
away_ht_score.addEventListener("input", myFunctionHt);
let input_away = away.value;
let input_home = home.value;
//FT Home//
let home_ft = document.getElementById("home_score");
let away_ft = document.getElementById("away_score");
home_score.addEventListener("input", myFunctionFt);
away_score.addEventListener("input", myFunctionFt);
let input_ft_away = away_ft.value;
let input_ft_home = home_ft.value;
function myFunctionHt() {
input_away = away.value;
input_home = home.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_home && !input_away) return;
var results = "";
if (input_home > input_away) {
results = "1";
} else if (input_home < input_away) {
results = "2";
} else if (input_home = input_away) {
results = "X";
}
document.getElementById("ht").value = results;
join_names();
}
function myFunctionFt() {
input_ft_away = away_ft.value;
input_ft_home = home_ft.value;
input_name_first = name_first.value;
input_name_last = name_last.value;
if (!input_ft_home && !input_ft_away) return;
var results = "";
if (input_ft_home > input_ft_away) {
results = "1";
} else if (input_ft_home < input_ft_away) {
results = "2";
} else if (input_ft_home = input_ft_away) {
results = "X";
}
document.getElementById("ft").value = results;
join_names();
}
function join_names() {
if (!input_name_first && !input_name_last) return;
let input_name_full = document.getElementsByName('htft')[0];
var var_name_full = concatenate(name_first.value, name_last.value, true);
input_name_full.value = var_name_full;
}
function concatenate(/*String*/string_one, /*String*/string_two, /*boolean*/with_space) {
if (with_space===true) {
return string_one+'/'+string_two;
}
else {
return string_one+string_two;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form class="form-group" action="addemp" method="post" onsubmit="return true" onClick="return false">
<table border="0" cellpadding="1">
<tbody>
<tr>
<td> <label class="form-label" style="color:blue" for="name">Home Team HT Score</label> </td>
<td> <input id="home_ht_score" name="home_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:red" for="name">Away Team HT Score</label> </td>
<td> <input id="away_ht_score" name="away_ht_score" type="text" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT Result</label> </td>
<td> <input id="ht" name="ht" type="text" class="form-control mb-3" oninput="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:blue" for="name">Home FT Score</label> </td>
<td> <input id="home_score" name="home_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:red" for="name">Away FT Score</label> </td>
<td> <input id="away_score" name="away_score" type="number" class="form-control mb-3" style="width: 200px;"></td>
</tr>
<tr>
<td> <label class="form-label" style="color:green" for="name">FT Result</label> </td>
<td> <input id="ft" name="ft" type="text" class="form-control mb-3" onchange="join_names();" onpaste="join_names();" style="width: 200px;"></td>
</tr>
<tr>
<td><label class="form-label" style="color:green" for="name">HT/FT</label> </td>
<td> <input name="htft" type="text" class="form-control mb-3" style="width: 200px;"> </td>
</tr>
<tr>
<td> </td>
<td><button class="btn btn-primary mb-4" type="submit">Save Match Result</button> </td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

How to fix counter not showing correct value as well as resetting with new string

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.

jQuery validate input fields in table cells

I'm trying to validate inputs in a table.
I have a table with rows and in their inputs. If some of the input is not empty, We need to check whether the adjacent input has value, if not return false. If both are empty true.
I made a little demo of what I want to do.
https://jsfiddle.net/51bz8ggv/2/
$(document).ready(function() {
$("table tr :input").each(function () {
console.log(this.value);
// some check here
});
});
Thanks.
https://jsfiddle.net/51bz8ggv/3/
$(document).ready(function() {
$("table td:nth-child(1) :input").each(function(index) {
var rowDate = $(this).val()
var rowPoints = $("table td:nth-child(2) :input").eq(index).val()
if (rowDate === "" && rowPoints === "") {
//both are empty
console.log(index + " : true")
} else if (rowDate !== "" && rowPoints !== "") {
//both have values
console.log(index + " : true")
} else {
//one is empty and the other have value
console.log(index + " : false")
}
});
});
I'm using nth-child(1) to loop through the first column than compare the value with the input in nth-child(2) aka the 2nd column. so if you work with different table be sure to adjust these numbers to fit the columns you're comparing
Iterate over the tr and compare the total input element with empty input field count.
// get all tr except the first and iterate over them
$("table tr:nth-child(n+2)").each(function() {
// get all input fields within it
var $inp = $(':input', this);
// filter out all empty input fields
var $fil = $inp.filter(function() {
return $(this).val().trim() == '';
});
// now check all are non-empty or all are empty
console.log($fil.length == 0 || $fil.length == $inp.length);
});
$("table tr:nth-child(n+2)").each(function() {
var $inp = $(':input', this);
var $fil = $inp.filter(function() {
return $(this).val().trim() == '';
});
console.log($fil.length == 0 || $fil.length == $inp.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%" border="1">
<tr>
<th>Date</th>
<th>Points</th>
<th>Result</th>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" value="2016-09-02" />
</td>
<td>
<input type="text" name="points[]" class="points" />
</td>
<td>false(error)</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" />
</td>
<td>
<input type="text" name="points[]" class="points" value="679" />
</td>
<td>false(error)</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" value="2016-09-02" />
</td>
<td>
<input type="text" name="points[]" class="points" value="679" />
</td>
<td>true</td>
</tr>
<tr>
<td>
<input type="text" name="date[]" class="date" />
</td>
<td>
<input type="text" name="points[]" class="points" />
</td>
<td>true</td>
</tr>
</table>
This could be helpful.
$(document).ready(function() {
$("table tr").each(function () {
$inputarray = $(this).find("input");
$length = $inputarray.size();
if($length>0){
$i = 0;
$inputarray.each(function() {
if(this.value!=="") {
$i++;
}
});
if($i===0 || $i===$length){
$(this).find( "td:last" ).text("true");
} else {
$(this).find( "td:last" ).text("false");
}
}
});
});
Your updated Fiddle
Try this code:
$(document).ready(function() {
$(".date").each(function () {
var $that = $(this);
var $currentRow = $that.parents("tr");
var $points = $currentRow.find(".points");
console.log($that.val() )
console.log($points.val() )
var $currentROw = $currentRow.find("td:last-child").text(($that.val() == "" && $points.val() == "") || ($that.val() != "" && $points.val() != ""));
});
});
https://jsfiddle.net/oa42nzr0/

How to ensure that multiple setinterval functions are not intefering

I have created two calculators on a page, the second one calculates properly, however the first one does not. I believe that this is due to my two setinterval functions interfering. How do I get both of these functions to work in conjunction.
var x = document.getElementById("x");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
setInterval(function() {
if (x == document.activeElement) {
var temp = x.value;
if (xstored != temp) {
xstored = temp;
x.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
d.innerHTML = x.value * .62;
}
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var c = document.getElementById("c")
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 50);
function calculate() {
b.innerHTML = a.value * .62;
c.innerHTML = Math.round(a.value * .0103);
}
function tisNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<table style="width:100%;text-align: center;">
<tbody>
<tr>
<td style="width:50%;background:none;">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Lawn Square Footage</p>
</td>
<td style="width:50%;font-size: 35px;font-weight: bold;background:none">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Water Usage</p>
</td>
</tr>
<tr>
<td style="width:50%;">
<input id="x" onkeypress="return isNumberKey(event)" data-in="" type="text" style="height: 250px;margin-top: 10px;width: 250px;text-align: center;font-size: 100px" />
</td>
<td style="width:50%;font-size: 100px;"><span id="d" class="counter"></span>
</td>
</tr>
</tbody>
</table>
<table style="width:100%;text-align: center;">
<tbody>
<tr>
<td style="width:33%;background:none;">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Lawn Square Footage</p>
</td>
<td style="width:33%;font-size: 35px;font-weight: bold;background:none">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Water Usage</p>
</td>
</tr>
<tr>
<td style="width:33%;">
<input id="a" onkeypress="return tisNumberKey(event)" data-in="" type="text" style="height: 250px;margin-top: 10px;width: 250px;text-align: center;font-size: 100px" />
</td>
<td style="width:33%;font-size: 100px;"><span id="b" class="counter"></span>
</td>
<td style="width:33%;">
<p style="font-size:50px; font-weight:bold;">Your lawn takes a <span id="c"></span> hour shower
</td>
</tr>
</tbody>
</table>
http://codepen.io/anon/pen/qdyPjE
You can't have 2 functions with the same name/signature. You have calculate() twice you should name one different like calculate1(). You are overriding the first calculate() function with the second one that is why the second one works but the first one doesn't...
Multiple setInterval functions will never interfere with one another, your script runs on a single thread. The functions are queued and will execute one after the other. You don't need to worry about two different functions trying same data at the same time.
Your actual problem appears to be that you have two functions with same name, as pointed out already in another answer.

checked in checkbox, auto update in checkbox

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);
}

Categories

Resources