简体   繁体   中英

jQuery and Joomla update selectbox on click

I'm a total noob when it comes to jQuery. This time I would like to populate a select box when a user clicks it. I managed to do that, but each time the user selects an option the select box instantly changes it's value back to default, so the user can't select the one he wants. Below you can view the code from Joomla that loads the database and the HTML file with the select box. I know I'm doing something wrong but I'm not sure what this is...

widget.php - Joomla Database file with query

<?php
    // Set flag that this is a parent file.
    define('_JEXEC', 1);
    define('DS', DIRECTORY_SEPARATOR);

    if (file_exists(dirname(__FILE__) . '/defines.php')) {
        include_once dirname(__FILE__) . '/defines.php';
    }

    if (!defined('_JDEFINES')) {
        define('JPATH_BASE', dirname(__FILE__));
        require_once JPATH_BASE.'/includes/defines.php';
    }

    require_once JPATH_BASE.'/includes/framework.php';

    $db = JFactory::getDbo();
    $db2 = JFactory::getDbo();
    $sql = "SELECT id, type, name FROM #__widgetkit_widget WHERE type = 'gallery'";
    $db->setQuery($sql);
    $rows = $db->loadObjectList();
    $query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";
    $db2->setQuery($query);
    $rows2 = $db2->loadObjectList();
    $my_yacht = $rows2[0]->w_id;
    echo '<option value="">-- Please Select --</option>';
    foreach($rows as $row) {
        echo '<option value="'.$row->id.'"';
        if($row->id == $my_yacht) { echo ' selected'; }
            echo '>'.$row->name.'</option>'."\n";
        }
?>

And the HTML file with the JavaScript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html prefix="og: http://ogp.me/ns#" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr" >
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            var j = jQuery.noConflict();
            j(document).ready(function () {
                j("#jform_w_id").click(function () {
                    j("#jform_w_id").load('widget.php');
                });
            });
        </script>
    </head>
    <body>
        <select class="" id="jform_w_id" name="jform[w_id]">
            <option value="">-- Please Select --</option>
            <option value="59">Bavaria 50 Cruiser</option>
            <option value="60">Bavaria 49</option>
        </select>
    </body>
</html>

The problem is that you're reloading the select box from widget.php every time a user clicks on the #jform_w_id select box. Since you aren't first grabbing the previously selected item, the previous selection is lost.

One solution is to store off the previously selected value before loading, then reassign the selection after loading, like so:

<script type="text/javascript">
    var j = jQuery.noConflict();
    j(document).ready(function () {
        var selectBox = j('#jform_w_id');
        selectBox.click(function () {
            var oldValue = selectBox.val();
            selectBox.load('widget.php');
            selectBox.val(oldValue);
        });
    });
</script>

With that said, I'm not convinced this is a good pattern, for a few reasons:

1) You're reloading from the server every time the user clicks that select. If the list is long, you're going to have a noticeable lag between the time the user clicks and the time the select box pops up. Make sure you understand why you are loading the data from the server every time there's a click, and make sure your use case really requires that. You may be able to have a process that caches the values and repopulates the dropdown asynchronously.

2) I haven't tested this, but it's possible that reloading the options box after clicking could cause the control to flicker, lose focus, or other unexpected behavior.

3) If you need to support mobile users, the above issues will be exacerbated by UI and bandwidth constraints.

Since I don't know your particular use case, these may be concerns you've already thought of, but if not, please consider them as you craft your page.

Finally, please consider replacing this line

$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = ".JRequest::getInt('id')."";

with a prepared statement. While the fact that you're currently parsing an int from the request object protects you from SQL injection attacks for this one use case, you'll glad you used prepared statements if you copy this chunk of code for use elsewhere where the WHERE clause parameter is a string. The semantics of prepared statements will depend on the DB you're using and Joomla's database API, but it's usually something like:

$query = "SELECT id, b_name, w_id FROM #__yachts WHERE id = :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':id', JRequest::getInt('id'));
if ($stmt->execute()) {
    while ($row = $stmt->fetch()) {
    ...
    }
}

See: http://us1.php.net/pdo.prepared-statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM