Jump to content

Variable scope


Xtremer360

Recommended Posts

On this i'm getting the following errors and I'm sure the majority of it is because of variable scope. TitlesDefended is not defined, Competitors is not defined, StipulationsAdded is not defined. Plus I'm not quote sure what I should put for my foreach loop that (... as ....) part.

 

<?php require ('php/bookings.php'); ?>

<script type="text/javascript">
function Competitors(matchNum) {
        
    function isDupe(which) {
        var result = false;
        $('ul#competitors'+ matchNum +' li').each(function(i, e) {
            if ($(e).attr('characterID') == which) {
                result = true;
                return false; // break out of .each()
            }
        });
        return result;
    }
    
    var characterID = $('#charactersDrop'+ matchNum +' option:selected').val();
    var characterName = $('#charactersDrop'+ matchNum +' option:selected').text();
    
    if (characterID > 0 && !isDupe(characterID)) {
        // Create the anchor element
        var anchor = $( '<a href="#">Remove</a>' );  
        
        // Create a click handler for the anchor element
        anchor.click( function() {
            $( this ).parent().remove();
            return false;  // makes the href in the anchor tag ignored
        } );
        
        // Create the <li> element with its text, and then append the anchor inside it.
        var li = $( '<li>' + characterName + ' </li>' ).append( anchor );
        li.attr ('characterID', characterID );
        
        // Append the new <li> element to the <ul> element
        $('#competitors'+ matchNum).append( li );
    }
}

function TitlesDefended(matchNum) {
    function isDupe(which) {
        var result = false;
        $('ul#titlesDefended'+ matchNum +' li').each(function(i, e) {
            if ($(e).attr('titleID') == which) {
                result = true;
                return false; // break out of .each()
            }
        });
        return result;
    }
    
    var titleID = $('#titlesDrop'+ matchNum +' option:selected').val();
    var titleName = $('#titlesDrop'+ matchNum +' option:selected').text();
    
    if (titleID > 0 && !isDupe(titleID)) {
        // Create the anchor element
        var anchor = $( '<a href="#">Remove</a>' );  
        
        // Create a click handler for the anchor element
        anchor.click( function() {
            $( this ).parent().remove();
            return false;  // makes the href in the anchor tag ignored
        } );
        
        // Create the <li> element with its text, and then append the anchor inside it.
        var li = $( '<li>' + titleName + ' </li>' ).append( anchor );
        li.attr( 'titleID', titleID );
        
        // Append the new <li> element to the <ul> element
        $( '#titlesDefended'+ matchNum ).append( li );
    }
}

function StipulationsAdded(matchNum) {
    function isDupe(which) {
        var result = false;
        $('ul#stipulationsAdded'+ matchNum +' li').each(function(i, e) {
            if ($(e).attr('stipulationID') == which) {
                result = true;
                return false; // break out of .each()
            }
        });
        return result;
    }
    
    var stipulationID = $('#stipulationsDrop'+ matchNum +' option:selected').val();
    var stipulationName = $('#stipulationsDrop'+ matchNum +' option:selected').text();
    
    if (stipulationID > 0 && !isDupe(stipulationID)) {
        // Create the anchor element
        var anchor = $( '<a href="#">Remove</a>' );  
        
        // Create a click handler for the anchor element
        anchor.click( function() {
            $( this ).parent().remove();
            return false;  // makes the href in the anchor tag ignored
        } );
        
        // Create the <li> element with its text, and then append the anchor inside it.
        var li = $( '<li>' + stipulationName + ' </li>' ).append( anchor );
        li.attr( 'stipulationID', stipulationID );
        
        // Append the new <li> element to the <ul> element
        $( '#stipulationsAdded'+ matchNum ).append( li );
    }
}

$(document).ready(function() {
    $('div.message-error').hide();
    $('div.message-success').hide();
    $('li').remove('.titleName');
    $('li').remove('.stipulationName');
    $('li').remove('.characterName');
    
    $("#bookerForm").validate({ 
        rules: {
            introduction: {
                required: true
            },
            matchtypeID: {
                required: true
            },
            liCompetitors: {
                required: true
            },
            matchwriterID: {
                required: true
            },
            matchTitle: {
                required: true
            },
            preview: {
                required: true
            },
            segment: {
                required: true
            }
        },
        messages: {
            introduction: "Please enter the event introduction!",
            matchtypeID: "Please choose the type of match!",
            liCompetitors: "Please choose atleast 2 competitors!",
            matchwriterID: "Please choose a match writer!",
            matchTitle: "Please enter a match title!",
            preview: "Please enter a preview!",
            segment: "Please choose a segment writer!"
        },
        submitHandler: function(form) {
            var eventName = $("#event").val();
            var eventID = $("#eventID").val();
            var introduction = $("#introduction").val();
            var type = $("#type").val();
            var matchArrayIndex = 0;
            var segmentArrayIndex = 0;
            var subArray = new Array();
            var masterArray = [];
            var i = 0
            foreach(... as ....) {
                var matchArray = new Array();
                var segmentArray = new Array();	
                
                foreach(match as matchValue)  {
                    var matchNumX = new Array;
                    var matchTypeIDX = new Array;
                    var titlesIDListX = new Array;
                    var stipulationsIDListX = new Array;
                    var competitorsIDListX = new Array;
                    var matchWriterIDX = new Array;
                    var matchTitleX = new Array;
                    var previewX = new Array; 
                    for(i=0;i<<?php echo $numMatches ?>; i++) {
                        var matchNum = i + 1;
                        var matchTypeID = $('select#matchTypeDrop'+ matchNum).val();  
                        var liTitles = $('ul#titlesDefended'+ matchNum +' li');
                        var titlesIDList = "";
                        var j = 0;
                        $('ul#titlesDefended'+ matchNum +' li').each(function(){
                            var liTitle = $( liTitles[ j ] );
                            
                            // only start appending commas in after the first characterID
                            if( j > 0 ) {
                                titlesIDList += ","; 
                            }
                            
                            // append the current li element's characterID to the list
                            titlesIDList += liTitle.attr( 'titleID' );
                            j++;
                        });
                        var j = 0;
                        var liStipulations = $('ul#stipulationsAdded'+ matchNum +' li');
                        var stipulationsIDList = "";
                        $('ul#stipulationsAdded'+ matchNum +' li').each(function(){
                            var liStipulation = $( liStipulations[ j ] );
                            
                            // only start appending commas in after the first characterID
                            if( j > 0 ) {
                                stipulationsIDList += ","; 
                            }
                            
                            // append the current li element's characterID to the list
                            stipulationsIDList += liStipulation.attr( 'stipulationID' );
                            j++;
                        });
                        var j = 0;
                        var liCompetitors = $('ul#competitors'+ matchNum +' li');
                        var competitorsIDList = "";
                        $('ul#competitors'+ matchNum +' li').each(function(){
                            var liCompetitor = $( liCompetitors[ j ] );
                            
                            // only start appending commas in after the first characterID
                            if( j > 0 ) {
                                competitorsIDList += ","; 
                            }
                            
                            // append the current li element's characterID to the list
                            competitorsIDList += liCompetitor.attr( 'characterID' );
                            j++;
                        });
                        var matchWriterID = $('select#matchWriter' + matchNum + '').val();
                        var matchTitle = $('input#matchTitle'+ matchNum +'').val();
                        var preview = $('textarea#preview'+ matchNum +'').val();
                        matchNumX.push(matchNum);
                        matchTypeIDX.push(matchTypeID);
                        titlesIDListX.push(titlesIDList);
                        stipulationsIDListX.push(stipulationsIDList);
                        competitorsIDListX.push(competitorsIDList);
                        matchWriterIDX.push(matchWriterID);
                        matchTitleX.push(matchTitle);
                        previewX.push(preview);
                        matchArray[matchArrayIndex] = new Object();               
                        matchArray[matchArrayIndex]['matchNum'] = matchNumX;
                        matchArray[matchArrayIndex]['matchtypeID'] = matchTypeIDX;
                        matchArray[matchArrayIndex]['titlesIDList'] = titlesIDListX;
                        matchArray[matchArrayIndex]['stipulationsIDList'] = stipulationsIDListX;
                        matchArray[matchArrayIndex]['competitorsIDList'] = competitorsIDListX;
                        matchArray[matchArrayIndex]['matchWriterID'] = matchWriterIDX;
                        matchArray[matchArrayIndex]['matchTitle'] = matchTitleX;
                        matchArray[matchArrayIndex]['preview'] = previewX;
                    }
                }
                
                foreach(segment as segmentValue) {
                    var segmentNumX = new Array;
                    var segmentWriterIDX = new Array;
                    var segmentOrderX = new Array;
                    for(i=0;i<<?php echo $numSegments ?>; i++) {
                        var segmentNum = i + 1;
                        var segmentWriterID = $('select#segmentWriter' + segmentNum + '').val();
                        var segmentOrder = $('select#sortOrder' + segmentNum + '').val();
                        segmentNumX.push(segmentNum);
                        segmentWriterIDX.push(segmentWriterID);
                        segmentOrderX.push(segmentOrder);
                        segmentArray[segmentArrayIndex] = new Object();               
                        segmentArray[segmentArrayIndex]['segmentNumber'] = segmentNumX;
                        segmentArray[segmentArrayIndex]['segmentWriterID'] = segmentWriterIDX;
                        segmentArray[segmentArrayIndex]['segmentOrder'] = segmentOrderX;
                    }
                }
                
                subArray[i] = whatever;
                subArray[i] = whenever;
                subArray[i] = matchArray;
                subArray[i] = segmentArray;
                i = i+i
            }
            
            var dataString = 'masterArray=' + masterArray;
            dataString += '&eventID=' + eventID + '&introduction=' + introduction + '&submitBooking=True';
            console.log( segmentArray );
            $.ajax({
                type: "POST",
                url: "processes/bookings.php",
                data: dataString, 
                success: function() {
                    $('div.message-error').hide();
                    $("div.message-success").html("<h6>Operation successful</h6><p>" + eventName + " saved successfully.</p>");
                    $("div.message-success").show().delay(10000).hide("slow");
                    return true;
                }
            });
            return false; 
        }   
    });
});
</script>

<p class="listInfos">
    Card Lineup for <?php echo "".$event." on ".$bookingDate."" ?>
</p>
        
<!-- Form -->
<form action="#" id="bookerForm" >
    <fieldset>
        <legend>Introduction</legend>
        <div class="field required">
            <label for="introduction">Introduction:</label>
            <textarea name="introduction" id="introduction" title="Introduction"></textarea>
            <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
        </div>
    </fieldset>
    <?php for( $i = 0; $i < $numMatches; $i++ ) { ?>
    <fieldset>
        <legend>Match #<?php echo $i+1 ?></legend>
        <div class="field required">
		<label for="matchTypeDrop<?php echo $i+1 ?>">Match Type:</label>
            <select class="dropdown" name="matchTypeDrop<?php echo $i+1 ?>" id="matchTypeDrop<?php echo $i+1 ?>" title="Match Type <?php echo $i+1 ?>">
                <option value="">- Select -</option>
               <?php
                    mysqli_data_seek( $matchtypesResult, 0 );
                    while ( $row = mysqli_fetch_array ( $matchtypesResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['matchType']."</option>\r";
                    }
                ?>
            </select>
            <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
        </div>
        <div class="field required">
		<label for="titlesDefended<?php echo $i+1 ?>">Title On The Line:</label><ul id="titlesDefended<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul>
            <select class="dropdown" name="titlesDrop<?php echo $i+1 ?>" id="titlesDrop<?php echo $i+1 ?>" title="Titles Dropdown <?php echo $i+1 ?>" style="margin-left: 195px;">
                <option value="">- Select -</option>
               <?php
                    mysqli_data_seek( $titlesResult, 0 );
                    while ( $row = mysqli_fetch_array ( $titlesResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['titleName']."</option>\r";
                    }
                ?>
            </select>
            <input type="button" value="Add Title" class="" onclick="TitlesDefended(<?php echo $i+1?>)"/>
        </div>
        <div class="field required">
		<label for="stipulationsAdded<?php echo $i+1 ?>">Stipulation:</label><ul id="stipulationsAdded<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul>
            <select class="dropdown" name="stipulationsDrop<?php echo $i+1 ?>" id="stipulationsDrop<?php echo $i+1 ?>" title="Stipulations Dropown <?php echo $i+1 ?>" style="margin-left: 195px;">
                <option value="">- Select -</option>
               <?php
                    mysqli_data_seek( $stipulationsResult, 0 );
                    while ( $row = mysqli_fetch_array ( $stipulationsResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['stipulation']."</option>\r";
                    }
                ?>
            </select>
            <input type="button" value="Add Stipulation" class="" onclick="StipulationsAdded(<?php echo $i+1 ?>)"/>
        </div>
        <div class="field required">
            <label for="competitors<?php echo $i+1 ?>">Competitors:</label><ul id="competitors<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul>
            <select class="dropdown" name="charactersDrop<?php echo $i+1 ?>" id="charactersDrop<?php echo $i+1 ?>" title="Characters Dropdown <?php echo $i+1 ?>" style="margin-left: 195px;">
                <option value="">- Select -</option>
               <?php
                    mysqli_data_seek( $charactersResult, 0 );
                    while ( $row = mysqli_fetch_array ( $charactersResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['characterName']."</option>\r";
                    }
                ?>
            </select>
            <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
            <input type="button" value="Add Character" class="" onclick="Competitors(<?php echo $i+1 ?>)"/>
        </div>
        <div class="field required">
            <label for="matchWriter<?php echo $i+1 ?>">Match Writer:</label>
            <select class="dropdown" name="matchWriter<?php echo $i+1 ?>" id="matchWriter<?php echo $i+1 ?>" title="Match Writer <?php echo $i+1 ?>">
                <option value="0">- Select -</option>
               <?php
                    mysqli_data_seek( $matchwriterResult, 0 );
                    while ( $row = mysqli_fetch_array ( $matchwriterResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['name']."</option>\r";
                    }
               ?>
            </select>
            <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
        </div>
        <div class="field required">
		<label for="matchTitle<?php echo $i+1 ?>">Match Title</label>
		<input type="text" class="text" name="matchTitle<?php echo $i+1 ?>" id="matchTitle<?php echo $i+1 ?>" title="Match Title<?php echo $i+1 ?>"/>
		<span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
	</div>
        <div class="field required">
            <label for="preview<?php echo $i+1 ?>">Preview:</label>
            <textarea name="preview<?php echo $i+1 ?>" id="preview<?php echo $i+1 ?>" title="preview <?php echo $i+1 ?>"></textarea>
            <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
        </div>
        <input type="hidden" name="type" id="type" value="Match" />
    </fieldset>
        <?php
        }
        ?>
        
    <?php if ($numSegments > 0) { ?>
        <?php for( $i = 0; $i < $numSegments; $i++ ) { ?>
            <fieldset>
                <legend>Segment <?php echo $i+1 ?></legend>
                    <div class="field required">
                        <label for="segmentWriter<?php echo $i+1 ?>">Segment Writer:</label>
                        <select class="dropdown" name="segmentWriter<?php echo $i+1 ?>" id="segmentWriter<?php echo $i+1 ?>" title="Segment Writer <?php echo $i+1 ?>">
                        <option value="0">- Select -</option>
                       <?php
                            mysqli_data_seek( $matchwriterResult, 0 );
                            while ( $row = mysqli_fetch_array ( $matchwriterResult, MYSQL_ASSOC ) ) { 
                                print "<option value=\"".$row['ID']."\">".$row['name']."</option>\r";
                            }
                       ?>
                    </select>
                        <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
                    </div>
                    <div class="field required">
                        <label for="segmentOrder<?php echo $i+1 ?>">Segment After:</label>
                        <select class="dropdown" name="segmentOrder<?php echo $i+1 ?>" id="segmentOrder<?php echo $i+1 ?>" title="Segment Order <?php echo $i+1 ?>">
                        <option value="0">- Select -</option>
                        <option value="introduction">Introduction</option>
                       <?php
                            for( $j = 1; $j <= $numMatches; $j++ ) {
                                print "<option value=$j>Match $j</option>\r";
                            }
                       ?>
                    </select>
                        <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span>
                    </div>
                    <input type="hidden" name="type" id="type" value="Segment" />
            </fieldset>
        <? } ?>
    <?php } ?>
        
    <fieldset>
    <input type="hidden" name="eventID" id="eventID" value="<?php echo $eventID; ?>" />
    <input type="hidden" name="event" id="event" value="<?php echo $event; ?>" />
    <input type="submit" class="submit" name="submitBooking" id="submitBooking" title="Submit Booking" value="Submit Booking"/>
    </fieldset>
</form>
<!-- /Form -->

<!-- Messages -->
<div class="message message-error">
    <h6>Required field missing</h6>
    <p>Please fill in all required fields. </p>
</div>
<div class="message message-success">
    <h6>Operation succesful</h6>
    <p>Booking was added to the database.</p>
</div>
<!-- /Messages -->

Link to comment
Share on other sites

If you post the relevant code I'll take a better look, but variable scope is quite an easy concept.

 

var global_var = 'foo';

function myFunction() {
    var scoped_var = 'bar';   
}

 

In the code above you can access global_var from within myFunction() as it was defined globally - i.e. outside of the scope of a function. scoped_var can only be accessed from within myFunction() as that's where it was defined - within the scope of the function. You couldn't access scoped_var from within another function however, as it's not in scope. The same principle applies to functions within functions; the top-level function being a kind of "global" scope, but for only the functions defined within.

 

If you redefine a global var from within the scope of a function, be sure to not add "var" in-front of the assignment, or you will declare a local variable -- the global variable would still exist, but you wouldn't be able to access it as you have a local variable with the same name (well you could access it, if you go through the window object: window.global_var).

 

As I said if you post the relevant code I'll take a better look, or someone else might have time to look through your code in greater detail. It's better to read and understand the problem yourself though, than to rely on someone to give you the answer.

Link to comment
Share on other sites

So I have deleted a lot of so you'll have to relook it over but I chopped it down to neccessary coding. I am just trying to focus on one thing at a time. Right now the function TitlesDefended is not adding the option as a li to the UL.

 

<?php require ('php/bookings.php'); ?>

<script type="text/javascript">
function TitlesDefended(matchNum) {
    var titleID = $('#titlesDrop'+ matchNum +' option:selected').val();
    var titleName = $('#titlesDrop'+ matchNum +' option:selected').text();
    $('#titlesDrop'+ matchNum +' option:selected').remove();
    
    if (titleID > 0) {
        var titlesCount = $('ul#titlesDefended'+ matchNum +' li').size();
        // Create the anchor element
        var anchor = $( '<a href="#">Remove</a>' );  
        
        // Create a click handler for the anchor element
        anchor.click( removeTitle );
        
        // Create the <li> element with its text, and then append the anchor inside it.
        if( titlesCount > 0 && $('.notitle').length != 0 ) { $('ul#titlesDefended'+ matchNum +'.notitle').remove(); } 
        var li = $( '<li>' + titleName + ' </li>' ).append( anchor );
        li.attr( 'titleID', titleID );
        
        // Append the new <li> element to the <ul> element
        $( '#titlesDefended'+ matchNum ).append( li );
    }
}

// Removes a character when the "Remove" link is clicked on them.
// 'evt' is the jQuery event for the click on the anchor
function removeTitle( evt ) {
evt.preventDefault();

var $liElement = $( this ).parent();   // 'this' in this context will be the anchor (<a>) element; the one that was clicked.

// Grab the characterID and characterName from the <li> element. They are stored on it as html attributes.
var titleID = $liElement.attr( 'titleID' );
var titleName = $liElement.attr( 'titleName' );

// Remove the parent <li> element
$liElement.remove();  

// Re-add the option for the removed character to the character dropdown
var option = $( '<option value="' + titleID + '">' + titleName + '</opton>' );
$( '#titlesDrop'+ matchNum ).append( option );
$( '#titlesDrop'+ matchNum +' option[value='']' ).remove();
$( '#titlesDrop'+ matchNum ).html( $( '#titlesDrop'+ matchNum+' option' ).sort(function (a, b) {
	return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
})); 
$( '#titlesDrop'+ matchNum ).prepend( '<option value="" selected="selected">- Select -</option>' );

// If no titles are left, put in the message "This handler controls no characters"
var titlesCount = $( 'ul#titlesDefended'+ matchNum ' li' ).size();
if( titlesCount == 0 ){
	$( 'ul#titlesDefended'+ matchNum ).append( '<li titleID="0" class="notitle">There are no titles being defended.</li>' );
}
}

$(document).ready(function() {
    $('div.message-error').hide();
    $('div.message-success').hide();
    $('li').remove('.titleName');
    
});
</script>

<p class="listInfos">
    Card Lineup for <?php echo "".$event." on ".$bookingDate."" ?>
</p>
        
<!-- Form -->
<form action="#" id="bookerForm" >
        <div class="field required">
		<label for="titlesDefended<?php echo $i+1 ?>">Title On The Line:</label><ul id="titlesDefended<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul>
            <select class="dropdown" name="titlesDrop<?php echo $i+1 ?>" id="titlesDrop<?php echo $i+1 ?>" title="Titles Dropdown <?php echo $i+1 ?>" style="margin-left: 195px;">
                <option value="">- Select -</option>
               <?php
                    mysqli_data_seek( $titlesResult, 0 );
                    while ( $row = mysqli_fetch_array ( $titlesResult, MYSQL_ASSOC ) ) { 
                        print "<option value=\"".$row['ID']."\">".$row['titleName']."</option>\r";
                    }
                ?>
            </select>
            <input type="button" value="Add Title" class="" onclick="TitlesDefended(<?php echo $i+1?>)"/>
        </div>
</form>
<!-- /Form -->

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.