I am having an issue with getting the value of an ID element of the item that is dynamically generated from the data obtained from the database. I have a query SELECT ItemID, ItemName, ItemImageName FROM Items. Than I have the following code that will generate ID for each <div> for all rows returned from the database by concatenating the value of ItemID to each ID name.
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch()
<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>
}
This should return a similar result to this for an item with ItemID=002:
<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>
Then I want to be able to click an image with an ID=Image002 and I want to get a value of ItemID with the getElementById("ItemID").innerHTML. I have the following code:
var itemID = document.getElementById("ItemID").innerHTML;
$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;
console.log(itemID);
This however returns itemID as undefined. Any help would be greatly appreciated!
<div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
<div id=ItemID001> 001 </div>
<div id=ItemName001> SomeNameOfItem001" </div>
<div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
<div id=ItemID002> 002 </div>
<div id=ItemName002> SomeNameOfItem002" </div>
<div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
<div id=ItemID003> 003 </div>
<div id=ItemName003> SomeNameOfItem003"> </div>
<script>
$(document).ready(function () {
$(".itemImage").click(function () {
var imgID = $(this).prop('id').replace("Image", "");
// you can directly use value imgID variable if its same. or you
//can use from ItemID inner html
var yourValue = $("#ItemID" + imgID).html();
alert(yourValue);
})
});
</script>
getElementById("ItemID").innerHTML returns undefined, because it is undefined. The correct id is ItemID002. You need to be able to tell which it is.
First, change your PHP to create HTML like this.
<div id="ItemID002" onclick="clicked(002)" />
Then, go to your Javascript and create this function.
function clicked(id){
var itemID= document.getElementById("ItemID"+id).innerHTML;
console.log(itemID);
}
Lastly, you're PHP creates <div id="ItemID"002>, you need to fix that by changing it from <div id= "ItemID" .$ItemID> $ItemID to <div id='ItemID.$itemId'>
EDIT: Also, I'd like to point out that in some places in your example, you forgot to use quotes when specifying the value of an attribute in HTML. I would recommend you fix that.
Good luck!
Alternatively you can achieve this by javascript only. So you don't need to change markup or PHP.
Here is a sample fiddle https://jsfiddle.net/L3bwfyve/
The key part is extraction of part of id of clicked element:
var itemIdPart = e.target.id.substr(5);
Be sure to check for nulls in e.target id etc...
Personally I would consider this solution a bit hacky... but you ask for javascrit, you get it ;-)
Related
i have a DOM Element
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
I want to get the HTML like $('.list-item').html();
Then i want to fill parts like data-attributes and content with own variables so i can get for example this:
<div class="list-item">
<div class="name">NAME CONTENT</div>
<div class="id" data-id="123456">CONTENT</div>
Link
</div>
Then i want to store that as string in a varibale like
var htmlCode = '<div class="list-item">.....';
The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!
You can use .clone() to clone your div and then use .attr() to change attr from id class .
Demo Code :
var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
You can use this
<script>
var html = $('.list-item').html();
console.log(html);
var list = $('<li></li>')
$('.list-item').children().each(function(index,elem){
$(list).append($(elem).clone());
})
$(list).children().each(function(i,e) {
$(e).data("id","1234")
$(e).html("ll");
})
console.log($(list).children());
</script>
Thank you all. With your help i got this solution:
var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');
So $code is my varibale wich stores the html as string without changing the DOM Element :)
I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"
I try convert simple string to HTML object for process it with jQuery.
My code:
var old_code_text = $(invoice_template_id).html();
console.log("old text ="+old_code_text);
old_code_text=$(old_code_text);
console.log("old text2 ="+old_code_text.html());
My first alert show me:
old text =<div id="template_invoice">
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
....
</div>
</div>
But my second alert show me :
old text2 =
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
Then I use old_code_text like it:
old_code_text.find("#product_invoice_table tbody").empty();
I dont understand where is div with id template_invoice?
When I parse string this div always deleted.
Thanks.
wrap the container in a dummy p element tag and you will get the container HTML also
var old_code_text = $("#template_invoice").wrap("<p/>").parent().html()
console.log("old text ="+old_code_text);
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
And then the JS/jQuery
function readMore() {
var subID = event.target.id;
var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");
alert(newTarget.id);
}
At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.
jsfiddle: https://jsfiddle.net/dr0f2nu3/
To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id
function readMore() {
var subID = event.target.id;
var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
<div class="articleContent">
<h1>header</h1>
<p class="articlePara" id="one"></p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">click
</div>
</div>
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.
With querySelector you get the element and then with parentElement you can retrieve the parent of that element.
function readMore(el) {
var articleFooterId = el.id;
var articlePara = document.querySelector(".articleContent #"+articleFooterId);
var articleContent = articlePara.parentElement;
console.log('articleFooter', articleFooterId);
console.log('articlePara', articlePara);
console.log('articleContent', articleContent);
}
In your html you can return the 'this' object back to the function by doing readMore(this).
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
jsfiddle
if you're using Jquery:
$(function () {
$('div.articleFooter').click(function () {
var para = $(this).prev().find('p.articlePara').text();
alert('T:' + para);
});
})
$('.articleFooter').click(function() {
var b=subId; //can be any
var a="p[id="+b+"]"+"[class='articlePara']";
$(a).something;
});
You have forgotten to pass in event as parameter in your onclick= call in html.
In your javascript, you need to include event in the parenthesis as well.
window.readMore = function(event) {...}
if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.
If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:
newtarget = $("#one.articlePara");
You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.
In my use case, I am trying to get value from dynamically generated hidden field in JQuery. When I click the button for that iteration I should get the value for the hidden field belongs to that iteration. But I am not able to get it. It is giving the value as 'undefined'
HTML:
<div class="comment-list-new" style= "max-height: 660px !important;overflow-y: scroll;">
<h5>Discussion Board</h5>
<ol>
{{ if .ViewData.Questions }}
{{ range .ViewData.Questions }}
<li>
<p id="question_id" class="question_id_val" hidden>{{.QuestionId}}</p>
<div class="q-comment">
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p id="quest_title">{{.QuestionTitle}}</p></h6>
</div>
<p id="quest_text">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<img src="/resources/img/team-small-2.png" />
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
</li><!--end of individual question-->
{{ end }}
{{ end }}
</ol>
</div><!--end of comments list-->
JS:
$('.questiondiv').on('click', '.submitanswerbutton', function() {
console.log("In submit button");
var question_id = $(this).closest('.question_id_val').val();
var answer_text = $('.answertext_val').val();
console.log(question_id);
console.log(answer_text);
$.getJSON("/submitanswer?question_id="+question_id+"&answer="+answer_text, function(data) {
console.log("answer Response"+data);
newQuestion = "<li><div class='q-comment'><div class='qanda' id='questionarea' name='questionarea'><div><div id='topic' class='upvote pull-left'><a class='upvote'></a><span class='count'>0</span><a class='downvote'></a></div><div ><div class='qanda-info'><h6><p id='quest_title'>"+title+"</p></h6></div><p id='quest_text'>"+desc+"</p></div></div ><div class='qanda-info'><div class='user-info'><img src='/resources/img/team-small-2.png' /></div><h6>Chip Mayer</h6><span class='date alt-font sub'>September 17 2014</span><a id='answertext' name ='answertext' type='submit' class='link-text'>Answer</a></div></div></div></li>";
$('ol').append(newQuestion);
});
});
In the above code I am trying to get the value for the hidden field question_id_val.
Could anyone help me with this?
Use closest() to get a reference to the outer container (li) and then use find() method to get the hidden field.
var question_id = $(this).closest('li').find('.question_id_val').val();
val() method works for usually input form fields(textbox,hidden fields etc..) .So you need to make sure your element is a valid form field in your page.
<input type="hidden" id="question_id" class="question_id_val" />
Or if you want to keep your p tag as it is, Use the html() or text() method to get the content of the p tag.
var question_id = $(this).closest('li').find('.question_id_val').text();
Remember, these method returns the text/html of all child content as well. So make sure to use it wisely.
val() should be used primarily in select, textarea and input elements.
For getting the inner text use html() or text()
var question_id = $(this).closest('.question_id_val').html();
or
var question_id = $(this).closest('.question_id_val').text();
If you know a css selector id or class I don't see problem why you can't do something like this:
var question_id = $('#question_id').text();
Or
var question_id = $('.question_id_val').text();