Brian Powell
Brian Powell

Reputation: 3411

what is causing this javascript code to function the way it is?

I know stackoverflow tends to shy away from "wall of text" posts, but I've been at this for about 4 hours and I can't figure it out, so I wanted to give as much information as possible.

I have a page with two input forms on it. Whenever I add text into the first one, the javascript function attached to the second input button runs, and I can't figure out why.

In my header I have two scripts:

<script type="text/javascript" src="/autocomplete/js/script.js"></script>

which contains:

function autocomplet() {
    var min_length = 0; // min caracters to display the autocomplete
    var keyword = $('#country_id').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'capoInstantSearch.php',
            type: 'POST',
            data: {keyword:keyword},
            success:function(data){
                $('#country_list_id').show();
                $('#country_list_id').html(data);
            }
        });
    } else {
        $('#country_list_id').hide();
    }
}

// set_item : this function will be executed when we select an item

function set_item(item) {
    // change input value
    $('#country_id').val(item);
    // hide proposition list
    $('#country_list_id').hide();

  $("#capoInfo").load("capoSingleReturn.php?q="+encodeURIComponent(item));  

}

capoInstantSearch.php looks like this:

<?php

function connect() {
    return new PDO('code here to connect'}

$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT statement is here....";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
    // put in bold the written text
    $country_name = str_replace(strtoupper($_POST['keyword']), '<b>'.$_POST['keyword'].'</b>', $rs['quotePartNumber']);
    // add new option
    echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['quotePartNumber']).'\')">'.$country_name.'</li>';
}
?>

and

<script type="text/javascript" src="/autocomplete/js/script2.js"></script>

which contains:

function compCheck() {
    var min_length = 0; // min caracters to display the autocomplete
    var bootyTime = $('#comp_id').val();
    if (bootyTime.length >= min_length) {
        $.ajax({
            url: 'capoInstantCompSearch.php',
            type: 'POST',
            data: {bootyTime:bootyTime},
            success:function(data){
                $('#comp_list_id').show();
                $('#comp_list_id').html(data);
            }
        });
    } else {
        $('#comp_list_id').hide();
    }
}

// set_item : this function will be executed when we select an item
function set_item(item) {
    // change input value
    $('#comp_id').val(item);
    // hide proposition list
    $('#comp_list_id').hide();
  $("#compReturn").load("capoCompReturn.php?w="+encodeURIComponent(item));
}

Input Box 1:

<input id="country_id" type="text" placeholder="Enter a Part Number"
onsubmit="this.value=this.value.toUpperCase()" autocomplete="off" onkeyup="autocomplet()">
<ul id="country_list_id"></ul>

Input Box 2:

<input id="comp_id" type="text" onkeypress="this.value=this.value.toUpperCase()" 
placeholder="Part Number 2" onkeyup="compCheck()"></h2>
<ul id="comp_list_id"></ul>

Ultimately, the contents of autocomplet() should be placed into this div

<div id="capoInfo" class="capoData"></div>

while the contents of compCheck() should be placed into

<div id="compReturn" class="blueBorder"></div>

When I type text into the first input box, it populates the <ul> country_list_id, and when I make a selection, it populates that answer into second input box on my page, then executes that code. I cannot figure out WHY it is doing this and it's driving me crazy....

Upvotes: 0

Views: 357

Answers (2)

jz552
jz552

Reputation: 36

It's because you have two functions that are in the global scope called "set_item"

Upvotes: 1

caseyWebb
caseyWebb

Reputation: 2096

You are defining your functions in the global scope, and the second is overwriting the first. You could solve this by namespacing (for lack of a better term) your functions by sticking them into an object.

For example,

script.js

var country = {

    autocomplete: function() {
        var min_length = 0; // min caracters to display the autocomplete
        var keyword = $('#country_id').val();
        if (keyword.length >= min_length) {
            $.ajax({
                url: 'capoInstantSearch.php',
                type: 'POST',
                data: {keyword:keyword},
                success:function(data){
                    $('#country_list_id').show();
                    $('#country_list_id').html(data);
                }
            });
        } else {
            $('#country_list_id').hide();
        }
    },

    // set_item : this function will be executed when we select an item
    set_item: function(item) {
        // change input value
        $('#country_id').val(item);
        // hide proposition list
        $('#country_list_id').hide();

      $("#capoInfo").load("capoSingleReturn.php?q="+encodeURIComponent(item));  

    }
}

script2.js

var comp = {

    compCheck: function() {
        var min_length = 0; // min caracters to display the autocomplete
        var bootyTime = $('#comp_id').val();
        if (bootyTime.length >= min_length) {
            $.ajax({
                url: 'capoInstantCompSearch.php',
                type: 'POST',
                data: {bootyTime:bootyTime},
                success:function(data){
                    $('#comp_list_id').show();
                    $('#comp_list_id').html(data);
                }
            });
        } else {
            $('#comp_list_id').hide();
        }
    },

    // set_item : this function will be executed when we select an item
    set_item: function(item) {
        // change input value
        $('#comp_id').val(item);
        // hide proposition list
        $('#comp_list_id').hide();
      $("#compReturn").load("capoCompReturn.php?w="+encodeURIComponent(item));
    }

}

and then change the references in your HTML to include the namespace, e.g.

input box 1 (note the onkeyup)

<input id="country_id" type="text" placeholder="Enter a Part Number"
onsubmit="this.value=this.value.toUpperCase()" autocomplete="off" onkeyup="country.autocomplete()">
<ul id="country_list_id"></ul>

and then repeat for all the other references, including the one in the PHP code.

You may also want to check out Browserify which brings Node's require module syntax to the browser. Additionally, you might read up on closures and IIFE's in JS.

Upvotes: 1

Related Questions