How to use special characters to select an element using jQuery?

Asked

Viewed 43 times

0

I need to check if a input type=radio was checked with jQuery to pass to the next step of the form. My function for this was already working, but I needed to transform the name of checkbox in array for it to store data of all options chosen.

Follows the code:

 $("#button-food").click(function() {
    var food = "";
    $('input:checkbox[name=food[]]').each(function() {
        if ($(this).is(':checked')) {
            food = $(this).val();
            console.log(food);
            
        }
    })
    console.log(food);
             
    if (food != "") {
        $("#food-page").hide();
        $("#drink-page").show();
    } else {
        alert("Você precisa escolher uma alternativa! Caso não coma nada, selecione a última opção.")
        $("#button-food").blur();
    }
    
    
})

The mistake only appeared after I changed the name of inputs for name="food[]", change that was necessary for the back-end of the site. And the console error message was as follows:

Uncaught Error: Syntax error, unrecognized expression: input:checkbox[name=food[]]
    at Function.se.error (jquery-3.5.1.slim.min.js:2)
    at se.tokenize (jquery-3.5.1.slim.min.js:2)
    at se.select (jquery-3.5.1.slim.min.js:2)
    at Function.se [as find] (jquery-3.5.1.slim.min.js:2)
    at E.fn.init.find (jquery-3.5.1.slim.min.js:2)
    at new E.fn.init (jquery-3.5.1.slim.min.js:2)
    at E (jquery-3.5.1.slim.min.js:2)
    at HTMLInputElement. (quiz.js:43)
    at HTMLInputElement.dispatch (jquery-3.5.1.slim.min.js:2)
    at HTMLInputElement.v.handle (jquery-3.5.1.slim.min.js:2)
se.error @ jquery-3.5.1.slim.min.js:2
se.tokenize @ jquery-3.5.1.slim.min.js:2
se.select @ jquery-3.5.1.slim.min.js:2
se @ jquery-3.5.1.slim.min.js:2
find @ jquery-3.5.1.slim.min.js:2
E.fn.init @ jquery-3.5.1.slim.min.js:2
E @ jquery-3.5.1.slim.min.js:2
(anonymous) @ quiz.js:43
dispatch @ jquery-3.5.1.slim.min.js:2
v.handle @ jquery-3.5.1.slim.min.js:2

1 answer

1

This happens because you cannot put any character as selector. A documentation jQuery highlights these characters as "reserved" for selectors:

! "#$%&'()*+,./:;<=>?@[\]^`{|}~

So when you try to use the selector:

//                      ↓↓
input:checkbox[name=food[]]

It will give an error - comparable to a syntax error in a programming language. After all, the functioning is the same. One needs to parse the selector so that the library can understand it, so that when finding a "wrong" character (as in this case an invalid reserved character) the parser is not able to proceed, since there is, of course, an error.

To fix, you need to inform that stretch [] is, in fact, part of the attribute name. To do this, you can escape them by using the backslash character (\) or wrap them in quotes:

// Opção 1: Utilizar aspas para denotar corretamente o conteúdo do atributo `name`:
//                     ↓      ↓
$('input:checkbox[name="food[]"]');


// Opção 2: Escapar, com barra invertida, o caractere reservado:
//                         ↓↓ ↓↓
$('input:checkbox[name=food\\[\\]]');

Browser other questions tagged

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