jquery - get the id of the closest element? - javascript

This is my code which is used to edit an input when clicked on it and then save in the db.
$(document).ready(function() {
$('.editable').on('click', function() {
var that = $(this);
if (that.find('input').length > 0) {
return;
}
var currentText = that.text();
var $input = $('<input>').val(currentText);
$(this).append($input);
// Handle outside click
$(document).click(function(event) {
if(!$(event.target).closest('.editable').length) {
if ($input.val()) {
that.text($input.val());
var div_id = $(this).closest('#commentbox').attr('id');
div_id = div_id.replace('comment-', '');
alert(div_id);
$.post( "updateComment.php", {id: div_id,message: $input.val()})
}
that.find('input').remove();
}
});
});
});
Var div_id is not retrieving it at all.
And I want to retrieve only the number from the id from this however it does not work. I've been trying several solutions and this last one isn't working either
<div id="comments">
<div class="commentbox" id="comment-90">...</div>
<div class="commentbox" id="comment-91">...</div>
</div>

This part of code is basically a problem:
var div_id = $(this).closest('#commentbox').attr('id');
Firstly, you are trying to get closest element from document as this points to document in that part of your code (you meant probably event.target instead).
Secondly, you are trying to find the closest element with id == 'commentbox', as this is what #<selector> means. You should use some other attribute for that purpose - probably best would be some class selector and then use the .attr('id') on it.

Related

Press a unique button do the actions

So as I started using JavaScript and jQuery, I have a question with unique div.
Is is possible in the JavaScript to make a unique div name then do the action onclick?
http://jsfiddle.net/agmr2ytd/4/
Example HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=">
Me 2
</div>
JavaScript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify).hide();
});
});
When I press a first a from div I wanna get the id value as a alert and hide it.
You need to set class = favorite to your divs, then this is working:
DEMO
jQuery / javascript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
var tohide = document.getElementById(verify);
tohide.style.display = 'none';
});
});
HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=" class="favorite">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=" class="favorite">
Me 2
</div>
Your selector is wrong, for attributes ^= means "attribute value starts with":
$(function() {
$('[id^=favorite] a').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify.replace(/([ #;?%&,.+*~\':"!^$[\]()=>|\/#])/g,'\\$1')).hide();
});
});
Example Fiddle <-
Your ID has to be escaped, used this answer for solution.

Javascript don't add the class

hello everyone javascript don't add the class to html
$(".ocmessage").each(function(){
var text = $(this).find('p').html();
if(strpos(text,"<b>"+name+"</b>")!==false) $(this).addClass("quoteme");
});
this code should detect if in <p>...</p> there are name of some member and if there is javascript should add class quoteme
how can i fix it?
I think you mean this. BTW, name isn't defined.
var name = ''; // change the value
if(text.indexOf("<b>"+name+"</b>") > -1) {
$(this).addClass("quoteme");
}
Assuming ocmessage is a div or another contain class.
Take a look at : http://jsfiddle.net/40vv7dbk/
$(".ocmessage").each(function () {
var $this = $(this);
var text = $this.find('p').html();
var name = "Ben"
// Will be -1 if not found.
if (text.indexOf(name) > -1) {
$this.addClass("quoteme");
}
});
What it is doing, is when the document is ready, going through all the Divs with the class ocmessage, looking for a tag, and then checking if a name is in there. If it does, I add the class quoteme.
Your elements with class ocmessage may contain more than one paragraph. So inside the first each-loop we have to do a second loop through all <p> like so:
$(".ocmessage").each(function(){
var $T = $(this);
$T.find('p').each(function() {
var text = $(this).html();
// find username and prevent multiple class adding
if(text.indexOf("<b>"+name+"</b>") > -1) {
$T.addClass("quoteme"); return false; // stop loop when class is added
}
});
});
Working FIDDLE here. Credits to Amit Joki.
This is a very poor way to accomplish the task. Here's the more standard jquery way to do it.
$(".ocmessage").has('p b:contains('+name+')').addClass("quoteme");

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

grabbing div id by click

I am using $('.startb').click(function() {
var myId = $(this).attr("id");
}); to capture the id "startb1" what do I need to add to also capture the id "test1" by the class "flashObj" by using the fact they are all in the same div container "audioContainer"
<div class="audioContainer">
<div class="audioTitle">hi</div>
<div class="playerHolder">
<div class="startb" id="startb1" rel="Audio/004_IAM_God_is_Love.mp3"><img src="dbs/images/start.png" width="40" height="40" /></div>
<div class="flashObj" id="test1"></div>
<div class="mp3Logo"><img src="dbs/images/mp3_off.gif"/></div>
</div>
</div>
You could search for siblings of the div having the class flashObj:
$('.startb').click(function() {
var myId = $(this).attr("id");
var flashObjID = $(this).siblings('.flashObj').attr('id');
});
var myId = this.id;
var otherId = this.parentNode.querySelector(".flashObj").id;
This method of getting the "startb1" id is approximately 150 times more efficient than yours, due to the amount of steps jQuery has to go through just to create the $(this) object, by the way.
Also, querySelector is supported in IE8 whereas getElementsByClassName isn't.
If IE7 and below is required, and the structure is reliable (ie. it will always be the fourth child div you need), use: var otherId = this.parentNode.children[3].id;.
Use .on() instead of .click() if you are using latest jQuery release:
$(".audioContainer").on("click", ".startb", function(e){
var _this = $(this);
var id = _this.attr("id");
var oId = _this.closest(".audioContainer").find(".flashObj").attr("id");
}
Now you can also map multiple events, keep events for later on and even pass data to the event.data object and etc.
Read more at: jQuery .on()
Assuming you want to use the same "click" event, the following should do the trick:
$('.startb').click(function() {
var myId = $(this).attr("id");
var flashID = $(this).parent().find(".flashObj").attr("id");
});

Having jQuery string comparison issues

I've got a fiddle going here to show what I'm trying to do.
I have a table that is generated dynamically, so the columns could appear in whatever order the user chooses. So, I'm trying to get the index of two specific headers so that I can add a CSS class to those two columns for use later.
You should use .filter() here instead (and whenever you need to restrict the element set), since your .each() return is getting thrown away, like this:
//Loop thru the headers and get the Supp elem
var suppCol = $("#my_table th").filter(function() {
return $(this).html() == "Supp";
});
//Loop thru the headers and get the Report elem
var reportCol = $("#my_table th").filter(function() {
return $(this).html() == "Report";
});
You can test the updated/working fiddle here. The alternative using .each() would look like tis:
var suppCol, reportCol;
$("#my_table th").each(function() {
var $this = $(this), html = $this.html();
if(html == "Supp") suppCol = $this;
if(html == "Report") reportCol= $this;
});
You can test that version here.

Categories

Resources