Bootstrap buttons not getting highlighted when clicked - javascript

I have an app with 3 buttons, the 3 buttons make an AJAX call to retrieve some data and redraw a table with the data. However when clicked the button should be kept highlighted so the user knows which data they are viewing.
This is the JS code that calls the Web API method:
iniciativasEstrategicas.GetVistaActividades = function (filtro) {
var idObjetivoValue = sessionStorage.idObjetivoValue;
$('#tab_vista1').html('<br><br><br><img class="loadImage" src="Images/loader.gif" />');
$.ajax({
url: 'IniciativasEstrategicasWebPart/GetVistaActividades',
type: 'POST',
data: {
idObjetivo: idObjetivoValue,
filtro: filtro
},
success: function (data) {
drawVistaActividades(data);
},
error: function (data) {
showErrorMessage(data);
}
});
}
This is the method that draws the data:
function drawVistaActividades(data) {
resetBreadCrumb();
var html = "";
for (var i = 0; i < data.length; i++) {
html += template.rowVistaActividades
.replace("{0}", data[i].nombreActividad)
.replace("{1}", data[i].iniciativaName)
.replace("{2}", data[i].fechaVencimiento)
.replace("{3}", data[i].fechaRealTerminacion)
.replace("{4}", data[i].responsables);
}
$("#tab_vistaActividades").html("<br>" + "<br>" + template.tableVistaActividades.replace("{0}", html));
}
This is the table template that I use to draw the data, and the buttons are there
tableVistaActividades: "<div>" +
"<div>" +
"<div class=\"btn-group\" role=\"group\" aria-label=\"Basic example\">" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('A tiempo')\">A tiempo</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Atrasadas')\">Atrasadas</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Pendientes')\">Pendientes</button>" +
"</div>" +
"</div>" +
"<table class='table'>" +
"<thead>" +
"<tr>" +
"<th>" +
"Actividad" +
"</th>" +
"<th>" +
"Iniciativa" +
"</th>" +
"<th>" +
"Fecha propuesta" +
"</th>" +
"<th>" +
"Fecha real terminación" +
"</th>" +
"<th>" +
"Responsables" +
"</th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"{0}" +
"</tbody>" +
"</table>" +"<div>",
and the row template
rowVistaActividades: "<tr>" +
"<td>" +
"{0}" +
"</td>" +
"<td>" +
"{1}" +
"</td>" +
"<td>" +
"{2}" +
"</td>" +
"<td>" +
"{3}" +
"</td>" +
"<td>" +
"{4}" +
"</td>" +
"</tr>",
As you can see in this page.
We are using the same Bootstrap button code and in that page the button remains highlighted when clicked.

This should solve your problem, basically you need to add "active" to selected option and remove "active" from siblings which was previously selected.
$(".btn-group > .btn").click(function(){
$(this).addClass("active").siblings().removeClass("active");
$(this).addClass("active");
});

As #taTrifynor said in the comment, you should simply use Button groups with input type="radio", read about it. For example:
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked="checked"/>Button 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"/>Button 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"/>Button 3
</label>
</div>
Or I don't understand what do you want.

Related

Javascript calculation (Products sum without Vat)

Hello I have a problem with some calculation in javascript(see image)
The cell that is with red border calculate product price sum with vat.
What im trying to do but didnt success is to calculate product price sum WITHOUT VAT(the cell with red broder should be 2000 not 2200)
Here is the code that im using,
var row_no = (new Date).getTime();
var newTr = $('<tr id="row_' + row_no + '" class="row_' + item_id + '" data-item-id="' + item_id + '"></tr>');
tr_html = '<td><input name="product_id[]" type="hidden" class="rid" value="' + product_id + '"><input name="product[]" type="hidden" class="rcode" value="' + item_code + '"><input name="product_name[]" type="hidden" class="rname" value="' + item_name + '"><input name="product_option[]" type="hidden" class="roption" value="' + item_option + '"><input name="part_no[]" type="hidden" class="rpart_no" value="' + item_supplier_part_no + '"><span class="sname" id="name_' + row_no + '">' + item_code +' - '+ item_name +(sel_opt != '' ? ' ('+sel_opt+')' : '')+' <span class="label label-default">'+item_supplier_part_no+'</span></span> <i class="pull-right fa fa-edit tip edit" id="' + row_no + '" data-item="' + item_id + '" title="Edit" style="cursor:pointer;"></i></td>';
if (site.settings.product_expiry == 1) {
tr_html += '<td><input class="form-control date rexpiry" name="expiry[]" type="text" value="' + item_expiry + '" data-id="' + row_no + '" data-item="' + item_id + '" id="expiry_' + row_no + '"></td>';
}
tr_html += '<td class="text-right"><input class="form-control input-sm text-right rcost" name="net_cost[]" type="hidden" id="cost_' + row_no + '" value="' + item_cost + '"><input class="rucost" name="unit_cost[]" type="hidden" value="' + unit_cost + '"><input class="realucost" name="real_unit_cost[]" type="hidden" value="' + item.row.real_unit_cost + '"><span class="text-right scost" id="scost_' + row_no + '">' + formatMoney(item_cost) + '</span></td>';
tr_html += '<td><input name="quantity_balance[]" type="hidden" class="rbqty" value="' + item_bqty + '"><input class="form-control text-center rquantity" name="quantity[]" type="text" tabindex="'+((site.settings.set_focus == 1) ? an : (an+1))+'" value="' + formatQuantity2(item_qty) + '" data-id="' + row_no + '" data-item="' + item_id + '" id="quantity_' + row_no + '" onClick="this.select();"><input name="product_unit[]" type="hidden" class="runit" value="' + product_unit + '"><input name="product_base_quantity[]" type="hidden" class="rbase_quantity" value="' + base_quantity + '"></td>';
if (po_edit) {
tr_html += '<td class="rec_con"><input name="ordered_quantity[]" type="hidden" class="oqty" value="' + item_oqty + '"><input class="form-control text-center received" name="received[]" type="text" value="' + formatDecimal(unit_qty_received) + '" data-id="' + row_no + '" data-item="' + item_id + '" id="received_' + row_no + '" onClick="this.select();"><input name="received_base_quantity[]" type="hidden" class="rrbase_quantity" value="' + qty_received + '"></td>';
}
if (site.settings.product_discount == 1) {
tr_html += '<td class="text-right"><input class="form-control input-sm rdiscount" name="product_discount[]" type="hidden" id="discount_' + row_no + '" value="' + item_ds + '"><span class="text-right sdiscount text-danger" id="sdiscount_' + row_no + '">' + formatMoney(0 - (item_discount * item_qty)) + '</span></td>';
}
tr_html += '<td class="text-right"><span class="text-right ssubtotal" id="subtotal_' + row_no + '">' + formatMoney((parseFloat(item_cost) * parseFloat(item_qty))) + '</span></td>';
if (site.settings.tax1 == 1) {
tr_html += '<td class="text-right"><input class="form-control input-sm text-right rproduct_tax" name="product_tax[]" type="hidden" id="product_tax_' + row_no + '" value="' + pr_tax.id + '"><span class="text-right sproduct_tax" id="sproduct_tax_' + row_no + '">' + (pr_tax_rate ? '(' + pr_tax_rate + ')' : '') + ' ' + formatMoney(pr_tax_val * item_qty) + '</span></td>';
}
tr_html += '<td class="text-right"><span class="text-right ssubtotal" id="subtotal_' + row_no + '">' + formatMoney(((parseFloat(item_cost) + parseFloat(pr_tax_val)) * parseFloat(item_qty))) + '</span></td>';
tr_html += '<td class="text-center"><i class="fa fa-times tip podel" id="' + row_no + '" title="Remove" style="cursor:pointer;"></i></td>';
newTr.html(tr_html);
newTr.prependTo("#poTable");
total += formatDecimal(((parseFloat(item_cost) + parseFloat(pr_tax_val)) * parseFloat(item_qty)), 4);
count += parseFloat(item_qty);
an++;
if(!belong)
$('#row_' + row_no).addClass('warning');
});
var col = 2;
if (site.settings.product_expiry == 1) { col++; }
var tfoot = '<tr id="tfoot" class="tfoot active"><th colspan="'+col+'">Total</th><th class="text-center">' + formatQty(parseFloat(count) - 1) + '</th>';
if (po_edit) {
tfoot += '<th class="rec_con"></th>';
}
if (site.settings.product_discount == 1) {
tfoot += '<th class="text-right">'+formatMoney(product_discount)+'</th>';
}
tfoot += '<th class="text-right">'+formatMoney(total)+'</th>';
if (site.settings.tax1 == 1) {
tfoot += '<th class="text-right">'+formatMoney(product_tax)+'</th>';
}
tfoot += '<th class="text-right">'+formatMoney(total)+'</th><th class="text-center"><i class="fa fa-trash-o" style="opacity:0.5; filter:alpha(opacity=50);"></i></th></tr>';
$('#poTable tfoot').html(tfoot);
You set the total which you display right here:
total += formatDecimal(((parseFloat(item_cost) + parseFloat(pr_tax_val)) * parseFloat(item_qty)), 4);
For you to display a price without vat you need another variable for it
var totalNoVAT = 0;
and in the loop:
totalNoVAT += formatDecimal((parseFloat(item_cost) * parseFloat(item_qty)), 4);
and finally display it by changing this:
tfoot += '<th class="text-right">'+formatMoney(total)+'</th>';
to this:
tfoot += '<th class="text-right">'+formatMoney(totalNoVAT)+'</th>';

dynamic form fields with javascript, php & mysql: strange error

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.

Javascript code adding empty records to mysql

I have a short problem.
Here is my form layout:
<form class="form-inline" action="javascript:addRecord();" method="GET">
<div class="row">
<div class="form-group col-lg-4">
<div class="form-group col-lg-6">
<label for="konu">Konu:</label>
<input class="form-control " type="text" name="konu" required="required" placeholder="Bir konu yazın"/>
</div>
</div>
</div>
<br>
<div class="form-group col-lg-5 ">
<button type="submit" class="btn btn-default">Kaydet</button>
</div>
</form>
<div id="add-record-div" class="alert alert-success" hidden="hidden">
<strong>RECORD INSERTED</strong>
</div>
And my javascript code:
function addRecord()
{
$.post('add.php', function(data)
{
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
getLastRecord();
$('#add-record-div').show('slow').delay('1000');
$('#add-record-div').hide('slow');
}
Databse insert looks like this: http://i.stack.imgur.com/fDiiC.jpg
My problem is this function adds only empty rows to mysql. 'giris_tarih' and 'degistirilme_tarih' are date values. Those are being added correctly but other columns are always empty. There is no problem with add.php page. If I only write: form class="form-inline" action="add.php" it works perfectly. But I couldn't get it worked with javascript function.
You have mismatched actions in your markup and script, and also your data is pointing to value which is not part of the object returned from your add.php (you set your ajax response to the variable data, therefore you must use data.propName...). I also corrected your table formatting a bit and used jQuery like the rest of your module.
function addRecord()
{
$.get('add.php', function(data)
{
$('#your-table').append('<tr>' + data.id + '</td>'
+ '<td>' + data.konu + '</td>'
+ '<td>' + data.aciklama + '</td>'
+ '<td>' + data.giris_tarih + '</td>'
+ '<td>' + data.degistirilme_tarih + '</td>'
+ '<td>' + data.ad_soyad + '</td>'
+ '<td>' + data.email + '</td>'
+ '</tr>');
getLastRecord();
$('#add-record-div').show('slow').delay('1000');
$('#add-record-div').hide('slow');
}

Adding Dynamic Inputs , getting value from Dynamic dynamic generate input

I created a dynamic Form with JavaScript, with AddChapitre function and I want to get number value from an input text <input type="text" class="form-control" id="grandTitreNbr1">. And created "numbers value" inputs when I click to addChapitre button using AddFeild() function <button id="b1" class="btn btn-primary" onclick="addFields()">add titres</button> .
The problem is when I click in addChapitre I get the The Chapitre Form hidden.
Here is it in JsFiddle : http://jsfiddle.net/javagose/6veqe55v/1/
This image will show the problem:
function addChapitre() {
var newdiv = document.createElement('div');
var addChapitre =
'<div class="panel panel-success"> <div class="panel-heading"> <h2 class="panel-title">' +
'<a data-toggle="collapse" data-target="#collapse" href="#collapse" class="collapsed">chapitre : ' + j +
' </a></h2></div><div class="panel-body" id="Chapitre' + j + '">';
newdiv.innerHTML += addChapitre;
addChapitre1 =
'<div class="panel-collapse" id="collapse' + j + '" >' +
'<form class="form-horizontal"><div class="form-group">' +
'<label for ="ChapTitre' + j + '">Titre du chapitre</label>' +
'<input type="text" class="form-control" id="ChapTitre' + j +
'" placeholder=" titre du chapitre ' + j + '"></div></form></div>';
newdiv.innerHTML += addChapitre1;
addChapitre2 =
'<div class="panel panel-success" id="grandTitres' + j + '">' +
'<div class="panel-heading"><h2 class="panel-title">' +
'<a data-toggle="collapse" data-target="#collapseTitre" ' +
'href="#collapseTitre" class="collapsed"> Grands titres des chapitre: ' + j + '</a></h2></div>';
newdiv.innerHTML += addChapitre2;
addChapitre2 =
'<div class="panel-body"><div class="panel-collapse" id="collapseTitre" >' +
'<form class="form-horizontal"><div class="form-group" id ="grandTitres1">' +
'<label for ="grandTitreNbr1"> GRAND TITRE</label>' +
'<input type="text " class="form-control" id="grandTitreNbr' + j + '">' +
'<button id="b1" class="btn btn-primary" onclick="addFields()">add titres</button>' +
'<div id="grandTitresDiv' + j + '">' +
'</div></div> </form></div></div> </div></div></div>';
newdiv.innerHTML += addChapitre2;
document.getElementById('conteneur').appendChild(newdiv);
j++;
}
function addFields() {
var number = document.getElementById("grandTitreNbr" + j + "").value;
var container = document.getElementById("grandTitresDiv" + j + "");
for (i = 0; i < number; i++) {
// Append a node with a random text
var newdiv = document.createElement('div');
var grandTitreTxt =
'<input type="text" class="form-control" id="grandTitreTxt' + j +
'" name="grandTitreTxt' + j + '"></div>';
newdiv.innerHTML += grandTitreTxt;
var grandTitreUpload =
'<div class="checkbox"><label><input type="checkbox"> Pdf </label></div>' +
' <input type="file" name="fichier" id="fichier"' + j + ' accept="pdf" />';
newdiv.innerHTML += grandTitreUpload;
var grandTitreUpload =
'<div class="checkbox"><label><input type="checkbox">video </label>' +
'</div> <input type="file" name="fichier" id="fichier"' + j +
' accept="video" />';
newdiv.innerHTML += grandTitreUpload;
container.appendChild(newdiv);
// Append a line break
container.appendChild(document.createElement("br"));
}
}

document.getElementById is returning null on the button click

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.

Categories