Using ID as a variable - javascript

I'm trying to find the text of the span with the class name "link" but i have problems.
<div id="item-0" class="box">
.......
</div>
<div id="item-1" class="box">
<p><strong>Link: </strong><span class="link">http://www.domain.com/list44/</span></p>
<p><input type="submit" value="submit" class="load-button2"></p>
</div>
<div id="item-2" class="box">
.......
</div>
$(".load-button2").click(function(){
var id = $(this).closest('.box').attr('id');
alert(id); // showing the right box ID
var linkp = $(/*** what should i put here? ***/ "#" + id + " .link").text;
});

You should just be able to do:
$(".load-button2").click(function(){
var id = $(this).closest('.box').attr('id');
alert(id); // showing the right box ID
var linkp = $("#" + id).find(".link").text();
});
Although, a more elegant solution would be:
$(".load-button2").click(function(){
var linkp = $(this).closest('.box').find(".link").text();
});

You can try this code:
$(".load-button2").click(function(){
var text = $(this).closest('.box').find('.link').text();
});

$(".load-button2").click(function(){
var id = $(this).closest('.box').attr('id');
alert(id); // showing the right box ID
//var linkp = $(what should i put here / "#" + id = " .link").text;
var linkp = $("#"+id).find(".link").text;
});

An alternative so you don't have to do another full DOM traversal (since you already get the container).
$(".load-button2").click(function(){
var container = $(this).closest('.box');
var id = container.attr('id');
alert(id); // showing the right box ID
var linkp = container.find('.link').text();
alert(linkp);
});
See it in action.

Related

JQuery add elements with bootstrap styling

I am trying to add a button to a specific HTML element using jQuery similar to, (https://www.w3schools.com/jquery/jquery_dom_add.asp)
My issue is that when I try and run the code,
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
I don't get the styling I am wanting and it is messing up another part of my code unless I do the same as above, except without the bootstrap styling like,
var txt1 = "<button">text</button>";
$("#thing1").append(txt1); // Append new elements
It works fine with the second example except for that the button styling doesn't use bootstrap like I am wanting in the first example and am not sure as to why?
A more complete picture of the code is below,
<script>
function askName(){
var name = prompt("What's your name?");
var message = "Hello " + name + ", would you like to build a table?"
document.getElementById('output').innerHTML = message;
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
};
function tables(){
var txt1 = "<p>Text.</p>"; // Create text with HTML
var txt2 = $("<p></p>").text("Text."); // Create text with jQuery
var txt3 = document.createElement("p");
txt3.innerHTML = "Text."; // Create text with DOM
$("body").append(txt1, txt2, txt3); // Append new elements
}
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</script>
</head>
<body>
<div class="container-fluid">
<button type = "button" class= "btn btn-primary" onclick="askName()">
Want to chat?
</button>
</div>
<h3 style = "text-align: center"class="text-primary" id="output"></h3>
<div id = thing1>
</div>
</body>
</html>
I think you just have a problem where you should be mixing your " and your '
try this:
var txt1 = "<button type = 'button' class = 'btn btn-primary'>text</button>";
Maybe the problem is with your quotes
var txt1 = "<button type = "button" class = "btn btn-primary">text</button>";
$("#thing1").append(txt1); // Append new elements
try
var txt1 = '<button type = "button" class = "btn btn-primary">text</button>';
$("#thing1").append(txt1); // Append new elements

How to know if two divs are present with same id in javascript?

Is there any way to check if two divs are having same ids?
I have created divs dynamically and I am finding it difficult to remove the div having a duplicate id, can anyone help here?
I do not know what you are trying to achieve here , but generally you should not have two elements with the same id . But if you have some reason to do this maybe you are building a validator or someting like this you can do the following to count the number of elements
var count = document.querySelectorAll('#test').length;
console.log(count);
then you can loop through them and remove them using
document.querySelectorAll('#test')[1].remove();
Try it with:
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
You have to loop all the elements as helpers like getElementById() won't work well when their aren't unique.
Example, no need for jQuery. Alerts the duplicate ID.
var idMap = {};
var all = document.getElementsByTagName("*");
for (var i=0; i < all.length; i++) {
// Do something with the element here
var elem = all[i];
if(elem.id != ""){ //skip without id
if(idMap[elem.id]){
alert("'" + elem.id + "' is not unique")
}
idMap[elem.id] = true;
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
</body>
</html>
var idList = [];
$('*[id]').each(function(){
var id = $(this).attr('id');
if($.inArray(id, idList)){
alert('the id ' + id + ' is already set!');
} else {
idList.push(id);
}
});
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if (ids.length>1 && ids[0]==this){
$("#"+this.id).remove();
}
});​
above function use jquery to create array of all IDs with in the document and remove duplicated id
Something like this should do what you want
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "1">
ola
</div>
<div id = "2">
ole
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
Example based on the link: jQuery: Finding duplicate ID's and removing all but the first
Can you not just control + F and search for the id's? Also if you are using an editor like atom, you can delete every other duplicate in one go after the search.

How to get the html element from jquery object

I have a html like follows.
<tr class="meta-info" id="${page.id}">
<td>
<div class="pull-left">
<font size="1">
Like
</font>
</div>
<div class="pull-right" style="font-size:1">
<span class="badge"><i class="icon-thumbs-up"></i>1</span>
</div>
</td>
</tr>
I am trying to increase the number of likes when ever the user cliks on Like hyperlink.
Here is my jquery code. I want to know how i can get the html element from the jquery object.
$(".like").click(function(event){
var parentTr = $(event.target).closest("tr");
if(parentTr.length){
var pageId = parentTr.attr("id");
var spanEle = parentTr.get(0)+" div span:first-child"; ------(1)
var lastNumber = parseInt(spanEle.text());
spanEle.text(lastNumber+1);
}
});
I don't know if i am doing right on line which is marked 1.
I think you need to add an extra <span> tag so that you can replace the count without touching the adjacent icon
<span class="badge"><i class="icon-thumbs-up"></i>
<span class="like-count">1</span>
</span>
then you can address it
$(".like").click(function() {
var spanEle = $(this).closest('tr').find('.like-count').first();
if (spanEle.length) {
var newCount = parseInt(spanEle.text());
spanEle.text(newCount + 1);
}
});
In an event handler, the this reference is event.target. You may be able to handle the element doesn't exist case neater than that too but that way's safe.
JSFiddle demo: http://jsfiddle.net/rupw/VfCvK/
Try this...
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.first('.badge');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
If the span element always has that classname then it will find the first (only?) one and return an int value of the text within.
Try: Fiddle
var lastNumber = parseInt(parentTr.find('.pull-right span').text(), 10);
You code will look like:
$(".like").click(function(event) {
var parentTr = $(event.target).closest("tr");
if (parentTr.length) {
var pageId = parentTr.attr("id");
var spanEle = parentTr.find('.pull-right span');
var lastNumber = parseInt(spanEle.text(), 10);
spanEle.text(lastNumber + 1);
}
});
Update: If you wish to keep the <i> tag then use:
spanEle.html(spanEle.html().replace(lastNumber, lastNumber + 1));
insteadof : spanEle.text(lastNumber + 1);
Sample

jquery two replace functions

I am not sure why item count parentheses aren't being removed in this tiny fiddle example.
EDIT: Here is my result from looking at the working answer.
$.fn.itemcount = function(){
var text = $(this).text();
text = text.replace("(","").replace(")","");
$(this).text(text);
};
$("#prc").itemcount();
$.fn.sidecartcost = function(){
var el = $(this);
var text = $(this).text();
text = text.replace("Your sub total is", "").replace(". ", "");
$(this).text(text);
};
$('.SideCartCost').sidecartcost();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="prc">(7 Items)</div>
<div class="blank">Woo</div>
<div class="SideCartCost">Your sub total is $300.03. </div>
you are not replacing the html/text of the div like so http://jsfiddle.net/x5jeL/1/

Changing a div's id in order to show/hide

My old code looked like this:
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
When my radio button was clicked:
<input class="editable" type="radio" name="q1" id="q1-a" onclick="unhide(this); scoreIncrement(this);"/>John
It would unhide this div:
<div id="answerq1a" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
But now, my radio button must look like this:
<input class="editable" type="radio" name="q1" id="untitled-region-1" onclick="unhide(this); scoreIncrement(this);"/>John
and my div that I want to unhide has the same id, but as they are unique, it replaces the 1 with the next number up. In my case it is 4 id's down so the id would be "untitled-region-5" for the new id, as follows:
<div id="untitled-region-5" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
So how can I change this code, to grab the new id "untitled-region-5" and minus 4 from it to fix it to the radio button with the new id's?
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
I am going along this sort of track:
function unhide2(rad) {
var id = $("div").attr('id').replace(/untitled-region-/, 'untitled-region-');
var untitled-region = document.getElementById(id);
if (untitled-region) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
untitled-region.className = "unhidden";
}
}
But I don't know how to replace the last digit on the id with "digit-4".
You've tagged this with jQuery, so I'll give you the jQuery answer.
The right way to solve this is not to mash about with id's, but to link the radio, and it's associated div some other way, and IMO the best way is using a data- attribute.
<input class="editable" type="radio"
name="q1" id="q1-a" data-answerId="untitled-region-5"/>John
Then your javascript becomes easy-as:
$('.editable').click(function(){
$('#' + currentShown).removeClass('unhidden').addClass('hidden');
var answerId = $(this).data('answerId');
$('#' + answerId).removeClass('hidden').addClass('unhidden');
});
Although I urge you to do away with the unhidden, hidden confusion and just use .show() and .hide()!

Categories

Resources