This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
After creating a batch of Html nodes, The link does not work!
How can I fix it?
Javascript Codes:
var nnn = '<div class="media mt-3 w-100" id="commentNode_0000">' +
'<a class="pr-0" href = "#" >' +
'<img class="mr-3" src="/images/comment1.png" alt="x">' +
'</a>' +
'<div class="media-body w-100">' +
'<h5 class="mt-0 mb-1">User</h5>' +
'<div id="collapse_0000" class="">' +
'<div id="cardId_0000" class="card">' +
'<p>TEST TEST</p>' +
'</div>' +
'<div class="comment-meta" id="commentId_0000">' +
'<span><input id="deleteC_24_20" type="submit" class="submitLink" value="delete"></span>' +
'<span><input id="editC_24_20" type="submit" class="submitLink" value="edit"></span>' +
'<span>' +
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>' +
'</span>' +
'<div id="replyComment_0000" class="collapse"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$(collapseId).append(nnn);
Exactly this line of code:
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>'
I expect this event to fire after clicking the tag that I have created dynamically.
But it doesn't work!
$("a[id^='replyC_']").on("click", function (event) {
var nodeId = event.target.id;
});
var collapseId = document.getElementById('collapseId')
var nnn = '<div class="media mt-3 w-100" id="commentNode_0000">' +
'<a class="pr-0" href = "#" >' +
'<img class="mr-3" src="/images/comment1.png" alt="x">' +
'</a>' +
'<div class="media-body w-100">' +
'<h5 class="mt-0 mb-1">User</h5>' +
'<div id="collapse_0000" class="">' +
'<div id="cardId_0000" class="card">' +
'<p>TEST TEST</p>' +
'</div>' +
'<div class="comment-meta" id="commentId_0000">' +
'<span><input id="deleteC_24_20" type="submit" class="submitLink" value="delete"></span>' +
'<span><input id="editC_24_20" type="submit" class="submitLink" value="edit"></span>' +
'<span>' +
'<a id="replyC_24_20" class="" role="button" data-toggle="collapse" href="#replyComment_0000" aria-expanded="false" aria-controls="collapseExample">reply</a>' +
'</span>' +
'<div id="replyComment_0000" class="collapse"></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$(collapseId).append(nnn);
$("a[id^='replyC_']").on("click", function (event) {
var nodeId = event.target.id;
console.log(nodeId);
});
<div id="collapseId"></div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
it works fine :)
Related
I'm trying to created a dynamic form in rails with a little bit of javascript I have a problem I only get one row in the output when using pry apparently it's because I have the same params for every field input since I use jQuery .clone, maybe someone has struggled with something similar can share some knowledge, how to dynamically add index to params in this form with javascript ?
#extends('Admin.master')
#section('content')
<div class="p-5">
<h3><i class="fas fa-cog ml-2"></i>Setting</h3><hr>
<form action="{{ route('settings.update', $setting->id) }}" method="POST" >
#csrf
#method('PUT')
<div id="showDynamic">
</div>
</form>
</div>
#endsection
#section('script')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
let count = 1;
$('.add').click(function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary" id="add">Add</a>\n' +
'<a class="btn btn-danger" id="delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
#endsection
1st id must be unique .. So change id="add" and id="delete" to classes class="btn btn-primary add"
2nd event-binding-on-dynamically-created-elements After changing the id to class use $(document).on('click' , '.add' , function(){ //code here })
Your code should be
<script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
</script>
$(document).ready(function(){
let count = 1;
$(document).on('click' , '.add' , function(){
count++;
dynamic(count);
});
dynamic(count);
function dynamic(number) {
var html = '' +
'<div class="row">\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Name">\n' +
'</div>\n' +
'<div class="col-md-4">\n' +
'<input class="form-control" placeholder="Link">\n' +
'</div>\n' +
'<div class="col-md-2">\n' +
'<a class="btn btn-primary add">Add</a>\n' +
'<a class="btn btn-danger delete">Delete</a>\n' +
'</div>\n' +
'</div>';
$('#showDynamic').append(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showDynamic"></div>
I have the following javascript that dynamically add textboxes together with a remove button to a div. How can I using the remove button delete the content of the row being selected to delete?
<script type="text/javascript">
function GetDynamicTextBox(value) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var div = document.createElement('DIV');
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("");
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(div) {
//document.getElementById("divcontent").removeChild(div.parentNode); // this does not work
iterateBoxesAndSetUniqueIds();
}
function iterateBoxesAndSetUniqueIds() {
// Set unique names of each textbox
var children = document.getElementById("divcontent").children;
for (i = 0; i < children.length; i++)
{
var el = children[i];
el.name = 'events[' + i + '].Key'; //
el.id = 'events[' + i + '].Key';
el.name = 'events[' + i + '].Value.StartDate';
el.id = 'events[' + i + '].Value.StartDate';
el.name = 'events[' + i + '].Value.EndDate';
el.id = 'events[' + i + '].Value.EndDate';
el.name = 'events[' + i + '].Value.Description';
el.id = 'events[' + i + '].Value.Description';
}
}
</script>
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
UPDATE
I added a snippet for updating the id for each textbox, but obviously I am doing something wrong here. Can anyone help with this too?
I assume you want to remove the entire row, so heres how to do that.
You almost had it, since you pass (this) in the onclick, it means we have a direct reference to the button that was clicked. From there, we can get its grandparent by using .parentNode twice (since the first parent is .col-md-2) and then use the remove() function.
div.parentNode.parentNode.remove()
function GetDynamicTextBox(value) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var div = document.createElement('DIV');
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("");
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(div) {
div.parentNode.parentNode.remove()
}
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
function GetDynamicTextBox(value, uniquedId) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(\'' + uniquedId +'\')"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var uniquedId = Math.floor(Math.random() * 100) + '_unique';
var div = document.createElement('DIV');
div.setAttribute("id", uniquedId);
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("", uniquedId);
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(uniquedId) {
var elem = document.getElementById(uniquedId);
return elem.parentNode.removeChild(elem);
}
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
<script type="text/javascript">
function GetDynamicTextBox(value, uniquedId) {
return('' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Key" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.StartDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.EndDate" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <input type="text" name="events[0].Value.Description" value=""/>' +
'</div>' +
'<div class="col-md-2">' +
' <button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(\'' + uniquedId +'\')"><i class="fa fa-angle-right"></i> Remove</button>' +
'</div>');
}
function AddTextBox() {
var uniquedId = Math.floor(Math.random() * 100) + '_unique';
var div = document.createElement('DIV');
div.setAttribute("id", uniquedId);
div.className = "form-group";
div.innerHTML = GetDynamicTextBox("", uniquedId);
document.getElementById("divcontent").appendChild(div);
}
function RemoveTextBox(uniquedId) {
var elem = document.getElementById(uniquedId);
return elem.parentNode.removeChild(elem);
}
</script>
<button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button>
<div id="divcontent">
</div>
I get an really strange error with my dynamic form field script. It is not so easy to explain, but I will do my best.
I have a HTML form with java script to add
1 select field
2 text-fields &
9 checkboxes
dynamically by clicking a link.
Every dynamic form-set create a own entry in my mysql db.
The one select field and the two text-fields are insert correctly the data into my db.
But with the 9 checkboxes, there is a mistake.
For Example: IF I create two form-sets AND i will check the each 1st check-boxes, the database entry is correctly
BUT
IF I create two form-sets AND i will check at the first form-set Checkbox 1 and on the second form-set Checkbox 2, my db-entry write the 1st and the 2nd checkbox-entry in the first (!!!) db-entry. There is no entry for the 2nd Checkbox in the second db-entry.
Maybe my screenshot will it make more understandable.
Here is my script. I really hope anybody can help me. Iam looking so long for a solution, but...
<?php
include('dbconnection.php');
?>
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="theme/scripts/jquery.js"></script>
<script type="text/javascript" src="theme/scripts/jqueryui.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<select name="artikel[]' + '">'
+ '<option value="test1">' + 'test1' + '</option>'
+ '<option value="test2">' + 'test2' + '</option>'
+ '</select><br /><br />'
+ '<b>Beschreibung oder Anzahl:</b><br>'
+ '<input name="beschreibung[]' + '" type="text" class="login-username" /><br />'
+ '<b>Preis in €:</b><br>'
+ '<input id="preis_' + counter + '" name="preis[]' + '" type="text" class="login-username" /><br />'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Aus-/Einbau<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Aus und Einbauarbeiten<br>" id="1a_' + counter + '" name="ausein[]' + '" />'
+ '<label for="1a_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Instandsetzung<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Teil instand gesetzt<br>" id="2b_' + counter + '" name="instand[]' + '" />'
+ '<label for="2b_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Teillack<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Teillackierung<br>" id="3c_' + counter + '" name="rep[]' + '" />'
+ '<label for="3c_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Farbangleich<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Farbtonangleichung<br>" id="4d_' + counter + '" name="farb[]' + '" />'
+ '<label for="4d_' + counter + '"></label>'
+ '</div>'
+ '</span>'
// + '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Neuteil<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Neuteil wurde verbaut<br>" id="5e_' + counter + '" name="neu[]' + '" />'
+ '<label for="5e_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Beilack.<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Beilackierung<br>" id="6f_' + counter + '" name="spot[]' + '" />'
+ '<label for="6f_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Finisch<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Finischarbeit<br>" id="7g_' + counter + '" name="finisch[]' + '" />'
+ '<label for="7g_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Delle Rep.<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value=" Dellen instand gesetzt<br>" id="8h_' + counter + '" name="delle[]' + '" />'
+ '<label for="8h_' + counter + '"></label>'
+ '</div>'
+ '</span>'
// + '<div style="float: left; width: 20px;"> </div>'
+ '<span style="float: left; width: 70px; text-align: center;">'
+ 'Lederrep.<br>'
+ '<div class="roundedTwo">'
+ '<input type="checkbox" value="Lederreparatur<br>" id="9i_' + counter + '" name="leder[]' + '" />'
+ '<label for="9i_' + counter + '"></label>'
+ '</div>'
+ '</span>'
+ '<div class="decoration"></div>'
+ '<input id="renr_' + counter + '" name="renr[]' + '" type="hidden" value="' + '<?php echo $renr ?>' + '" />'
+ '<input id="datum_' + counter + '" name="datum[]' + '" type="hidden" value="' + '<?php echo $datum ?>' + '" />'
+ '<input id="jahr_' + counter + '" name="jahr[]' + '" type="hidden" value="' + '<?php echo $jahr ?>' + '" />'
+ '<input id="id1_' + counter + '" name="id1[]' + '" type="hidden" value="' + '<?php echo $id1 ?>' + '" />'
);
});
});
</script>
</head>
<body>
<?php
$id = $_GET['id'];
if (isset($_POST['submit_val'])) {
if ($_POST['artikel']) {
$post_count = count($_POST['artikel']);
for ($i=0;$i<$post_count;$i++) {
$values1 = mysql_real_escape_string($_POST['artikel'][$i]);
$values2 = mysql_real_escape_string($_POST['preis'][$i]);
$values3 = mysql_real_escape_string($_POST['beschreibung'][$i]);
$values4 = mysql_real_escape_string($_POST['ausein'][$i]);
$values5 = mysql_real_escape_string($_POST['instand'][$i]);
$values6 = mysql_real_escape_string($_POST['rep'][$i]);
$values7 = mysql_real_escape_string($_POST['farb'][$i]);
$values8 = mysql_real_escape_string($_POST['neu'][$i]);
$values9 = mysql_real_escape_string($_POST['spot'][$i]);
$values10 = mysql_real_escape_string($_POST['finisch'][$i]);
$values14 = mysql_real_escape_string($_POST['delle'][$i]);
$values15 = mysql_real_escape_string($_POST['leder'][$i]);
$values11 = mysql_real_escape_string($_POST['datum'][$i]);
$values12 = mysql_real_escape_string($_POST['jahr'][$i]);
$values13 = mysql_real_escape_string($_POST['renr'][$i]);
$values16 = mysql_real_escape_string($_POST['id1'][$i]);
$query = mysql_query("INSERT INTO rechnung (artikel,preis,beschreibung,ausein,instand,rep,farb,neu,spot,finisch,delle,leder,datum,jahr,renr,kd) VALUES ('$values1', '$values2', '$values3', '$values4', '$values5', '$values6', '$values7', '$values8', '$values9', '$values10', '$values14', '$values15', '$values11', '$values12', '$values13', '$values16')", $conid );
}
}
echo "<h3><strong>" . count($_POST['artikel']) . "</strong> Artikel hinzugefügt</h3>";
//mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<form method="post" action="?id=<?php echo $id; ?>">
<div id="container">
<div id="neu"><p id="add_field"><img src="plus.png" width="30px"><b>Artikel hinzufügen</b></p></div>
<div class='decoration'></div>
</div>
<input type="submit" name="submit_val" value="Weiter zu Fahrzeugdaten" class="button button-blue"/>
</form>
<?php } ?>
</body>
The problem is caused by the name of the checkboxes.
You use the same logic for assigning names to all your form controls regardless of tgeir type: controlname[]. Yes, as a result of [] at the end php will interpret these parameters as arrays. So far, so good.
However, in html if a checkbox is not checked, then it is not a successful control, hence it will not be submitted to the server.
If the 2nd checkbox is not checked in the 1st record, then the empty vslue will not be sent to the server. If subsequently the 2nd checkbox is checked in the 2nd record, then it will be the 1st value in the order of the 2nd checkboxes in the submitted values.
It's a lot easier to picture this if you use print_r to print the $_POST in your php code.
The solution is to include an index in the name of the checkboxes to indicate which record they belong to. So instead of using ausein[] as name, use ausein[0], ausein[1], etc as name.
The Solution from #Shadow was helpful.
But i have to set the default count from
var counter = 0;
to
var counter = -1;
This solve my problem.
I have a JavaScript string called _categoryItemDivTemplate that defines HTML markup, including a <div> with class="MakeTopLevelCategory".
I thought I can remove that <div> with the following code:
item = $(_categoryItemDivTemplate);
if (!isTopLevel)
item.remove('div.MakeTopLevelCategory');
But it has no effect.
Am I missing something? Is it necessary to first add the item to the DOM?
EDIT:
Here's the template from the code:
var _categoryItemDivTemplate =
'<div class="CategoryItem" style="clear:both;">'
+ '<div class="CategoryHeader">'
+ '<img src="/images/plus.gif" class="Icon"/>'
+ '<img src="/images/icn_folder.gif" class="Icon"/>'
+ '<span class="Title"> </span>'
+ '<div style="float:right; font-size: 11px;" class="CategorySelector">'
+ '<div class="DeleteCategory" title="Delete this Category"> </div>'
+ '<div class="EditCategory" title="Rename this Category"> </div>'
+ '<div class="MakeTopLevelCategory" title="Make this Category a Top-level Category"> </div>'
+ '<div class="MoveSubcategory" title="Move this Category"> </div>'
+ '<div class="SubcategoryMarker AddSubcategory" title="Add a new Subcategory to this Category"> </div>'
+ '<div class="PackageCostingMarker AddPackage" title="Add a new Package to this Category"> </div>'
+ '<div class="ProductCostingMarker AddProduct" title="Add a new Product to this Category"> </div>'
+ '<div class="NarrativeMarker AddArticle" title="Add a new Article to this Category"> </div>'
+ '</div>'
+ '</div>'
+ '<div class="CategoryItems" style="display: none;">'
+ '</div>'
+ '</div>';
Removing it from the object does not removes it from the string, if you want to remove it from the string then you need to replace the string with the object sources so try
item = $('<div />', {html:'_categoryItemDivTemplate'});
if (!isTopLevel) {
item.find('div.MakeTopLevelCategory').remove();
}
I have a textarea and a button. The button submits the data to a page through AJAX through a function. When the button is clicked it calls a function that takes in 3 parameters for this question only one of them is necessary.
Let's look at the code to understand more clearly:
var offers = <? php echo PostOffer::GetOffers($_GET["id"]); ?> ;
for (var i = 0; i < offers.length; i++) {
var date = offers[i].Date.split(" ");
document.write('<div class="row-fluid offer">' +
'<div class="span2">' +
'<img class="profile_picture" src="' + offers[i].Picture_Path + '" />' +
'</div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="username">' +
'<p style="font-weight: bold;">' + offers[i].Name + '</p>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>' +
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
'<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="date">' +
'<p class="pull-right"><strong><span class="muted">Offered on: </span></strong>' + date[0] + '</p>' +
'</div>');
if (offers[i].Username == "<?php echo $_SESSION["
username "]; ?>") {
document.write('<div class="controls pull-right">' +
'Edit ' +
'Delete | ' +
'</div>');
}
document.write('</div>' +
'</div>' +
'</div>' +
'<hr />');
}
The important part is:
...
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>' +
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
'<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
...
The most important is:
...
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ' +
...
In the onclick of that button the function document.getElementById("edited_content") returns a null value. I've tried logging it to the console it prints null. Why is that happening?
Any help would be appreciated!
Because at the point you call document.getElementById("edited_content"), edited_content does not exist.
You are creating it by appending a string, so you'd need to do something like:
// Add the first part
document.write('<div class="row-fluid offer">' +
'<div class="span2">' +
'<img class="profile_picture" src="' + offers[i].Picture_Path + '" />' +
'</div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="username">' +
'<p style="font-weight: bold;">' + offers[i].Name + '</p>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>');
// Now we can get edited_content
document.write('<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick=\'editPostOffer("<?php echo $_GET["id"]; ?>","' + offers[i].Offer_ID + '","' + document.getElementById("edited_content") + '");\'>Save Edits</button> ');
// Write the rest of the HTML
document.write('<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="date">' +
'<p class="pull-right"><strong><span class="muted">Offered on: </span></strong>' + date[0] + '</p>' +
'</div>');
P.S. You tagged the question with jQuery - there are much better ways of doing what you are trying to achieve. Better still, use a templating engine.