I can not access an item with an ID that contains% with JQuery

2

I am creating an input element dynamically to introduce a title to an image that the user uploads.

When I create the element I assign it as id title + the name of the uploaded image. To remove the spaces and accents that may have the name of the image that is being uploaded, add an encodeURI (nameImage). This returns a string with %

Example: "garden games" - > encodeURI returns jardi%CC%81n%20juegos

The input element is created and displayed on the page correctly with that id.

The problem is when I try to access it when they save the data. I access it by $("#titlejardi%CC%81n%20juegos").val() to get its value. For the elements that are created without % because they do not have spaces or accents I am doing well. How can I access the value of the item?

    
asked by Maria Jo 14.07.2017 в 11:20
source

3 answers

3

As you say @blonfu in your answer , jQuery uses CSS Syntax to select the elements.

To treat these characters as CSS notation, they should be escaped by placing two backslashes in front of them.

$('#titlejardi\%CC\%81n\%20juegos').css( 'color', 'red' );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="titlejardi%CC%81n%20juegos">
  Lorem ipsum dolor amet
</div>

or with regex:

function jq( myid ) {
 
  return "#" + myid.replace( /[:.[\],=@%]/g, "\$&" );
 
}

$( jq('titlejardi%CC%81n%20juegos') ).css( 'color', 'green' );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="titlejardi%CC%81n%20juegos">
      Lorem ipsum dolor amet
    </div>

Source: learn.jquery.com

    
answered by 14.07.2017 / 14:09
source
1

In principle in HTML there is no problem with using those characters in ids, not in javascript.

Example:

var contenido = document.getElementById("titlejardi%CC%81n%20juegos").innerHTML;
console.log("Texto del div: " + contenido);
<div id="titlejardi%CC%81n%20juegos">
  Lorem ipsum dolor amet
</div>

However in CSS you can not use certain characters, I think you can only use letters, numbers, hyphens and underscores. You can not start with a number either.

jQuery uses CSS selectors to access the elements and possibly that's why it does not work.

    
answered by 14.07.2017 в 12:00
-1

I would not use that type of structure as id . In any case you could use a library or function as you return a more appropriate text for an id. If you are looking for information of the type "normalize name javascript" you will find interesting links and functions of the basic library that you can use as String.normalize

The other option is to use something other than the id to make the selection, for example data-imagename or whatever.

    
answered by 14.07.2017 в 11:36