Javascript using Jquery! looping and printing value - javascript

Suppose I have this:
<div id="apple" class="fruit"></div>
<div id="orange" class="fruit"></div>
<div id="grape" class="fruit"></div>
<div id="pear" class="fruit"></div>
How do I write a javascript function that can loop and print out all the fruit IDs with class "fruit"? Using JQuery.

$('div.fruit').each(function(){
//will loop through all divs with the class fruit.
$(this).attr('id'); //will give you the id of the current div
});

As printed out as comma separated list (ids is an array of the ids).
var ids = $.map($('div.fruit'), function(e) {
return e.id;
});
document.write(ids.join(','));
Working Demo - click on the output tab to see the output.
Using the following would cater for there being <div class="fruit"> with no id
var ids = $.map($('div.fruit'), function(e) {
return e.id? e.id : null;
});

Related

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.
#foreach($starter in $starter)
<div class="product">
<div class="color"><img src= "$starter.img" width="100" height="100"></div>
<span class="product-name">$starter.name</span>
<div class="compare-wrap">
<input type="checkbox" id="">
<label id="view">Compare</label>
</div>
</div>
#end
I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:
var checkedArray = [];
$(":checkbox").change(function(){
if((this).checked){
checkedArray.push(this.id);
document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
}
else{
checkedArray.splice(checkedArray.indexOf(this.id), 1);
document.getElementById('view').innerHTML = 'Compare';
}
var str = checkedArray.join(', ');
alert(str);
});
but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?
document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:
var views = document.getElementsByClassName('view');
var i = views.length;
while(i--) {
views[i].innerHTML = "Compare";
}
HTML
<label class="view">Compare</label>
Element ID must be unique.
Hope it helps.

Find an element that contains id of selector + text

I'm confused as to how I should go about doing this.
My page is using PHP to take product codes off a database and using them to generate ids for elements. For example: $("#touch-'.$productcode.'") and $("#popup-'.$productcode.'")
I need to make it so when an element is clicked on, jQuery will find an element in the document which contains the last 11 characters of the selector's id plus additional text.
e.g. the selector $(this) (which has a generated id of #touch-123-456-789) would get its own id, remove everything but the last 11 characters (the product code), append popup- to the beginning, and then find the element $("#popup-123-456-789") and perform an action.
How about some thing like this..
<div class='touch' id='touch-123-456-789'> bla bla </div>
on your jquery
$('.touch').click(function(){
var id = $(this).attr('id');
id = id.substring(5);
$('#popup' + id).doSomething();
});
This is your Html
<div class="pop-up" value= "123-456-789">one</div>
<div class="pop-up" value="123-123-123">two</div>
This is your jQuery
$(".pop-up").click(function(){
var value = $(this).attr("value");
var yourElement = "popup-"+value;
$("#"+yourElement).doSomething(function () {
});
});
Try to break your id like:
$('.touch').click(function () {
var id = $(this).attr('id');
id = id.split(/-(.+)?/)[1];
$('#popup-' + id).html("Hello changed");
});
The .split() here will split the on the first occurrence of "-". So you can do anything with this.
Lets suppose you have two elements in your html code:
<div class='touch' id='touch-123-456-789'> Touch me </div>
<div class="popup" id="popup-123-456-789"></div>
This might help. http://jsfiddle.net/79yut/
HTML:
<div class="element" id="#touch-123-456-790">Sample element1</div>
<div class="element" id="#touch-123-456-791">Sample element2</div>
<div class="element" id="#touch-123-456-792">Sample element3</div>
<div class="element" id="#touch-123-456-793">Sample element4</div>
<div class="element" id="#touch-123-456-794">Sample element5</div>
JS:
for (i = 0; i <= $(".element").length; i++) {
if (i < $(".element").length) {
var id = $(".element").eq(i).attr("id");
id = "popup-" + id.substring(7);
$(".element").eq(i).attr("id", id);
} else {
$("#popup-123-456-792").css('color','blue');
}
}

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

Jquery get each div's sub child divs and grab info into an array

I have a some html that looks like this
<div id="main">
<div id="sub_main_1" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
<div id="sub_main_2" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
</div>
I would like to pull out each sub_main divs information into an array in javascript. So far I have this as my jquery code
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
The alert is just a test that it should show "hi" twice. But this is not working. I am also not clear on how I can store the two inputs in a javascript array. Any help would be great! Thanks,
var array = $('#main input').map(function() {
return $(this).val();
}).get();
EDIT:
Note that this will return the values of all input elements under #main. You can make the $('#main input') selector as specific as you need if not all input elements are desired.
var info = $("#main .sub_main input:text").map(function() {
return $(this).val();
}).get(); // get() converts resulting collection into array
http://api.jquery.com/map/
Are you waiting for the DOM to load?
$(document).ready(function(){
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
});
if you want to pull out the child divs of your 'main' div, use
$('.main>div')
This will select all div children of anything with the class of 'main'.
why not just do something simple like this:
var firsts = [];
var seconds = [];
("#main .sub_main input").each(function(){
var $this = $(this);
if($this.is(".sub_name_first"){
firsts.push($this.val());
} else {
seconds.push($this.val());
}
});
sure, its not the best way, but i just wrote that in 1 minute and it works

Categories

Resources