Datatable date range function - javascript

I have two datatables and I use four datepickers(datepicker,datepicker2,datepicker3,datepicker4). Two for each datatable. Actually it's working for one table but for the other it's not vice versa. Here is my code
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var mini = document.getElementById('datepicker').value;
var maxi = document.getElementById('datepicker2').value;
var mini2 = document.getElementById('datepicker3').value;
var maxi2 = document.getElementById('datepicker4').value;
if((mini !== '') && (maxi !== '')){
var taena = data[10]; // use data for the date column
var ifMin = mini.substring(0,2) + mini.substring(3,5) + mini.substring(6,10);
var ifMax = maxi.substring(0,2) + maxi.substring(3,5) + maxi.substring(6,10);
var ifTaena = taena.substring(0,2) + taena.substring(3,5) + taena.substring(6,10);
if ( ( ifMin === '' && ifMax === '' ) || ( ifMin === '' && ifTaena <= ifMax ) || ( ifMin <= ifTaena && ifMax === '' ) || ( ifMin <= ifTaena && ifTaena <= ifMax ) ){
return true;
}
return false;
}
if((mini2 !== '') && (maxi2 !== '')){
var taena2 = data[9]; // use data for the date column
console.log(taena2);
var ifMin2 = mini2.substring(0,2) + mini2.substring(3,5) + mini2.substring(6,10);
var ifMax2 = maxi2.substring(0,2) + maxi2.substring(3,5) + maxi2.substring(6,10);
var ifTaena2 = taena2.substring(0,2) + taena2.substring(3,5) + taena2.substring(6,10);
if ( ( ifMin2 === '' && ifMax2 === '' ) || ( ifMin2 === '' && ifTaena2 <= ifMax2 ) || ( ifMin2 <= ifTaena2 && ifMax2 === '' ) || ( ifMin2 <= ifTaena2 && ifTaena2 <= ifMax2 ) ){
return true;
}
return false;
}
return false;
}
);
I hope you guys could help me

Related

Making a date mask react with javascript: If i press simultaneous numbers i lost the mask

I'm trying to make a mask react date dd/mm/yyyy to a custom date input.
If i press the keys slow, the mask is setted correct dd/mm/yyyy, but supposing i press the numbers rapid, my mask is breaking
This is my component:
<DateInput
name="date"
placeholder="Data"
value={this.props.data}
dateFormat="DD/MM/YYYY"
onChange={this.props.changeDataTarefa}
animation="none"
onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>
this is my functions:
fixDatePattern(currDate) {
var currentDate = currDate;
if (currentDate){
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
}
if (!this.isNumber(lastNumberEntered) && currentDate) {
return currentDate.substring(0, currentLength - 1);
}
if (currentLength > 10) {
return currentDate.substring(0, 10);
}
let dateCountTracker = 0
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 4 && currentDate[3] > 3) {
let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
return currentDate + '/';
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
return currentDate + '/';
}
dateCountTracker = currentLength;
return currentDate;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Instead of using keyup, use keypress event on input. And you could also use react input mask plugin for same.
You can use below code for key press event and please check working stackblitz demo.
render() {
return (
<div>
<span>Date : </span>
<input type="text" maxLength="10" placeHolder="dd/mm/yyyy" onKeyPress={this.onKeyPress}/>
</div>
)
}
onKeyPress(e){
let input = e.target;
if(e.charCode < 47 || e.charCode > 57) {
e.preventDefault();
}
var len = input.value.length;
if(len !== 1 || len !== 3) {
if(e.charCode == 47) {
e.preventDefault();
}
}
if(len === 2) {
input.value += '/';
}
if(len === 5) {
input.value += '/';
}
}
You could use below react input mask plugins to achieve requirement.
imaskjs and react-input-mask

Angularjs tiny display bug with ng-if

I have a small bug with my display logic. User selects job length as step 1 then clicks on a cell to determine availability. Everything works but I need Selected to show up on the other cells. I think some sort of boolean I have to attach i'm not sure. Assume for now jobLength=3 (this comes anyway from the HTML5 custom slider not displayed below but is just above the table as Step 1).How do I get Selected to show up.
Here's the code.
<tbody>
<tr ng-repeat="hour in workhours" ng-init="selectedIndex=$index">
<td>{{hour}}:00 - {{hour+1}}:00</td>
<td class="hidden-xs" ng-class = "{ 'full' : !entry.HoursAvailable.includes(hour),
'selected' : renderGreen(selectedIndex, $index, jobLength)}"
ng-click = "checkSlotAvailability(hour, jobLength, entry, data)"
ng-repeat= "entry in data.calendar">
<!-- /* ============ -->
<!-- Display Logic -->
<!-- =============== -->
<span ng-if="entry.HoursAvailable.includes(hour)
&& !renderGreen(selectedIndex, $index, jobLength)
&& !(selectedIndex == selectedRow
&& $index == selectedColumn)">
Available
</span>
<span ng-if="entry.HoursAvailable.includes(hour)
&& renderGreen(selectedIndex, $index, jobLength)
&& $index == selectedColumn
&& selectedIndex == selectedRow
<!-- I added this check slot f(x) to render table dynamically when user adjusts job length -->
&& checkSlotAvailability(hour, jobLength, entry, data)">
Selected
</span>
<span ng-if="entry.HoursAvailable.includes(hour)
&& !renderGreen(selectedIndex, $index, jobLength)
&& selectedIndex == selectedRow
&& $index == selectedColumn">
Unavailable
</span>
<span ng-if="!entry.HoursAvailable.includes(hour)">
Full
</span>
</td>
</tr>
</tbody>
controller
(function() {
"use strict";
angular
.module("availability")
.controller("availabilityController", function($scope, $http){
$scope.data = {};
$scope.data.response = "Available";
$scope.workhours = Array.from({length:9}).map((_, i)=> i + 9); // creating all possible working hours in a day (9-17)
$http.get('../api/availability.json')
.then( function(response){
$scope.data.calendar = response.data;
});
function setBuffer(date){
var today = formatDateToString(new Date('2016-05-18T11:27:00'));
var bufferTime = 1;
if(date == today){
bufferTime = 2;
}
return bufferTime;
}
function formatDateToString(date){
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
var yyyy = date.getFullYear();
return (yyyy + "-" + MM + "-" + dd);
}
function getRowAndColumn(row, column){
$scope.selectedRow = row;
$scope.selectedColumn = column;
}
$scope.renderGreen = function(selectedIndex, $index, jobLength){
if( $index == $scope.selectedColumn
&& selectedIndex >= $scope.selectedRow
&& selectedIndex <= ($scope.selectedRow + jobLength - 1) && $scope.data.response == "Available")
return true;
else
return false;
}
/* ===========================
Check Availabiliy function
============================== */
$scope.checkSlotAvailability = function(time, jobLength, date, availability) {
var date = date.Date;
var calendar = availability.calendar;
var response = "";
var buffer = setBuffer(date);
var selectedIndex = time - 9;
if( jobLength < 1 || jobLength > 5 ){
alert("Please enter job length from 1 to 5");
response = "Available";
}else {
for( var i = 0; i < calendar.length; i++ ){
getRowAndColumn(selectedIndex, i);
if( date == calendar[i].Date ){
if( time < 9 || time > 17 ){ // Can't book before 9am or after 5pm. Code should never reach here.
response = "Unavailable";
break;
}else {
for( var j = 0; j < calendar[i].HoursAvailable.length; j++){
if( time == calendar[i].HoursAvailable[j]){
if( ( time == 9 || time == 17 ) && calendar[i].HoursAvailable[j]
|| time - buffer < 9
|| time == calendar[i].HoursAvailable[j]
&& time - buffer == calendar[i].HoursAvailable[j - buffer]
&& time + buffer == calendar[i].HoursAvailable[j + buffer] ){
for( var k = j; k < calendar[i].HoursAvailable.length; k++ ){
if( time >= 13 && time == calendar[i].HoursAvailable[k] && time + jobLength <= 18
&& time - buffer == calendar[i].HoursAvailable[k - buffer] //5pm
|| (time + jobLength + (buffer - 1)) == calendar[i].HoursAvailable[k + jobLength + (buffer - 1)]
&& time - buffer == calendar[i].HoursAvailable[k - buffer]
|| (time + jobLength + (buffer - 1)) == calendar[i].HoursAvailable[k + jobLength + (buffer - 1)] ){ //9am
response = "Available";
break;
}else if( k == calendar[i].HoursAvailable.length - 1 ){
response = "Unavailable";
}
}
break;
}else{
response = "Unavailable";
break;
}
}else if( j == calendar[i].HoursAvailable.length - 1 ){ //no available slot
response = "Full";
}
}
break;
}
}else if( i == calendar.length - 1 ){ //no available date
response = "Full";
break;
}
}
}
$scope.data.response = response;
return response;
};
});
})();

Make result letters bold as I type in searchbox

I am using Opencart v2.2.0. Search box is autocomplete and that part is alright. But now I need to make letters bold as I type in the search box.
Example:
The user starts typing "some", and as he types, the results are:
something
awesome
etc.
NOTICE: The words "something" and "awesome" are just an example, in real time I do not know what search terms would user type in.
So far I have this code, but as I am not really a js/jquery expert, I need help implementing the upper request. Thank you all.
//<![CDATA[
function doLiveSearch( ev, keywords ) {
if( ev.keyCode == 38 || ev.keyCode == 40 ) {
return false;
}
$('#autosearch_search_results').remove();
updown = -1;
if( keywords == '' || keywords.length < 2 ) {
return false;
}
keywords = encodeURI(keywords);
$.ajax({url: $('base').attr('href') + 'index.php?route=module/autosearch/ajax_asr&keyword=' + keywords, dataType: 'json', success: function(result) {
if( result.length > 0 ) {
var eList = document.createElement('ul');
eList.id = 'autosearch_search_results';
var eListElem;
var eLink;
var eImage;
for( var i in result ) {
eListElem = document.createElement('li');
eLink = document.createElement('a');
if( (result[i].thumb) != '' )
{
eImage = document.createElement('img');
eImage.src = result[i].thumb;
eLink.appendChild(eImage);
}
// name
var el_span = document.createElement('name');
var textNode = document.createTextNode(result[i].name);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
// model
if( (result[i].model) != '' )
{
var el_span = document.createElement('model');
var textNode = document.createTextNode(result[i].model);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
if( typeof(result[i].href) != 'undefined' ) {
eLink.href = result[i].href;
}
else {
eLink.href = $('base').attr('href') + 'index.php?route=product/product&product_id=' + result[i].product_id + '&keyword=' + keywords;
}
eListElem.appendChild(eLink);
if( (result[i].price) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
// special price
if( (result[i].special) != '' )
{
var el_span = document.createElement('special-price');
var textNode = document.createTextNode(result[i].special);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// price
var el_span = document.createElement('price');
var textNode = document.createTextNode(result[i].price);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
}
// quantity/stock
if( (result[i].stock) != '' )
{
var br = document.createElement("br");
eLink.appendChild(br);
eLink.appendChild( document.createTextNode(result[i].stock) );
}
eList.appendChild(eListElem);
}
if( $('#autosearch_search_results').length > 0 ) {
$('#autosearch_search_results').remove();
}
//view all results
if( (result[i].viewall) != '' )
{
eListElem = document.createElement('li');
eLink = document.createElement('a');
var el_span = document.createElement('viewall');
var textNode = document.createTextNode(result[i].viewall);
eLink.appendChild(el_span);
el_span.appendChild(textNode);
eLink.href = $('base').attr('href') + 'index.php?route=product/search&search=' + keywords;
eListElem.appendChild(eLink);
eList.appendChild(eListElem);
}
$('#search').append(eList);
}
}});
return true;
}
function upDownEvent( ev ) {
var elem = document.getElementById('autosearch_search_results');
var fkey = $('#search').find('[name=search]').first();
if( elem ) {
var length = elem.childNodes.length - 1;
if( updown != -1 && typeof(elem.childNodes[updown]) != 'undefined' ) {
$(elem.childNodes[updown]).removeClass('highlighted');
}
// Up
if( ev.keyCode == 38 ) {
updown = ( updown > 0 ) ? --updown : updown;
}
else if( ev.keyCode == 40 ) {
updown = ( updown < length ) ? ++updown : updown;
}
if( updown >= 0 && updown <= length ) {
$(elem.childNodes[updown]).addClass('highlighted');
var text = elem.childNodes[updown].childNodes[0].text;
if( typeof(text) == 'undefined' ) {
text = elem.childNodes[updown].childNodes[0].innerText;
}
}
}
return false;
}
var updown = -1;
$(document).ready(function(){
$('#search').find('[name=search]').attr('autocomplete', 'off'); //disable autocomplete
$('#search').find('[name=search]').first().keyup(function(ev){
doLiveSearch(ev, this.value);
}).focus(function(ev){
doLiveSearch(ev, this.value);
}).keydown(function(ev){
upDownEvent( ev );
}).blur(function(){
window.setTimeout("$('#autosearch_search_results').remove();updown=0;", 1500);
});
$(document).bind('keydown', function(ev) {
try {
if( ev.keyCode == 13 && $('.highlighted').length > 0 ) {
document.location.href = $('.highlighted').find('a').first().attr('href');
}
}
catch(e) {}
});
});
//]]>
just add a function that highlights all the searched text end run it on every text you add to your html:
function highlightQuery(string,searchQuery){
if(!string){
return "";
}
var expr = searchQuery;
expr = expr.replace(/\s+/, "|",searchQuery);
var regex = new RegExp(expr,"gi");
return string.replace(regex, function($1){
return '<span class="highlight">'+ $1 +'</span>';
});
}
We are trying to do the formatting part at javascript
so that only display should be done at HTML part
Execute the below function on typeahead ,and then you just need to display
the resultant array( formattedResult ) in HTML.
formattedResult will contain the formatted text.
While displaying formattedResult array in HTML , put 2nd position text
in bold of each iterated item.
Please try following code:-
//argument types searchList(Array) and searchWord(String)
function formatResult(searchList, searchWord ){
var formattedResult = [[]];
for(var prop in searchList){
if(searchList[prop].indexOf("some")!=-1)
{
var index= searchList[prop].indexOf(searchWord );
var temp = [];
temp.push(searchList[prop].substring(0,index));
temp.push(searchWord.toUpperCase());
temp.push(searchList[prop].substring(index + searchWord.length,
searchList[prop].length));
//console.log(temp);
formattedResult.push(temp);
}
else{
formattedResult.push(searchList[prop])
}
}
return formattedResult;
}

How to fix and work with tree toc?(old syntax)

so i bought a site witch is connected to a gestional programm in office..
the site is a little old, it's fully compatible with all the versions of internet explorer but not with other browsers(opera,safari,chrome,firefox...)
the only piece not working is a menu not opening correctly, when you click on it it doesn't happen anything or in chrome it changes the image but it doesn't upload the links. it seems that it doens't upload things in the hiddenframe...
in chrome it gives error in loadchildren function.
in firefox it gives error in function Toc_click ()
TypeError: window.event is undefined
[Break On This Error]
var eSrc = window.event.srcElement;
we searched for the problem and we think that the problem should be in this file
the problem should be a syntax problem, it's compatible in old browsers but not on the new ones. i cannot change completely the code as it is connected with other files(a lot) and sql server...
we already tried to change
document.frames["hiddenframe"].location.replace(strLoc);
by
document.getElementsByName("hiddenframe").location.replace(strLoc);
it doens't work and it doesn't work on IE either...
/* TOC.JS */
var framesTop = parent.parent;
//var L_LoadingMsg_HTMLText = "Loading, click to cancel...";
var LoadDiv = '<DIV ONCLICK="loadFrame(true);" CLASS="clsLoadMsg">';
L_LoadingMsg_HTMLText = LoadDiv + L_LoadingMsg_HTMLText + "</LI>";
function caps(){
var UA = navigator.userAgent;
if(UA.indexOf("MSIE") != -1)
{
this.ie = true;
this.v = UA.charAt(UA.indexOf("MSIE") + 5);
if( this.v == 2 ) this.ie2 = true;
else if( this.v == 3 ) this.ie3 = true;
else if( this.v == 4 ) this.ie4 = true;
else if( this.v == 5 ) this.ie5 = true;
else if( this.v == 6 ) this.ie6 = true;
else this.ie6 = true;
}
else if(UA.indexOf("Mozilla") != -1 && UA.indexOf("compatible") == -1)
{
this.nav = true;
var v = UA.charAt(UA.indexOf("Mozilla") + 8);
if(v == 2 ) this.nav2 = true;
else if(v == 3 ) this.nav3 = true;
else if(v == 4 ) this.nav4 = true;
}
if(UA.indexOf("Windows 95") != -1 || UA.indexOf("Win95") != -1 || UA.indexOf("Win98") != -1 || UA.indexOf("Windows 98") != -1 || UA.indexOf("Windows NT") != -1 || UA.indexOf("Windows XP") != -1) this.win32 = true;
else if(UA.indexOf("Windows 3.1") != -1 || UA.indexOf("Win16") != -1) this.win16 = true;
else if(UA.indexOf("Mac") != -1) this.anymac = true;
else if(UA.indexOf("SunOS") != -1 || UA.indexOf("HP-UX") != -1 || UA.indexOf("X11") != -1) this.unix = true;
else if(UA.indexOf("Windows CE") != -1) this.wince = true;
}
var bc = new caps();
////////////////////////////////////////////
// Not sure why this is here, it puts a scrollbar up when none is needed
// if("object" == typeof(parent.document.all.fraPaneToc)) parent.document.all.fraPaneToc.scrolling = "yes";
////////////////////////////////////////////
var eSynchedNode = null;
var eCurrentUL = null;
var eCurrentLI = null;
var bLoading = false;
function loadFrame( bStopLoad )
{
if( "object" == typeof( eCurrentUL ) && eCurrentUL && !bStopLoad )
{
eCurrentUL.innerHTML = hiddenframe.chunk.innerHTML;
eCurrentUL = null;
bLoading = false;
}
else if( "object" == typeof( eCurrentUL ) && eCurrentUL )
{
eCurrentUL.parentElement.children[1].className = "";
eCurrentUL.parentElement.children[0].src = "bs.gif";
eCurrentUL.parentElement.className = "kid";
eCurrentUL.className = "clsHidden";
eCurrentUL.innerHTML="";
eCurrentUL = null;
bLoading = false;
}
else
{
bLoading = false;
}
return;
}
function GetNextUL(eSrc)
{
var eRef = eSrc;
for(var i = eRef.sourceIndex + 1; i < document.all.length; i++)
{
if( "UL" == document.all[ i ].tagName )
{
return document.all[ i ];
}
else if( "LI" == document.all[ i ].tagName )
{
break;
}
}
return false;
}
function MarkSync(eSrc)
{
if("object" == typeof(aNodeTree)) aNodeTree = null;
if("LI" == eSrc.tagName.toUpperCase() && eSrc.children[1] && eSynchedNode != eSrc )
{
UnmarkSync();
eSrc.children[1].style.fontWeight = "bold";
eSynchedNode = eSrc;
}
}
function UnmarkSync()
{
if("object" == typeof(eSynchedNode) && eSynchedNode )
{
eSynchedNode.children[1].style.fontWeight = "normal";
eSynchedNode = null;
}
}
function MarkActive(eLI)
{
if( "object" == typeof( eLI ) && eLI && "LI" == eLI.tagName.toUpperCase() && eLI.children[1] && eLI != eCurrentLI )
{
MarkInActive();
window.eCurrentLI = eLI;
window.eCurrentLI.children[1].className = "clsCurrentLI";
}
}
function MarkInActive()
{
if( "object" == typeof( eCurrentLI ) && eCurrentLI )
{
window.eCurrentLI.children[1].className = "";
window.eCurrentLI = null;
}
}
function LoadChildren( eLink )
{
var strLoc = "loadtree.asp" + eLink.href.substring( eLink.href.indexOf( "?" ) );
document.frames["hiddenframe"].location.replace(strLoc);
}
function Navigate_URL( eSrc )
{
var eLink = eSrc.parentElement.children[1];
urlIdx = eLink.href.indexOf( "URL=" );
if("object" == typeof(framesTop.fraTopic) && eLink && "A" == eLink.tagName && urlIdx != -1 )
{
if(eLink.target=="fraTopic"||eLink.target=="_top"){
framesTop.fraTopic.location.href = eSrc.parentElement.children[1].href.substring( urlIdx + 4 );
}else{
window.open(eSrc.parentElement.children[1].href,eLink.target);
}
MarkSync(eSrc.parentElement);
}
else if("object" == typeof(framesTop.fraTopic) && eLink && "A" == eLink.tagName && eLink.href.indexOf( "tocPath=" ) == -1 && eLink.href.indexOf( "javascript:" ) == -1 )
{
if(eLink.target=="fraTopic")
{
framesTop.fraTopic.location.href = eSrc.parentElement.children[1].href;
}
else if( eLink.target=="_top" )
{
top.location = eLink.href;
return;
}
else
{
window.open(eSrc.parentElement.children[1].href,eLink.target);
}
MarkSync(eSrc.parentElement);
}
else if( eSynchedNode != eSrc.parentElement && ( urlIdx != -1 || ( eLink.href.indexOf( "javascript:" ) == -1 && eLink.href.indexOf( "tocPath=" ) == -1 ) ) )
{
// START D.S.
if(eLink.target=="fraTopic")
{
if (navigator.userAgent.indexOf("Windows") == -1) {
var MyHref = eSrc.parentElement.children[1].href;
do
{
if (MyHref.indexOf("%2E") != -1) MyHref = MyHref.replace("%2E", ".");
else if (MyHref.indexOf("%2F") != -1) MyHref = MyHref.replace("%2F", "/");
else if (MyHref.indexOf("%3F") != -1) MyHref = MyHref.replace("%3F", "?");
else if (MyHref.indexOf("%3D") != -1) MyHref = MyHref.replace("%3D", "=");
else if (MyHref.indexOf("%26") != -1) MyHref = MyHref.replace("%26", "&");
else break;
}
while (true);
parent.fraTopic.location.href = MyHref;
} else {
parent.fraTopic.location.href = eSrc.parentElement.children[1].href;
}
}
// END D.S.
MarkSync( eSrc.parentElement );
}
}
function Image_Click( eSrc , bLeaveOpen )
{
var eLink = eSrc.parentElement.children[1];
if("noHand" != eSrc.className)
{
eLI = eSrc.parentElement;
MarkActive(eLI);
var eUL = GetNextUL(eLI);
if(eUL && "kidShown" == eLI.className)
{
// hide on-page kids
if( !bLeaveOpen )
{
eLI.className = "kid";
eUL.className = "clsHidden";
eSrc.src = "bs.gif";
}
}
else if(eUL && eUL.all.length)
{
// show on-page kids
eLI.className = "kidShown";
eUL.className = "clsShown";
eSrc.src = "bo.gif";
}
else if("kid" == eLI.className)
{
// load off-page kids
if( !bLoading )
{
bLoading = true;
eLI.className = "kidShown";
eUL.className = "clsShown";
window.eCurrentUL = eUL;
eSrc.src = "bo.gif";
eUL.innerHTML = L_LoadingMsg_HTMLText;
LoadChildren( eLink );
}
}
}
}
function Toc_click ()
{
var eSrc = window.event.srcElement;
event.returnValue = false;
if("A" == eSrc.tagName.toUpperCase() && "LI" == eSrc.parentElement.tagName)
{
var eImg = eSrc.parentElement.children[0];
if(eImg) eImg_click(eImg);
}
else if("SPAN" == eSrc.tagName && "LI" == eSrc.parentElement.tagName)
{
var eImg = eSrc.parentElement.children[0];
if(eImg) eImg_click(eImg);
}
else if("IMG" == eSrc.tagName)
{
}
return event.returnValue;
}
function eImg_click(eImg)
{
if("IMG" == eImg.tagName)
{
Image_Click( eImg , false );
Navigate_URL( eImg );
}
}
function Toc_dblclick()
{
return;
}
function window_load()
{
if( self == top ) location.replace( "default.asp" );
var objStyle = null;
if( bc.win32 && ( bc.ie4 || bc.ie5 || bc.ie6 ) && "object" == typeof ( ulRoot ) && "object" == typeof( objStyle = document.styleSheets[0] ) && "object" == typeof( objStyle.addRule ) )
{
window.eSynchedNode = document.all["eSynchedNode"];
objStyle.addRule( "UL.clsHidden" , "display:none" , 0 );
objStyle.addRule( "UL.hdn" , "display:none" , 0 );
//--ulRoot.onclick=Toc_click;
ulRoot.ondblclick=Toc_dblclick;
if( window.eSynchedNode )
{
MarkActive(window.eSynchedNode);
window.eSynchedNode.all.tags( "B" )[0].outerHTML = eSynchedNode.all.tags("B")[0].innerHTML;
window.scrollTo(0,window.eSynchedNode.offsetTop-(document.body.clientHeight/2));
}
else
{
MarkActive(document.all.tags( "LI" )[0]);
}
}
}
window.onload = window_load;
suggestions?

Correct a function to declare a winner as soon as possible

I'm making a tic-tac-toe game.
How would I change the following code so that the winner could be declared before complete is true, (every square filled) and the winner is the first to achieve 3 matching values, not the last to achieve it?
function check_squares () {
var values = new Array();
var complete = true;
$('.square').each(function () {
values.push( $(this).html() );
//if ($(this).html() == '') complete = false;
});
if (complete == true) {
var winner = false;
if ( values[0] == values[1] && values[1] == values[2] ) winner = values[0];
if ( values[3] == values[4] && values[4] == values[5] ) winner = values[3];
if ( values[6] == values[7] && values[7] == values[8] ) winner = values[6];
if ( values[0] == values[3] && values[3] == values[6] ) winner = values[0];
if ( values[1] == values[4] && values[4] == values[7] ) winner = values[1];
if ( values[2] == values[5] && values[5] == values[8] ) winner = values[2];
if ( values[0] == values[4] && values[4] == values[8] ) winner = values[0];
if ( values[2] == values[4] && values[4] == values[6] ) winner = values[2];
if (winner) {
$('#output').html('Winner: ' + winner);
} else {
$('#output').html('No Winner');
}
} else {
if (player_x == true) {
$('#output').html('x turn to move');
} else {
$('#output').html('o turn to move');
}
}
}
Your function is almost correct. Mainly, you just need to call it each time that a player changes a cell's value.
I have tweaked your function a little bit to allow it to be called multiple times. I have added comments to the sections that I changed to make them easier to find.
// Move these two variables into the global scope so that they are not reset
// by each call to check_squares and so that our click function can access them.
var complete = false;
var winner = null;
function check_squares () {
var values = new Array();
$('.square').each(function () {
values.push( $(this).html() );
//if ($(this).html() == '') complete = false;
});
// Debug statement to see the order of the values.
console.log(values);
if (!complete) {
if ( values[0] == values[1] && values[1] == values[2] ) winner = values[0];
if ( values[3] == values[4] && values[4] == values[5] ) winner = values[3];
if ( values[6] == values[7] && values[7] == values[8] ) winner = values[6];
if ( values[0] == values[3] && values[3] == values[6] ) winner = values[0];
if ( values[1] == values[4] && values[4] == values[7] ) winner = values[1];
if ( values[2] == values[5] && values[5] == values[8] ) winner = values[2];
if ( values[0] == values[4] && values[4] == values[8] ) winner = values[0];
if ( values[2] == values[4] && values[4] == values[6] ) winner = values[2];
if (winner) {
$('#output').html('Winner: ' + winner);
// Indicate that there was a winner so no more input is allowed.
complete = true;
} else {
$('#output').html('No Winner');
}
} else {
if (player_x == true) {
$('#output').html('x turn to move');
} else {
$('#output').html('o turn to move');
}
}
}
// Add a click handler to each square that checks for win conditions after each
// X or 0 is added.
$(".square").click(function() {
if (!complete)
{
// This obviously needs to be changed to determine which player is going.
$(this).html("X");
check_squares();
}
});
I have created a simple JSFiddle to see a working example.

Categories

Resources