extracting a user choice from variable class box - javascript

Truly a quirk of Javascript that goes above my head
I read into this and it seemed to do with cases in Javascript. \
Either way, I have multiple class div boxs and data filling each box. The code below outputs what the user chooses into console.
All good and well, however i am trying to extract the users choice and put it into a variable so what the user chose from the drop down can be used to inform other parts of my code. I dont know how to extract that information?
//Global variables
classText = document.getElementsByClassName("searchText");
classBox = document.getElementsByClassName("searchBoxModule");
//HTML
<div id="searchBox">
<div class="searchBoxModule" onclick="firstBox()">
<a class='searchText'></a>
</div>
<div class="searchBoxModule">
<a class='searchText'></a>
</div>
<div class="searchBoxModule">
<a class='searchText'></a>
</div>
<div class="searchBoxModule">
<a class='searchText'></a>
</div>
<div class="searchBoxModule">
<a class='searchText'></a>
</div>
</div>
//Javascript
for(var i = 0; i < classText.length; i++) {
classText[i].innerHTML = arrFiltered[i] || "";
console.log(i + arrFiltered[i]);
classBox[i].onclick = function (value) {
//if a search box is click do:
return function(){
console.log(value);
};
//The below outputs the choice of the user... but how do i put this into a variable?
}(i + 1 + " " + arrFiltered[i]);
}
Thanks,
Ewan

I think your problem is with this
(classText[i].innerHTML = arrFiltered[i] || "";)
not being able to get the innerHTML.
So do something like this in the HTML.
<div id="searchBox">
<div class="searchBoxModule" onclick="firstBox()">
<a class='searchText' id="searchText1"></a>
</div>
then you can easily do:
foo = document.getElementById('searchText1');

Related

Why are my class elements created by javascript undefined when i try to acess them by their class name?

I created a link node with javascript, appended it to the body and gave it a class of 'heart'.
They are visible in the browser and when I inspect, I can see that they have the class name 'heart'.
However, when I try to access them by the method getElementsByClassName and console.log() the resuly, it returns all of them as undefined, as if they don't exist.
Here is my whole code:
body.appendChild(imagebox);
for (var i = 9; i <= 16; i++) {
var imagebox = document.createElement("div");
imagebox.classList.add("imagebox");
var heart = document.createElement("a");
heart.innerHTML = "❤";
heart.classList.add("heart");
imagebox.appendChild(heart);
}
var hearts = document.getElementsByClassName("heart");
console.log(hearts[9]);
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
<div class="imagebox">
<a class="heart">❤</a>
</div>
I get in the console that it is undefined.
What I wanted to mention which kinda complicates whole thing is that I created first 8 elements of class heart in html code, and after that, I created another 24 in javascript and gave them all the same class name.
I think you should insert body.appendChild(imagebox) into the for loop
const body = document.querySelector('body');
for (var i = 9; i <= 16; i++) {
var imagebox = document.createElement("div");
imagebox.classList.add("imagebox");
var heart = document.createElement("a");
heart.innerHTML = "❤";
heart.classList.add("heart");
imagebox.appendChild(heart);
body.appendChild(imagebox);
}
var hearts = document.getElementsByClassName("heart");
console.log(hearts[9]);
Solved the issue,athough i dont understand it,if someone could explain me why this works would be great.
This whole javascript code was inside file all_product.js in that file i this javacript code was wrapped with window.addEventListener("scroll",function(){}),where i created this loop and links.When i put console.log(hearts[9]); at the bottom of the page it didnt work,but when i putted inside window.addEventListener it works as normal.

Find previous <a> element?

SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>

Javascript Selecting child element not working

i m working on adding a FB share button to all my posts.
so i wanted to use the sharer.php? method with all the parameter retrieved from the post.
So my blog structure
<div id='postwrapper'>
<div id='title'>
hello</a>
</div>
<div id='da'>
<span>Posted on </span>
<span class='divider'></span>
<span>By</span>
</div>
<div class='post_content'>$row['post'] gud day</div>
<div id='post_footer'>
<a href=viewpost.php>Continue reading</a>
<a href='#' onClick='fbshare(this)'>Insert text or an image here.</a>
</div>
</div>
My javascript for fbshare function (not complete).
function fbshare(fb) {
var p1 = fb.parentNode;
var p2 = p1.parentNode;
var title = p2.getElementById("title").innerHTML;
alert(title);
}
Everytime i try this it says undefined is not a function
getElementById is a function of the document. Assuming you have more than one post on the page (ids must by unique), try using a class instead:
<div class='title'>
And using getElementsByClassName:
var title = p2.getElementsByClassName("title")[0].innerHTML;
http://jsfiddle.net/AJ9uj/

Get specific data from page and write it to div

I'm building an online store with javascript shopping cart. However, the script doesn't allow printing only one or two values when displaying cart, but I need to do this.
Here's what the cart looks like:
<div class="simpleCart_items">
<div>
<div class="headerRow">
<div class="item-name">Tuote</div>
<div class="item-price">Hinta</div>
<div class="item-decrement">-</div>
<div class="item-quantity">Määrä</div>
<div class="item-increment">+</div>
<div class="item-total">Yhteensä</div>
<div class="item-remove">Poista</div>
</div>
<div class="itemRow row-0 odd" id="cartItem_SCI-1">
<div class="item-name">Teipit</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">3</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-1 even" id="cartItem_SCI-3">
<div class="item-name">Car Speaker -hajuste</div>
<div class="item-price">€4.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€4.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
<div class="itemRow row-2 odd" id="cartItem_SCI-5">
<div class="item-name">Teipit (Musta hiilikuitu)</div>
<div class="item-price">€0.00</div>
<div class="item-decrement"><img src="css/minus.png" alt="minus">
</div>
<div class="item-quantity">1</div>
<div class="item-increment"><img src="css/plus.png" alt="plus">
</div>
<div class="item-total">€0.00</div>
<div class="item-remove"><img src="css/remove.png" alt="Remove">
</div>
</div>
</div>
</div>
NOTE: The cart is written via javascript so it isn't visible in page source, only in inspect mode of the browser.
So how would I gather the item-name, item-priceand item-quantity?
I've tried this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name + price + quantity;
$('#items').html(data);
But this won't actually do anything.
When doing this -> $('.item-name');
You are just capturing the element as object but not the value.
Now that you got your element as object, you need to extract the value and, in this case, your element object is a div so you can try .text() or .html() (to get the text or html inside the div).
(For this situation I will use text() cause you are working just with values and there is nothing related to html)
Try this:
var name = $('.item-name');
var price = $('.item-price');
var quantity = $('.item-quantity');
var data = name.text() + price.text() + quantity.text();
$('#items').html(data);
Better solution:
This will make clickable the div in which you have the product and match the cartItem_SCI pattern.
So, when user clicks any of the elements of your cart, you will get the name, price and quantity values that will be attached to the $('#items') div using append() method instead of html() (because using this will replace the product information each time the user clicks a div)
$(document).ready(function() {
$('div[id^="cartItem_SCI-"]').css({ cursor:'pointer' });
$('div[id^="cartItem_SCI-"]').click(function() {
var name = $(this).find('.item-name');
var price = $(this).find('.item-price');
var quantity = $(this).find('.item-quantity');
var data = name.text() + ' - ' + price.text() + ' - ' + quantity.text();
$('#items').append(data + '<br/>');
});
});​
You are just getting a reference to the class, add .html() to get the inner html of the element that the class applied to.
var name = $('.item-name').html();
For one item you can get like this.But since you have multiple items make one object like this .
var item={};
$('.item-name').each(function(){item.name=$(this).html()});
$('.item-price').each(function(){item.price=$(this).html()});
$('.item-quantity').each(function(){item.quantity=$(this).html()});
var data='';
for(var i=0;i<item.length;i++)
{
data+=item[i].name+item[i].price+item[i].quantity;
}
$('#items').html(data);

Get content id (greatest) by clicking button on it Jquery

I need to get comment id when clicking to report button (I want to get comment-6)
Now when I click 'report' it show a modal box with form.
<div class="comment-box medium-comment" id="comment-6">
<div class="photo-box">
<img src="img/samples/photo_1.jpg" alt="" class="photo rounded"/>
</div>
<div class="avatars">
<a href="#" title="">
<img src="img/samples/followers/1.jpg" alt=""/>dearskye
</a>
<span>commented on</span>
<a href="#" title="">
<img src="img/samples/followers/2.jpg" alt=""/>Antony12
</a>
</div>
<div class="comment rounded">
<div class="bg-tl"></div>
<div class="text">Happy golden days of yore
Happy golden days of yore Happy golden days
of yore</div>
<div class="buttons">
REPORT
</div>
</div>
<div class="cinfo">
2 дня назад
</div>
<div class="both"></div>
</div>
clicking to
REPORT
call jquery
jQuery('a.report').bind('click', function(event) {
showModalWindow('report-window');
});
and function is
function checkReportForm(form)
{
var result=true;
var select=jQuery("#report-window select");
var textarea=jQuery("#report-window textarea");
if(textarea.hasClass('default'))
{
//Save placeholder
textarea.data('placeholder', textarea.text());
textarea.toggleClass('default');
}
textarea.attr('class','rounded');
if(select.val()==0)
{
if(textarea.val()==''||textarea.val()==textarea.data('placeholder'))
{
result=false;
textarea.toggleClass("alert");
}
}
if(result)
{
closeModalWindow('report-window');
}
I tried to do it but nothing. I suppose it is possible otherwise will think to change code. I hope someone will help me.
You can use closest to get the closest element which cotains the required class and get its id. Try this.
jQuery('a.report').click(function() {
var $commentBox = $(this).closest(".comment-box");
var id = $commentBox.attr('id').replace('comment-', '');
alert(id);//It will alert the comment id
//Store the comment id in report window
$('#report-window').data('commentid', id);
});
Now use $('#report-window').data('commentid') to get the current comment id inside checkReportForm method.
If i understand you correctly, the following should fetch the comment id for you:
$(".report").click(function() {
var $box = $(this).parents(".comment-box");
var commentId = $box.attr("id").replace("comment-", "");
// commentId contains 6
// call showModalBox and do whatever you want
});
When this context is your report link:
var id = Number(this.parentNode.parentNode.id.substring(8));

Categories