Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Pasar Variable de Formulario a javaScript

Estas en el tema de Pasar Variable de Formulario a javaScript en el foro de Frameworks JS en Foros del Web. Buenas a todos. Estoy intentando realizar una funcion de autocomplete similar a Twitter, es decir que te sugiera nombres de usuario tras @ Para ello ...
  #1 (permalink)  
Antiguo 12/06/2012, 08:04
 
Fecha de Ingreso: febrero-2007
Mensajes: 70
Antigüedad: 17 años, 2 meses
Puntos: 1
Pasar Variable de Formulario a javaScript

Buenas a todos. Estoy intentando realizar una funcion de autocomplete similar a Twitter, es decir que te sugiera nombres de usuario tras @
Para ello he utilizado el script que he encontrado en esta pagina http://jsfiddle.net/mekwall/mcWnL/52/

Código HTML:
<script type='text/javascript'>//<![CDATA[ 

(function($){

    $.widget("ui.tagging", {
        // default options
        options: {
            source: [],
            maxItemDisplay: 3,
            autosize: true,
            animateResize: false,
            animateDuration: 50
        },
        _create: function() {
            var self = this;
            
            this.activeSearch = false;
            this.searchTerm = "";
            this.beginFrom = 0;

            this.wrapper = $("<div>")
                .addClass("ui-tagging-wrap");
            
            this.highlight = $("<div></div>");
            
            this.highlightWrapper = $("<span></span>")
                .addClass("ui-corner-all");

            this.highlightContainer = $("<div>")
                .addClass("ui-tagging-highlight")
                .append(this.highlight);

            this.meta = $("<input>")
                .attr("type", "hidden")
                .addClass("ui-tagging-meta");

            this.container = $("<div></div>")
                .width(this.element.width())
                .insertBefore(this.element)
                .addClass("ui-tagging")
                .append(
                    this.highlightContainer, 
                    this.element.wrap(this.wrapper).parent(), 
                    this.meta
                );
            
            var initialHeight = this.element.height();
            
            this.element.height(this.element.css('lineHeight'));
            
            this.element.keypress(function(e) {
                // activate on @
                if (e.which == 64 && !self.activeSearch) {
                    self.activeSearch = true;
                    self.beginFrom = e.target.selectionStart + 1;
                }
                // deactivate on space
                if (e.which == 32 && self.activeSearch) {
                    self.activeSearch = false;
                }
            }).bind("expand keyup keydown change", function(e) {
                var cur = self.highlight.find("span"),
                    val = self.element.val(),
                    prevHeight = self.element.height(),
                    rowHeight = self.element.css('lineHeight'),
                    newHeight = 0;
                cur.each(function(i) {
                    var s = $(this);
                    val = val.replace(s.text(), $("<div>").append(s).html());
                });
                self.highlight.html(val);
                newHeight = self.element.height(rowHeight)[0].scrollHeight;
                self.element.height(prevHeight);
                if (newHeight < initialHeight) {
                    newHeight = initialHeight;
                }
                if (!$.browser.mozilla) {
                    if (self.element.css('paddingBottom') || self.element.css('paddingTop')) {
                        var padInt =
                            parseInt(self.element.css('paddingBottom').replace('px', '')) + 
                            parseInt(self.element.css('paddingTop').replace('px', ''));
                        newHeight -= padInt;
                    }
                }
                self.options.animateResize ?
                    self.element.stop(true, true).animate({
                            height: newHeight
                        }, self.options.animateDuration) : 
                    self.element.height(newHeight);
                
                var widget = self.element.autocomplete("widget");
                    widget.position({
                        my: "left top",
                        at: "left bottom",
                        of: self.container
                    }).width(self.container.width()-4);
                
            }).autocomplete({
                minLength: 0,
                delay: 0,
                maxDisplay: this.options.maxItemDisplay,
                open: function(event, ui) {
                    var widget = $(this).autocomplete("widget");
                    widget.position({
                        my: "left top",
                        at: "left bottom",
                        of: self.container
                    }).width(self.container.width()-4);
                },
                source: function(request, response) {
                    if (self.activeSearch) {
                        self.searchTerm = request.term.substring(self.beginFrom); 
                        if (request.term.substring(self.beginFrom - 1, self.beginFrom) != "@") {
                            self.activeSearch = false;
                            self.beginFrom = 0;
                            self.searchTerm = "";
                        }
                        if (self.searchTerm != "") {
                            
                            if ($.type(self.options.source) == "function") {
                                self.options.source(request, response);                   
                            } else {
                                var re = new RegExp("^" + escape(self.searchTerm) + ".+", "i");
                                var matches = [];
                                $.each(self.options.source, function() {
                                    if (this.label.match(re)) {
                                        matches.push(this);
                                    }
                                });
                                response(matches);
                            }
                        }
                    }
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function(event, ui) {
                    self.activeSearch = false;
                    //console.log("@"+searchTerm, ui.item.label);
                    this.value = this.value.replace("@" + self.searchTerm, ui.item.label) + ' ';
                    self.highlight.html(
                        self.highlight.html()
                            .replace("@" + self.searchTerm,
                                     $("<div>").append(
                                         self.highlightWrapper
                                             .text(ui.item.label)
                                             .clone()
                                     ).html()+' ')
                    );
                        
                    self.meta.val((self.meta.val() + " @[" + ui.item.value + ":]").trim());
                    return false;
                }
            });

        }
    });

})(jQuery);


$(function() {
    
    var names = [
        {
            
        }
    ];
    
    $("textarea").tagging({
        source: function(request, response) {
            $.ajax({
                type: "post",
                url: "jsonn.php?name=" + document.form.message.value,
                data: { term: request.term, json: JSON.stringify(names) 
				},
                success: function(data){
                    response(data);
                },
                dataType: "json"
            });
        }
    });

});
//]]>  

</script> 

Dados mis escasos conocimientos sobre este tema, tengo el siguiente problema, necesito pasar via post a un archivo php que lo procesara cualquier cosa que se introduzca tras @..... la solucion que he encontrado es
Código HTML:
url: "jsonn.php?name=" + document.form.message.value,
sin embargo esto pasa el mensaje al completo y no solo lo que se encuentra tras @...
Hay alguna forma de pasar tan solo esa variable??
Gracias de antemano.
  #2 (permalink)  
Antiguo 12/06/2012, 08:16
Avatar de dontexplain  
Fecha de Ingreso: junio-2012
Mensajes: 536
Antigüedad: 11 años, 10 meses
Puntos: 127
Respuesta: Pasar Variable de Formulario a javaScript

Cita:
Iniciado por josemadridista Ver Mensaje
Buenas a todos. Estoy intentando realizar una funcion de autocomplete similar a Twitter, es decir que te sugiera nombres de usuario tras @
Para ello he utilizado el script que he encontrado en esta pagina [URL="http://jsfiddle.net/mekwall/mcWnL/52/"]http://jsfiddle.net/mekwall/mcWnL/52/[/URL]

Código HTML:
<script type='text/javascript'>//<![CDATA[ 

(function($){

    $.widget("ui.tagging", {
        // default options
        options: {
            source: [],
            maxItemDisplay: 3,
            autosize: true,
            animateResize: false,
            animateDuration: 50
        },
        _create: function() {
            var self = this;
            
            this.activeSearch = false;
            this.searchTerm = "";
            this.beginFrom = 0;

            this.wrapper = $("<div>")
                .addClass("ui-tagging-wrap");
            
            this.highlight = $("<div></div>");
            
            this.highlightWrapper = $("<span></span>")
                .addClass("ui-corner-all");

            this.highlightContainer = $("<div>")
                .addClass("ui-tagging-highlight")
                .append(this.highlight);

            this.meta = $("<input>")
                .attr("type", "hidden")
                .addClass("ui-tagging-meta");

            this.container = $("<div></div>")
                .width(this.element.width())
                .insertBefore(this.element)
                .addClass("ui-tagging")
                .append(
                    this.highlightContainer, 
                    this.element.wrap(this.wrapper).parent(), 
                    this.meta
                );
            
            var initialHeight = this.element.height();
            
            this.element.height(this.element.css('lineHeight'));
            
            this.element.keypress(function(e) {
                // activate on @
                if (e.which == 64 && !self.activeSearch) {
                    self.activeSearch = true;
                    self.beginFrom = e.target.selectionStart + 1;
                }
                // deactivate on space
                if (e.which == 32 && self.activeSearch) {
                    self.activeSearch = false;
                }
            }).bind("expand keyup keydown change", function(e) {
                var cur = self.highlight.find("span"),
                    val = self.element.val(),
                    prevHeight = self.element.height(),
                    rowHeight = self.element.css('lineHeight'),
                    newHeight = 0;
                cur.each(function(i) {
                    var s = $(this);
                    val = val.replace(s.text(), $("<div>").append(s).html());
                });
                self.highlight.html(val);
                newHeight = self.element.height(rowHeight)[0].scrollHeight;
                self.element.height(prevHeight);
                if (newHeight < initialHeight) {
                    newHeight = initialHeight;
                }
                if (!$.browser.mozilla) {
                    if (self.element.css('paddingBottom') || self.element.css('paddingTop')) {
                        var padInt =
                            parseInt(self.element.css('paddingBottom').replace('px', '')) + 
                            parseInt(self.element.css('paddingTop').replace('px', ''));
                        newHeight -= padInt;
                    }
                }
                self.options.animateResize ?
                    self.element.stop(true, true).animate({
                            height: newHeight
                        }, self.options.animateDuration) : 
                    self.element.height(newHeight);
                
                var widget = self.element.autocomplete("widget");
                    widget.position({
                        my: "left top",
                        at: "left bottom",
                        of: self.container
                    }).width(self.container.width()-4);
                
            }).autocomplete({
                minLength: 0,
                delay: 0,
                maxDisplay: this.options.maxItemDisplay,
                open: function(event, ui) {
                    var widget = $(this).autocomplete("widget");
                    widget.position({
                        my: "left top",
                        at: "left bottom",
                        of: self.container
                    }).width(self.container.width()-4);
                },
                source: function(request, response) {
                    if (self.activeSearch) {
                        self.searchTerm = request.term.substring(self.beginFrom); 
                        if (request.term.substring(self.beginFrom - 1, self.beginFrom) != "@") {
                            self.activeSearch = false;
                            self.beginFrom = 0;
                            self.searchTerm = "";
                        }
                        if (self.searchTerm != "") {
                            
                            if ($.type(self.options.source) == "function") {
                                self.options.source(request, response);                   
                            } else {
                                var re = new RegExp("^" + escape(self.searchTerm) + ".+", "i");
                                var matches = [];
                                $.each(self.options.source, function() {
                                    if (this.label.match(re)) {
                                        matches.push(this);
                                    }
                                });
                                response(matches);
                            }
                        }
                    }
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function(event, ui) {
                    self.activeSearch = false;
                    //console.log("@"+searchTerm, ui.item.label);
                    this.value = this.value.replace("@" + self.searchTerm, ui.item.label) + ' ';
                    self.highlight.html(
                        self.highlight.html()
                            .replace("@" + self.searchTerm,
                                     $("<div>").append(
                                         self.highlightWrapper
                                             .text(ui.item.label)
                                             .clone()
                                     ).html()+' ')
                    );
                        
                    self.meta.val((self.meta.val() + " @[" + ui.item.value + ":]").trim());
                    return false;
                }
            });

        }
    });

})(jQuery);


$(function() {
    
    var names = [
        {
            
        }
    ];
    
    $("textarea").tagging({
        source: function(request, response) {
            $.ajax({
                type: "post",
                url: "jsonn.php?name=" + document.form.message.value,
                data: { term: request.term, json: JSON.stringify(names) 
				},
                success: function(data){
                    response(data);
                },
                dataType: "json"
            });
        }
    });

});
//]]>  

</script> 

Dados mis escasos conocimientos sobre este tema, tengo el siguiente problema, necesito pasar via post a un archivo php que lo procesara cualquier cosa que se introduzca tras @..... la solucion que he encontrado es
Código HTML:
url: "jsonn.php?name=" + document.form.message.value,
sin embargo esto pasa el mensaje al completo y no solo lo que se encuentra tras @...
Hay alguna forma de pasar tan solo esa variable??
Gracias de antemano.
A ver, twitter funciona de la siguiente manera.

Como los nombres de usuario no pueden contener espacios, se considera que la variable a buscar sea todo aquello hasta que haya un espacio.

Como le dije a @pepito_jimenez la posibilidad

De la cadena anterior sólo seleccionas el contenido hasta que haya el espacio, para ello puedes usar simplemente una expresión regular, para eso puedes usar el método match.

Puedes probar alguna expresión regular como esta

Cita:
/@.+\s?$/
"Como le dije a @pepito_jimenez la posibilidad"

Como le dije a @pepito_jimenez la posibilidad

Última edición por dontexplain; 12/06/2012 a las 08:25
  #3 (permalink)  
Antiguo 12/06/2012, 08:25
 
Fecha de Ingreso: febrero-2007
Mensajes: 70
Antigüedad: 17 años, 2 meses
Puntos: 1
Respuesta: Pasar Variable de Formulario a javaScript

Sin embargo eso puede dar lugar a un problema, en caso de que introduzcas varios nombres de usuario tras @---- el script que te devuelve el automplete en php va sacar cada uno, entonces no servirar para "sugerir" es por eso que se hace necesario enviar tan solo eso ya desde javascript

Etiquetas: ajax, formulario, funcion, html, input, javascript, jquery, js, php, variables
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 13:52.