Transforming jQuery code into Javascript

Asked

Viewed 1,242 times

7

I have a problem similar to that : Insert text - Stack

But in my case I need the code in pure Javascript and I have no idea (novice in Prog. web) how to change from jQuery that they gave as a response.

jQuery:

$('.botao_add').click(function(){
    $(this).parent().children('select').append($('<option>', {
    value: $(this).parent().children('input:first').val(),
    text: $(this).parent().children('input:first').val()}));
});

$('.botao_del').click(function(){
    $(this).parent().children('select').children('option:selected').each(function() {
        $(this).remove();
    });
});

How would this excerpt look in pure Javascript? And how to check somehow, even in jQuery, if the data entered in the input has already been entered in the box?

  • 3

    I don’t think it’s right for someone to give you the code ready, the coolest thing would be for you to learn JS and be able to do it on your own. From a JS student at Codeacademy, it’s super interactive and easy. After 30 minutes you’ll be able to make your own code. http://www.codecademy.com/pt/tracks/javascript

  • If I’m asking here, it’s because I’ve had no progress in what I’m developing even though I have a little knowledge in javascript (well little)! And I don’t think it’s wrong for someone to want to get a code ready to have a base!

  • 5

    The site You Might Not Need jQuery contains information on how to do a lot of things with pure Javascript. It has a slider for you to choose whether you want to see IE8+, IE9+ or IE10 version+

  • 1

    After I met jquery I don’t even want to see pure js in front of me, in the topic you mentioned there are some examples in pure js, and you may notice that it is much more complicated, but what exactly prevents you from using jquery?

  • 1

    @Jader who prevents me from using jquery is my superior because he thinks it is a very "complex form"!

  • 1

    I’m kind of running out of time to do this right now, but the first thing I would ask, if I could help you with, would it be: do you need legacy browser compatibility, or could it be HTML5? HTML5 makes it easy to do a lot of jQuery stuff.

  • In this case where I am working @Ruipimentel, I would need compatibility! But thanks anyway!

  • @Jader, in this case the Jquery you implemented, has the possibility to check whether the input value has already been entered into the box?

  • 1

    @Jader This is not the case with Bruno, but the performance of pure Javascript is good (for example, see this comparison) superior to jQuery.

  • 1

    @Beet I was already aware of this difference in performance, but for simple applications, and even often more complex, this does not affect at all... It will only appear in a loop with many repetitions where a selector is used.

  • 1

    @Bruno I had answered with the jquery code with existence check (as stated in his request), but they were denying my answer so I removed it, follow the jsfiddle for you to take a look: http://jsfiddle.net/jaderw/ht5b9xzk/1/

Show 6 more comments

3 answers

8

whereas:

  1. jQuery itself, at least in version 2, does not support browsers well ancient;

  2. IE6, IE7 and even IE8 are getting rarer every day;

  3. The work to make the code really compatible with these relics requires a good deal of work, which can be even well instructive for you;

I present the following "translation", which I tested only on Chrome. The goal was just to transcribe, literally, instruction per instruction from jQuery to a simple Javascript. I decided not to use features of the latest versions, such as querySelector and the querySelectorAll, And I didn’t bother to optimize or validate anything either. With the code in hand, you can then study the bugs that occur in the browsers where you test and then edit the answer with the solutions.

window.addEventListener("load", function() {
    var botoes_add = document.getElementsByClassName("botao_add");
    for(var i = 0; i < botoes_add.length; i++){
        botoes_add[i].addEventListener("click", function(){
            var selects = this.parentElement.getElementsByTagName("select");
            var input_first = this.parentElement.getElementsByTagName("input")[0];
            for(var j = 0; j < selects.length; j++){
                var novo_option = document.createElement("option");
                novo_option.value = input_first.value;
                novo_option.innerHTML = input_first.value;
                selects[j].appendChild(novo_option);
            }
        });
    }
    var botoes_del = document.getElementsByClassName("botao_del");
    for(var i = 0; i < botoes_del.length; i++){
        botoes_del[i].addEventListener("click", function(){
            var selects = this.parentElement.getElementsByTagName("select");
            for(var j = 0; j < selects.length; j++){
                var options = selects[j].getElementsByTagName("option");
                for(var k = 0; k < selects[j].children.length; k++){
                    if(selects[j].children[k].selected) selects[j].removeChild(selects[j].children[k]);
                }
            }
        });
    }
});

At least in Chrome 36.0.1985.125 for Linux, which I tested, I’m sure the functionality is identical at the jsFiddle you quoted.

Edit: I forgot to put my pàoprio jsFiddle, and to say that the innerHTML was chosen instead of innerText to allow compatibility with Firefox.

I hope it serves as a first step for you.

Hugs!

  • 1

    +1 for the effort you put into this post. I would love to give another +1 for the comment on being instructive.

  • Thanks, @Renan! Having something to add or realizing some slip, not only you but everyone else, you may feel free to edit :D

1


A simpler way to your problem:

function move(Origem, Destino)
{
    var opt = document.createElement("option"); 
    var valor = Origem.value;
    if(valor==""){
        alert("Informe um dado válido!"); 
        return;
    }

    opt.text = valor ;
    opt.value = valor ;
    Destino.options.add(opt);
 }

function tira(Destino)
{
    var i;
    for(i = 0; i < Destino.options.length; i++)
    { 
        if (Destino.options[i].selected && Destino.options[i].value != "")
        {
            valor=Destino.options[i].value;
            Destino.remove(Destino.selectedIndex);
        }
    }
}

0

think q if you download the development version of jquery and search what makes each function you can understand, even because jquery is done in pure js, it is just a huge library with various functions.

Example of a code "not jquery" simulating the selector $ jquery in js pure.

html

<p id="ha">lalala</p>

js

function $(par) {
    re = /^[.#]/;
    if (re.test(par)) {
        return document.querySelector(par);
    } else {
        return document.querySelectorAll(par);
    }
}

console.log($("#ha").id);

or

(function (window) {
    function $(par) {
        re = /^[.#]/;
        if (re.test(par)) {
            return document.querySelector(par);
        } else {
            return document.querySelectorAll(par);
        }
    }

    window.$ = $;
})(window);

console.log($("#ha").id);

output

ha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.