jQuery syntax error, unrecognised expression - javascript

syntax error, unrecognised expression: #2015-11-30|1112|1
I have an anchor tag with an Id of '2015-11-30|1112|1' that I would like to apply a class to. I am doing the same method for on a '' and this works, but I am getting syntax errors with the following. Can anyone explain the syntax error?
$(document).ready(function() {
$("#tbl_calendar").on("click", "a", null, clickAppointment);
});
function clickAppointment(eventData)
{
//Get the Id of the appointment that has been clicked:
currentAppointment = $(this).attr('id');
//alert('clicked' + '#'+currentAppointment)
$('#'+currentAppointment).addClass('selected');
}

You should escape the special chracters in your id using \\, check example bellow.
Hope this helps.
console.log( $("#2015-11-30\\|1112\\|1").text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="2015-11-30|1112|1">Div text example</div>

For your current code to work, you don't have to use that id selector since you already have the reference of the object inside the event function.
$(document).ready(function() {
$("#tbl_calendar").on("click", "a", clickAppointment);
function clickAppointment(eventData) {
//"this" will have a reference to the clicked object
$(this).addClass("selected");
}
});
Not sure about your HTML, but considering something similar to the below one.
<ul id="tbl_calendar">
<li>
<a id="2015-11-30|1112|1">Click</a>
</li>
</ul>
Working sample

Related

How to get specific div through this?

I build a method that allow me to return the clicked element by the user, something like this:
$('#button2').on('mouseover', function()
{
console.log(this);
}
this return:
<tr id="res-7" class="entry border-bottom" rel="popover" data-original-title="" title="">
<td style="padding-left: 10px">
<div class="name"><strong>Test</strong></div>
<div class="description">Foo</div>
</td>
</tr>
essentially my target is get the content of div name and div description, someone could explain how to do this? Thanks.
Something like this: jsfiddle
$(document).on("mouseover","tr", function(){
var name = $(this).find(".name").text();
var description = $(this).find(".description").text();
console.log("Name: "+name+"\nDecsription: "+description);
})
Don't forget ID of each element must be unique so your code is not correct because "#button2" must be unique, so this is always #button2 in your function.
Note the difference between text() and html(). I used .text() to get just the text without "strong" code. If you need it use html().
You could use innerHTML
$(this).find('name').innerHTML; //returns "test"
$(this).find('description').innerHTML; //returns "foo"
This will find the class within the current element, and return the values you need.
Since you already have an id on your element, accessing the name and description attributes is easy:
$('#button2').on('mouseover', function() {
var $res7 = $('#res-7');
// Access the two divs
var name = $res7.find('.name').text(); // or .html()
var description = $res7.find('.description').text(); // or .html()
// Print them out
console.log(name);
console.log(description);
});
Of course, this block of code should be inside a jQuery ready event handler.
I'm sure there is a cleaner way, but this should get you what you want.
$('#button2').on('mouseover', function()
{
console.log($(this).find(".name").html());
console.log($(this).find(".description")).html());
}

Unable to get offset of an element

I am trying to get offset of some elements which is working fine for me. But the problem occurs if element id contains single quotes. It throw an error, e.g, if the element id is whats_next its working fine.
But if id is what's_next if gave me an error.
Error: Syntax error, unrecognized expression: #What's_Next
....value:null},t.error=function(e){throw new Error("Syntax error, unrecognized exp...
Also I don't have access over HTML I can not change the HTML. Do you guys have any solution for this ?
Here is my code:
$('.custom-toc li a').click(function(){
var id = $(this).attr('href');
console.log(id);
console.log($(id).offset());
});
HTML of element where I am clicking:
<a rel="internal" href="#What's_Next">What's Next</a>
HTML of element offset element:
<span id="What's_Next"></span>
<h4 class="editable">What's Next2</h4>
You can escape ' using replace()
HTML:
<div class="custom-toc">
<ul>
<li>
dddfs
</li>
</ul>
</div>
<span id="What's_Next">hello</span>
<h4 class="editable">What's Next2</h4>
JS :
$('.custom-toc li a').click(function(){
var id = $(this).attr('href').replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g,'\\$1');
console.log(id);
console.log($(id).offset());
});
Have you tried going for the id as attribute approach?
Like this:
var id = "What's Next";
var elem = $("span[id="+id+"]");
Well I tried, and it doesn't work :) - Cudos to Garvit, he has it right, this is his solution (only simplified):
var id = $(this).attr('href');
console.log(id);
id = id.replace("'","\\'");
console.log($("#"+id).offset());
Here's another way to do it without escaping the quote, although it requires you to remove the hash from the front of the href (and also, using $("*") is slow)
$('.custom-toc li a').click(function() {
var href = $(this).attr('href').substring(1);
var a = $("*").filter(
function(index) {
return $(this).attr('id') == href;
}
);
console.log($(a[0]).offset());
You can't use the ' symbol inside your div's id - You should change
<span id="What's_Next"></span>
to
<span id="Whats_Next"></span>
EDIT:
because You can't/don't want to change div's id You are working on an invalid code. You should consider debugging it first to further work.
EDIT 2:
Thanks to #Tibrogargan comment I've checked the w3c recommendation and he's probably right:
id = ID A unique identifier for the element. There must not be
multiple elements in a document that have the same id value. Any
string, with the following restrictions:
must be at least one character long
must not contain any space characters
Source: w3c.org

How to use the title attribute of a div to add a class?

I'm trying to add a class to a div by using the title attribute. Currently the alert is correct. However the class isn't added.
JS Part:
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", +clicked_id).addClass("glow");
}
HTML Part:
<div id="sticky" class="" title='sticky1' onclick='index(this.title)'</div>"
I don't know if I got your question right but I understood that you want to filter|find you div by the title. So maybe this code will help you:
function index(clicked_id){
alert(clicked_id);
$('#sticky [title="' + clicked_id + '"]').addClass("glow");
}
This is how I would do it:
$("[title*='sticky']").click(function(){
$(this).addClass("glow");
});
Here is the JSFiddle demo
Why do you need to do it like that? Can't you just set the class on the element clicked?
JavaScript
function index(el){
$(el).addClass("glow");
}
HTML
<div id="sticky" onclick='index(this)'></div>
Instead just pass this:
onclick='index(this)'
now in the function:
function index(el){
var e = $(el).attr('title');
$('#sticky[title="'+e+'"]').addClass("glow");
}
As the element itself is the target one then just use this:
function index(el){
$(el).addClass("glow");
}
or better to go unobtrusive, remove the inline event handler and use this way:
$('#sticky').on('click', function(e){
$(this).addClass("glow");
});
js at Question returns expected results. Missing closing > at html #sticky <div> tag at
onclick="index(this.title)"
following onclick attribute . Additionally,
+
should be removed at
+clicked_id
at .attr() setting title . javascript + operator attempting to convert clicked_id String to Number when placed before string
function index(clicked_id){
alert(clicked_id);
$('#sticky').attr("title", clicked_id).addClass("glow");
}
.glow {
color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="sticky" class="" title="sticky1" onclick="index(this.title)">click</div>

Getting the class name which triggered the event

I have a tag with below HTML :
<a href='#' class='create_account singup header-icon'>Create Account</a>
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class'));
/**
In case , user click on button with class `create_account` , I get in console
`create_account singup header-icon` , which is correct,
**but I want `create_account` i.e is the class which triggered the Click event**
*/
});
I would just create a separate click handler for each class, like so:
// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
// Attach a new click handler per-class. This could be a shared function
$("."+selector).click(function(e) {
e.preventDefault();
alert(selector); // Logs individual class
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="create_account" href="">Create</a>
<a class="member_login" href="">Login</a>
<a class="product_services" href="">Services</a>
If you want you can abstract the shared logic out into another function, like this Fiddle
Alternative Approach with Data Attributes
<a href='#' class='action-trigger' data-action='Creation'>Create Account</a>
$('.action-trigger').click(function(){
console.log($(this).data('action'));
});
Retrieve Class Based on it Being First
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class').split(' ')[0]);
});
Alternative Approach with Parameters
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account').click(function(){
MyFunction('CreateAccount');
});
$('.member_login').click(function(){
MyFunction('MemberLogin');
});
function MyFunction(type)
{
console.log(type);
}
$(this).attr('class');
This will always return the list of classes that the element has. You can actually include an 'id' attribute to the element to access it when clicked.
<a href='#' class='but' id='create_account'>Button 1</a>
$('.but').click(function(){
alert($(this).attr('id'));
});
Demo: https://jsfiddle.net/dinesh_feder/2uq5h03j/
There are good solutions put forth using an array of selectors, but here is a solution using the strings of the selectors and the classes of the triggering element.
It's unfortunate that .selector was removed in jQuery 1.9 or else this would be even simpler. The approach is to get the original selector as an array and intersect it with the array of classes on the triggering element. The result will be the class that triggered the event. Consider this example:
[".create_account", ".member_login", ".product_services"]
[".class1", ".class2", ".create_account"]
Their intersection is:
[".create_account"]
Here is working code:
var selector = '.create_account, .member_login, .product_services';
$(selector).on("click", { sel: selector.split(", ") }, function(e){
var classArr = $(this).attr("class").split(" ").map(function(a){ return "."+a; });
var intersect = $.map(e.data.sel,function(a){return $.inArray(a, classArr) < 0 ? null : a;});
alert(intersect[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 class2 create_account">class1 class2 create_account</button><br/><button class="class3 product_services class4">class3 product_services class4</button><br/><button class="class5 class6 member_login">class5 class6 member_login</button>
I would add the classes into an array and then iterate to it to see if our target has one of those into its class attribute :
var classes = ['.create_account' , '.member_login' , '.product_services'];
$(classes.join()).click(function(){
for(var i=0; i<classes.length; i++){
var classPos = $(this).attr('class').indexOf(classes[i].substring(1));
if(classPos>-1)
$('#result').html(classes[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='create_account singup header-icon'>Create Account</a>
<a href='#' class='member_login singup header-icon'>Member Login</a>
<a href='#' class='singup header-icon product_services'>product services</a>
<p id="result"></p>
Well, to take back the Manish Jangir .... example, if you have to retrieve only the concerned class, then why don't you test it? you use jquery so you can use "hasClass" don't you?
$('.create_account , .member_login , .product_services').click(function(e){
if($(this).hasClass('create_account')){
alert('create_account');
}
if($(this).hasClass('member_login')){
alert('member_login');
}
if($(this).hasClass('product_services')){
alert('product_services');
}
});
This is maybe not a "perfect solution" but it fits your requirements...^^
You can also do it this way with jquery :
$('body').on('click','.create_account',function(event){
alert('.create_account');
//do your stuff
});
$('body').on('click','.member_login',function(event){
//...
});
$('body').on('click','.product_services',function(event){
//...
});
this way you just have to add a block if you add a new class that needs an event on click on it... I do not see any more "specific" answer to your question... I always used to do it this way since the way I handle the event on classes can be really different...

Adding a Space when using addClass and variables using jQuery

I have jQuery read some text then add a class based on the value of this text. (The text read is rendered by my CMS).
The HTML Looks like this:
<ul class="zoneSubscriptions">
<li>
<ul>
<li class="zoneName">Professional</li>
<li>Never</li>
</ul>
</li>
<li>
<ul>
<li class="zoneName">RTTM</li>
<li>Never</li>
</ul>
</li>
</ul>
I want to read the text of class="zoneName"and add a class based on this.
JS to do this:
$(function() {
var zone = $( ".zoneName" ).text();
$( "#zones" ).addClass( zone );
});
This works without issue, however, I need it to add two classes, Professional and RTTM. What it adds is ProfessionalRTTM.
My question is how would I add the classes while keeping a space between the words?
In other words it should render like this: class="Professional RTTM" not class="ProfessionalRTTM"
Note: In my example there are two "zoneName"s. There could be anywhere from 1 to 5 or more when used live.
Try iterating the tags:
var $zones = $("#zones");
$(".zoneName").each(function () {
$zones.addClass( $(this).text() );
});
Also possible (if you want to reuse the list of class names)
var classes = [];
$(".zoneName").each(function () {
classes.push($(this).text());
});
$("#zones").addClass(classes.join(" "));
You're calling .text() on multiple results which is joining them together.
Why not do something like this instead:
var zone = $( ".zoneName" ).each(function(){
$("#zones").addClass($(this).text());
});
Find all your .zoneNames and then call addClass for each one.
jsFiddle example
You need to iterate across the .zoneNames, otherwise your .text() will be a one undivided string (unless you have whitespace in there)
$(".zoneName").each(function() {
$("#zones").addClass($(this).text());
});
You can use the callback function of addClass(), and use map() to get an array of the text, then simply join with a space:
$('#zones').addClass(function() {
return $('.zoneName').map(function() {
return $(this).text();
}).get().join(' ');
});
Here's a fiddle

Categories

Resources