I want to sample

console.log($('[data-id=+name+]')); 

When name is equal to the word "Circle" - JS finds it, and if there is a space in the phrase, for example, "test drink", then JS gives an error:

jquery.js: 1468 Uncaught Error: Syntax error, unrecognized expression: [data-id = test drink]

Tell me what to do in this case?

  • Wait, you are a normal question, here it is something else - lazyproger

2 answers 2

Began to test This code works, it finds a div, and with spaces and without

 $("body").append('<div data-attr="Кофе Чай"></div>'); $("[data-attr='Кофе Чай']").data('attr'); //И даже если так name = 'Кофе Чай'; $("[data-attr='"+name+"']").data('attr'); 

Try this:

 console.log($('[data-id=+name+]')); //Твой код замени на console.log($("[data-id='"+name+"']")); //Скорее всего дело в кавычках 

    Use .data() to get the value of the data class

    Example:

     $("input[name=getValue]").on("click", function(){ $("input[type=text]").each(function(){ var val = $(this).data("id"); if(val === "Круг") alert("val = Круг"); }); }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-id="Круг" value="круг"><br/> <input type="text" data-id="Квадрат" value="квадратик"><br/> <input type="text" data-id="Трегольник" value="трегольничек"><br/> <input type="button" name="getValue" value="Получить все значения data-id" />