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();
Related
I have a very large HTML that contains lots of divs with the same name, I want a way to only filter or extract that value from that div.
Here is an example:
<td class="last">
<div class="container-relative">
<div class="name" title=""User" <John Appleseed>"></div>
<div class="date">9/17/2019</div>
<div class="tool"></div>
</div>
</td>
I need to extract only what's between <John Appleseed>, in this case is 'John Appleseed'.
You could use querySelectorAll to take all the elements with class name, then get the title attribute with getAttribute, and finally use a regular expression to match text between <>.
document.querySelectorAll('.name').forEach(item => {
let title = item.getAttribute('title');
console.log(title.match(/\<.*\>/));
});
<td class="last">
<div class="container-relative">
<div class="name" title=""User" <John Appleseed>"></div>
<div class="date">9/17/2019</div>
<div class="tool"></div>
</div>
</td>
var divs=[];
for(i=0,j=0,obj=document.getElementsByClassName("name");i<obj.length;i++)
if(obj[i].title.includes("John Appleseed") &&
/* obj[i].title.split("\"")[2].trim()=="<John Appleseed>" && */
obj[i].tagName.toLowerCase()=="div"){
divs[j++]=obj[i];
}
console.log(divs);
separate your div using div ID. Then get your respective div using that value of ID. Then in javascript you can use getElementByID.
You can use Xpath,
.//div[contains(#class, 'Test')]
Then extract you required text from it.
I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());
I have a problem here: I want to get the ID of commentUserId in the hidden input into the javascript file to put into an ajax. But all I got was the value of the first row.
This is the design code
<c:forEach items="${commentList}" var="items">
<div class="media" style="padding: 10px 0">
<div class="media-body">
<input type="hidden" id="commentUserId" name="commentUserId" value="${items.accountId.accountId}"/>
<a id="${items.commentId}" name="btnReportComment" class="btn btn-report">\Report</a>
</div>
</div>
and this is code in javascript
$('a[name=btnReportComment]').click(function() {
var commentUserId = $('#commentUserId').val();
alert(commentUserId);})
Try to update your click event like:
$('a[name=btnReportComment]').click(function() {
var commentUserId = $(this).closest('.media-body').find('[name="commentUserId"]').val();
alert(commentUserId);
})
Here, we are using this to get the reference of click btnReportComment.
Then we find the commentUserId input w.r.t to it using closest & find.
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 ;-)
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.