Ver Mensaje Individual
  #1 (permalink)  
Antiguo 27/07/2016, 01:10
jaschei
 
Fecha de Ingreso: enero-2016
Mensajes: 13
Antigüedad: 8 años, 3 meses
Puntos: 0
Alguna mano para entender este script?

Estimados
Resulta que tengo un formulario en el cual hay un SELECT en donde ingreso un valor y automáticamente me completa otros casilleros, en este caso unos INPUT(type=text). Ej: ingreso un producto y entiende cual es el precio del mismo y me llena el "value" de ese input.

Para que esto suceda se ejecuta una function php en donde se pasan ciertos atributos, los cuales uno de ellos es $ajaxoptions. Esta variable es un array en donde en donde nos encontramos posicionado otro array UPDATE de la siguiente forma:
'update' => array('YYYY'=>'XXXX').
De esta manera la función que voy a dejar adjunta, que en realidad es un <script>, se comporta haciendo que cualquier input del formulario donde el id="YYYY", le completa el value="XXXX".

Ahora, lo que quiero hacer yo, es agregar otro input o botón que me permita poder cargar una página donde la URL contenga ese valor XXXX. Ej: localhost/product.php?id=XXXX.

Por ahora lo que si logro es poner un parámetro (dir=action del formulario que deseo) en un input submit que realiza la acción, distinta a la del botón que originalmente realiza el action del formulario.

El código es el siguiente:
Código PHP:
/**
 *    Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: /societe/ajaxcompanies.php).
 *  The HTML field must be an input text with id=search_$htmlname.
 *  This use the jQuery "autocomplete" function.
 *
 *  @param    string    $selected           Preselecte value
 *    @param    string    $htmlname           HTML name of input field
 *    @param    string    $url                Url for request: /path/page.php. Must return a json array ('key'=>id, 'value'=>String shown into input field once selected, 'label'=>String shown into combo list)
 *  @param    string    $urloption            More parameters on URL request
 *  @param    int        $minLength            Minimum number of chars to trigger that Ajax search
 *  @param    int        $autoselect            Automatic selection if just one value
 *  @param    array    $ajaxoptions        Multiple options array (Ex: array('update'=>array('field1','field2'...)) will reset field1 and field2 once select done)
 *    @return string                      Script
 */
function ajax_autocompleter($selected$htmlname$url$urloption=''$minLength=2$autoselect=0$ajaxoptions=array())
{
    if (empty(
$minLength)) $minLength=1;

    
$script '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" />';

    
$script.= '<script type="text/javascript">';
    
$script.= '$(document).ready(function() {
                    var autoselect = '
.$autoselect.';
                    var options = '
.json_encode($ajaxoptions).';

                    // Remove product id before select another product
                    // use keyup instead change to avoid loosing the product id
                    $("input#search_'
.$htmlname.'").keydown(function() {
                        //console.log(\'purge_id_after_keydown\');
                        $("#'
.$htmlname.'").val("");
                    });
                    $("input#search_'
.$htmlname.'").change(function() {
                        //console.log(\'change\');
                        $("#'
.$htmlname.'").trigger("change");
                    });
                    // Check when keyup
                    $("input#search_'
.$htmlname.'").keyup(function() {
                            //console.log(\'keyup\');
                            if ($(this).val().length == 0)
                            {
                                $("#search_'
.$htmlname.'").val("");
                                $("#'
.$htmlname.'").val("").trigger("change");
                                if (options.option_disabled) {
                                    $("#" + options.option_disabled).removeAttr("disabled");
                                }
                                if (options.disabled) {
                                    $.each(options.disabled, function(key, value) {
                                        $("#" + value).removeAttr("disabled");
                                    });
                                }
                                if (options.update) {
                                    $.each(options.update, function(key, value) {
                                        $("#" + key).val("").trigger("change");
                                    });
                                }
                                if (options.show) {
                                    $.each(options.show, function(key, value) {
                                        $("#" + value).hide().trigger("hide");
                                    });
                                }
                                if (options.update_textarea) {
                                    $.each(options.update_textarea, function(key, value) {
                                        if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
                                            CKEDITOR.instances[key].setData("");
                                        } else {
                                            $("#" + key).html("");
                                        }
                                    });
                                }
                            }
                    });
                    $("input#search_'
.$htmlname.'").autocomplete({
                        source: function( request, response ) {
                            $.get("'
.$url.($urloption?'?'.$urloption:'').'", { '.$htmlname.': request.term }, function(data){
                                if (data != null)
                                {
                                    response($.map( data, function(item) {
                                        if (autoselect == 1 && data.length == 1) {
                                            $("#search_'
.$htmlname.'").val(item.value);
                                            $("#'
.$htmlname.'").val(item.key).trigger("change");
                                        }
                                        var label = item.label.toString();
                                        var update = {};
                                        if (options.update) {
                                            $.each(options.update, function(key, value) {
                                                update[key] = item[value];
                                            });
                                        }
                                        var textarea = {};
                                        if (options.update_textarea) {
                                            $.each(options.update_textarea, function(key, value) {
                                                textarea[key] = item[value];
                                            });
                                        }
                                        return { label: label, value: item.value, id: item.key, update: update, textarea: textarea, disabled: item.disabled }
                                    }));
                                }
                                else console.error("Error: Ajax url '
.$url.($urloption?'?'.$urloption:'').' has returned an empty page. Should be an empty json array.");
                            }, "json");
                        },
                        dataType: "json",
                        minLength: '
.$minLength.',
                        select: function( event, ui ) {        // Function ran when new value is selected into javascript combo
                            //console.log(\'set value of id with \'+ui.item.id);
                            $("#'
.$htmlname.'").val(ui.item.id).trigger("change");    // Select new value
                            // Disable an element
                            if (options.option_disabled) {
                                if (ui.item.disabled) {
                                    $("#" + options.option_disabled).prop("disabled", true);
                                    if (options.error) {
                                        $.jnotify(options.error, "error", true);        // Output with jnotify the error message
                                    }
                                    if (options.warning) {
                                        $.jnotify(options.warning, "warning", false);        // Output with jnotify the warning message
                                    }
                            } else {
                                    $("#" + options.option_disabled).removeAttr("disabled");
                                }
                            }
                            if (options.disabled) {
                                $.each(options.disabled, function(key, value) {
                                    $("#" + value).prop("disabled", true);
                                });
                            }
                            if (options.show) {
                                $.each(options.show, function(key, value) {
                                    $("#" + value).show().trigger("show");
                                });
                            }
                            // Update an input
                            if (ui.item.update) {
                                // loop on each "update" fields
                                $.each(ui.item.update, function(key, value) {
                                    $("#" + key).val(value).trigger("change");
                                });
                            }
                            if (ui.item.textarea) {
                                $.each(ui.item.textarea, function(key, value) {
                                    if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
                                        CKEDITOR.instances[key].setData(value);
                                        CKEDITOR.instances[key].focus();
                                    } else {
                                        $("#" + key).html(value);
                                        $("#" + key).focus();
                                    }
                                });
                            }
                            console.log("ajax_autocompleter new value selected, we trigger change");
                            $("#search_'
.$htmlname.'").trigger("change");    // To tell that input text field was modified
                        }
                        ,delay: 500
                    }).data("ui-autocomplete")._renderItem = function( ul, item ) {
                        return $("<li></li>")
                        .data( "item.autocomplete", item )
                        .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
                        .appendTo(ul);
                    };

                  });'
;
    
$script.= '</script>';

    return 
$script;

Espero que se entienda y puedan darme una mano
Desde ya muchas gracias