getElementByID for Dynamically generated ID Elements
<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>
How do I use getElementById on dynamically created inputs?
Okay so I found a solution. Apparently you can't use getElementById(checkboxId)
to get the checkbox states. You have to create an array using getElementsByTagName("input")
and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!
JavaScript - getElementById on dynamically added elements
You seem to have an extra space in the id
string you are testing for. Since #{...}
is an evaluated value, it shouldn't be in quotes in the first place.
Also, why use the back-tick string syntax here?
if (!!document.getElementById(`#\\3${playerId} `) == false) {
And, getElementById()
already knows to look for id's so adding the #
is going to search for elements that actually start with #
.
Finally, if the element with that id
does exist, it will return a "truthy" value that when converted to a Boolean, will convert to true
, so there is no need to force a Boolean conversion (with !!
) and then check to see if that is false
.
That line can be rewritten to:
if (!document.getElementById(${playerId})) {
Accessing dynamically generated DIV using document.getElementByID
document.getElementById
gets an element, by its ID, from the document.
You haven't added the div to the document yet, so it can't be found.
That said you already have the element! There's no need to search for it, in the document or anywhere else.
newDiv.innerHTML = html2;
getElementById Where Element is dynamically created and appended to DOM
I fixed my problem and I basically just mix jquery and javascript together. Yeah I know bad practice whatnot but for now it works flawlessly and that's what matters for the team.
So in short that's the end result. Nothing magic but it did it for me :
<script src="js/firstscript.js"></script>
$(document).ready(function(e){
$('.button').click(function(e){
e.preventDefault();
var userCurrency = 'usd';
$('<input>').attr({
type: 'hidden',
id: 'userCurrency',
name: 'userCurrency',
value: userCurrency
}).appendTo('#payment-form');
})
})
//vanilla javascript code below
var amountCurrency = userCurrency;
How do I get a dynamically created ID?
Your problem is that id
is unique and can only be assigned once to a element, like so:
<p id="paragraph"> This is legal </p>
<p id="paragraph"> This is illegal - It is no longer unique </p>
<p class="paragraph"> This is legal </p>
<p class="paragraph"> This is legal </p>
You can access the currently clicked class by using $(this)
like so:
$('.paragraph').click(function() {
$(this).html('See, totally legal.');
});
See this example to see this in use.
Your solution needs to add an onclick()
method to a button
. This then gets the parent()
form. You can then find()
the class and get the val()
from the form data.
Your form was also submitting the action. You need to have a <button>
of type button
so it does not submit the action. This must also be a class since it will not be unique if you're multiply creating them.
Here is a working example to just re-add your AJAX request too.
$(document).ready(function() { $('.submit-btn').click(function() { var elements = { 'userid': $(this).parent().find('.userid').val(), 'productid': $(this).parent().find('.productid').val(), 'collection': $(this).parent().find('.collection').val(), 'wish': $(this).parent().find('.wish').val() };
console.log("User ID: " + elements.userid); console.log("Product ID: " + elements.productid); console.log("Collection: " + elements.collection); console.log("Wish: " + elements.wish);
// TODO: Add your AJAX request using these elements });});
button { background: #0084ff; border: none; border-radius: 5px; padding: 8px 14px; font-size: 15px; color: #fff; cursor: pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This will be generated by PHP -->
<form method='POST'> <input hidden class="userid input-box" value="1"> <input hidden class="productid input-box" value="1"> <input hidden class="collection input-box" value="1"> <input hidden class="wish input-box" value="1"> <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button></form>
<!-- This will be generated by PHP --><br />
<form method='POST'> <input hidden class="userid input-box" value="2"> <input hidden class="productid input-box" value="2"> <input hidden class="collection input-box" value="2"> <input hidden class="wish input-box" value="2"> <button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button></form>
document.getelementById doesn't work on dynamically generated divs
Since you already creating the div in js, why not hold the reference then?
function makeDiv() {
var quizDiv=document.createElement("div");
document.body.appendChild(quizDiv);
return quizDiv;
}
function createInputBox(quizDiv,boxId) {
// var quizDiv = document.getElementById("quizDiv");
quizDiv.innerHTML = "<input type='text' id='" + boxId + "'>";
}
var quizDiv=makeDiv();
createInputBox(quizDiv,1);
Dynamically generated html, document.getElementByID returns null
After figuring out that passing an <asp:button/>
as a string wasn't going to work, I took an alternative approach.
In populateMemberTable()
I added an href attribute to the first column in each row
var href = true;
foreach(DataColumn column in new_dt.Columns)
{
html.Append("<td>");
if (href)
{
href = false;
html.Append("<a href='/default.aspx?guid=" + Session["guid"] + "&membid=" + row[column.ColumnName] +"'>");
html.Append(row[column.ColumnName]);
html.Append("</a></td>");
}
else
{
html.Append(row[column.ColumnName]);
btnValue.Append(row[column.ColumnName]);
btnValue.Append(";");
html.Append("</td>");
}
}
And then I saved the membId as a session variable in Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
//save guid (http://url.com?guid=xxxxxx) as session variable
Session["guid"] = Request.QueryString["guid"];
var membId = Request.QueryString["membid"];
if (membId != null)
{
Session["membid"] = membId;
}
}
It might not be the most elegant solution, but it got me what I needed and was straightforward to implement. Thanks for the input everyone!
Related Topics
Move Items in Ul Li Up and Down
How to Reload the Page Without the Query Parameters
How to Store Data After Refreshing the Web Page
Why Does This Onclick Event Not Work in an HTML Iframe
Open a Component in New Window on a Click in React
Sequelize How to Check If Entry Exists in Database
How to Get Field Value on Change for Formitem in Antd
How to Use If Statement Inside Json
How to Prevent Form to Reload Page After Onsubmit
Html Input File Selection Event Not Firing Upon Selecting the Same File
Transforming Null into Empty String in JavaScript
How to Allow Only English Letters in Input Fields
How to Reload a Page With React-Router
Loading Screen Gets Stuck While Processing Http Request
Creating a Json Dynamically With Each Input Value Using Jquery
How to Make a Bot Delete Messages After a Certain Time Period