Set order number in sequence of checkbox checked in php + javascript - javascript

I'm getting some problems trying to set order number if sequence of checkbox checked with javascript:
<?php
for ($x=0; $x<count($UnidadesServicio); $x++){
$idunidadserv = $UnidadesServicio[$x]['idunidadserv'];
$unidadserv = utf8_encode($UnidadesServicio[$x]['lugarunidad']);
$desunidad = utf8_encode($UnidadesServicio[$x]['desunidad']);
?>
<tr>
<td width="10%"><input type="checkbox" id="cbx_<?php echo $idunidadserv;?>" name="chk_unidadserv" value="<?php echo $idunidadserv;?>" onClick="AgregarUnidadServ()" /></td>
<td width="56%" height="28"> <?php echo $unidadserv;?> </td>
<td width="13%"> </td>
<td width="21%" align="center"> <input name="txt_orden_<?php echo $x;?>" type="text" id="txt_orden_<?php echo $idunidadserv;?>" value="" size="2" maxlength="1" class="txtorden" /> </td>
</tr>
<?php
}
?>
My JavaScript function:
<script>
function AgregarUnidadServ(){
var group = document.getElementsByName('chk_unidadserv');
var i;
for (i=0; i<group.length; i++){
if (group[i].checked == true){
var id = parseFloat(i+1);
$("#txt_orden_"+id).val(i);
}
}
}
</script>
What i need to to do:
When check any checkbox, set in input text the sequence number (1, 2, 3, etc.)
That code, display like this:
Greetings.

$("#txt_orden_"+id).val(id);
And sequence will start from 1.

Related

How to make input affect an echo

In this problem, when I sum a number to the quantity with the button,I want to change the total but it doesnt change, which is this line:
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
Here's the php code
<tr>
<td width="40%"><?php echo $producto['NOMBRE'] ?></td>
<td><button onclick="add_number()">mas</button><input type="text" id="suma" name="suma" value="<?php echo $producto['CANTIDAD'] ?>" readonly="readonly"></input></td>
<td width="20%" class="Text-center"><?php echo $producto['PRECIO'] ?></td>
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
<td width="5%">
<form action="" method="post">
<input type="hidden"
name="id"
value="<?php echo openssl_encrypt($producto['ID'],COD,KEY); ?>">
<button
class="btn btn-danger"
type="submit"
name="btnAccion"
value="Eliminar"
>Eliminar</button>
</form>
</td>
</tr>
Here's the Java code:
function add_number() {
var first_number = parseInt(document.getElementById("suma").value);
var result = first_number + 1;
document.getElementById("suma").value = result
}
In the function add_number where you increment the quantity value, you can also add the price to total cell of table each time, change your JavaScript function like this:
function add_number() {
var suma = parseInt(document.getElementById("suma").value); /* get current quantity */
var total = parseInt(document.getElementById("total").innerHTML); /* get current total */
var percio = parseInt(document.getElementById("percio").innerHTML); /* get price */
document.getElementById("suma").value = suma + 1; /* change quantity */
document.getElementById("total").innerHTML = (suma + percio).toFixed(2); /* change total */
}
Note the usage of innerHTML and value. The difference is because value is used for <input> tag while innerHTML is used for <td> tag.
Also note that you need to sed id for total cell and price cell in oder to read and write in them in your JavaScript function.
<td width="20%" class="Text-center" id="percio">
<?php echo $producto['PRECIO'] ?>
</td>
<td width="20%" class="Text-center" id="total">
<?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?>
</td>

php form building in loop, javascript only affecting first element

I'm currently building a form, and using a PHP loop to build the elements in a table which hold the values I'm submitting after clicking a checkbox.
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
My issue is, I have an id on the checkbox and id's on the values so I can only get the console log when I click the very first checkbox and it only logs the very first item. How can I change this so that I can submit with any checkbox in the table and it's associated values?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
Here is the solution to your problem, you need to use classes instead of IDs.
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td class="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
Now, in your JS section, you can fetch them by their class:
var productNumber = document.getElementsByClassName("productNumber").innerHTML = productNumber;
var detailColor = document.getElementsByClassName("detailColor").innerHTML = detailColor;
var category = document.getElementsByClassName("category").innerHTML = category;
Note: If you're applying CSS styles to those elements via their ID, you can change #productNumber to .productNumber in your CSS or you can leave the ID tag with the same name as your previous code.
In PHP code
<form id="saveLineup">
<?php $i=0; ?>
#foreach($lists as $list)
<?php $i+=1; ?>
<tr style="text-align:center;">
<td id="groupNumber<?php echo $i ?>">.
{{$list['product']}} - {{$list['product_NAME']}}
</td>
<td id="detailColor<?php echo $i ?>">.
{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}.
</td>
<td id="category<?php echo $i ?>">.
{{$list['CATEGORY']}}
</td>
<td>
<input id="addToLineup<?php echo $i ?>"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo
"checked='checked'"; ?>>
</td>
</tr>
#endforeach
<input id="listcount"> type="hidden" value="<?php echo $i; ?>" >
</form>
Js function
$("#addToLineup").click(function (e) {
for(var i=1 ; i <= parseInt(document.getElementById("listcount").value); i++) {
Console.log(document.getElementById("productNumber"+i).innerHTML);
Console.log(document.getElementById("detailColor"+i).innerHTML);
Console.log(document.getElementById("category"+i).innerHTML);
}
});

validation in javascript for a php loop

I am trying to make a simple validation in javascript for a foreach in php, but I don't know how to parse each row from view
<table>
<?php $i=1; ?>
<?php foreach($questions $row):
?>
<tr><td colspan="2"><?php echo $i++; ?><?php echo $row->question;?></td></tr>
<tr><td colspan="2"><?php echo $row->category;?></td></tr>
<tr><td colspan="2"><?php echo $row->id;?></td></tr>
<tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_1;?>"></td>
<td class="answer"><?php echo $row->var_a;?></td>
</tr><tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_2;?>"></td>
<td class="answer"><?php echo $row->var_b;?></td>
</tr><tr>
<td><input type="checkbox" id="r" value="<?php echo $row->var_3;?>"></td>
<td class="answer"><?php echo $row->var_c;?></td?
</tr>
<?php endforeach; ?>
</table>
<button type="button" id="submit">Send</button>
And in javascript I try to check every answer for each question .
<script>
$("#submit").on("click", function(){
var x=0;
if(document.getElementById("r").checked == true document.getElementById("r").value == 1){
x=x+1;
}
});
</script>
Each answer has value 1 or 0, and it can be multiple choice.
IDs need to be Unique - use class or name instead
if you have jQuery USE jQuery
$("#submit").on("click", function(e){
var x=$(".r:checked").length; // using class="r"
if (x < $(".r").length) {
alert("Please check all checkboxes");
e.preventDefault();
}
});
or using name="r"
$("#submit").on("click", function(e){
var x=$('input[name="r"]:checked').length;
if (x < $('input[name="r"]').length) {
alert("Please check all checkboxes");
e.preventDefault();
}
});

Calculated fields in HTML form not working

I am working with DreamWeaver, PHP, MySQL, JQuery Mobile and JavaScript. I am showing MySQL records on a table and each row has an edit link to open an update record file. Using JavaScript in an insert record file, I am able to calculate fields values using a JavaScript function, but now, I am trying to do the same in an update record file.
The problem I have now, is that on the second file the JavaScript function is called, but any calculation is made.
The only difference I see there is that on the second file (update record) the fields already have a value, but I am not sure if that is the source of the problem, but I guess not, then the user can manually change the values.
This is the JavaScript code for both files:
<script type="text/javascript">
function calculatetotal(){
alert("I am an alert box!");
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
var totaliva =0;
var totcliente =0;
totcliente = (mat+mo+uti+ind).toFixed(2);;
var totaliva = ((poriva)/100)*totcliente;
document.getElementById('totCliente').value = (mat+mo+uti+ind).toFixed(2);
document.getElementById('totaliva').value = totaliva;
document.getElementById('totalpre').value= parseFloat(totaliva)+parseFloat(totcliente);
}
</script>
I need your help to understand why is it working on the insert record file and not on the update record file.
This is the code for the form part in HTML from the update record part:
<form method="post" name="form1" id="form1" data-ajax="false" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Obra:</td>
<td><select name="int_obra">
<?php
do {
?>
<option value="<?php echo $row_Recordset2['idObra']?>" <?php if (!(strcmp($row_Recordset2['idObra'], htmlentities($row_Recordset1['int_obra'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>><?php echo $row_Recordset2['nombreObra']?></option>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
?>
</select></td>
<tr>
<tr valign="baseline">
<td nowrap align="right">Materiales:</td>
<td><input type="text" name="dbl_materiales" value="<?php echo htmlentities($row_Recordset1['dbl_materiales'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="mat" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Mano de Obra:</td>
<td><input type="text" name="dbl_mano_de_obra" value="<?php echo htmlentities($row_Recordset1['dbl_mano_de_obra'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="mo" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Utilidad:</td>
<td><input type="text" name="dbl_utilidad" value="<?php echo htmlentities($row_Recordset1['dbl_utilidad'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="uti" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Indirectos:</td>
<td><input type="text" name="dbl_indirectos" value="<?php echo htmlentities($row_Recordset1['dbl_indirectos'], ENT_COMPAT, 'UTF-8'); ?>" id="ind" onChange="calculatetotal()"size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Pre. aprobado por cliente:</td>
<td><input name="dbl_total" type="text" id="totcliente" value="<?php echo htmlentities($row_Recordset1['dbl_total'], ENT_COMPAT, 'UTF-8'); ?>" size="32" readonly></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">% IVA:</td>
<td><input type="text" name="dbl_porcentaje_iva" value="<?php echo htmlentities($row_Recordset1['dbl_porcentaje_iva'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="poriva" onChange="calculatetotal()"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Total IVA:</td>
<td><input name="dbl_total_iva" type="text" value="<?php echo htmlentities($row_Recordset1['dbl_total_iva'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="totaliva" readonly></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">TOTAL DEL PRESUPUESTO:</td>
<td><strong>
<input name="dbl_total_presupuesto" type="text" value="<?php echo htmlentities($row_Recordset1['dbl_total_presupuesto'], ENT_COMPAT, 'UTF-8'); ?>" size="32" id="totalpre" readonly>
</strong></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">MONEDA:</td>
<td><select name="int_moneda">
<option value="1" <?php if (!(strcmp(1, htmlentities($row_Recordset1['int_moneda'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>>PESO MXN</option>
<option value="2" <?php if (!(strcmp(2, htmlentities($row_Recordset1['int_moneda'], ENT_COMPAT, 'UTF-8')))) {echo "SELECTED";} ?>>USD</option>
</select></td>
</tr>
<tr valign="baseline">
<td nowrap align="right"> </td>
<td><input type="submit" value="Actualizar Presupuesto"></td>
</tr>
</table>
<input type="hidden" name="MM_update" value="form1">
<input type="hidden" name="idPresupuesto" value="<?php echo $row_Recordset1['idPresupuesto']; ?>">
</form>
I have updated the JavaScript code, and now it works as expected. Thank you for your help.
<script type="text/javascript">
function calculatetotal(){
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
totcliente = (mat+mo+uti+ind).toFixed(2);
var totaliva = parseFloat(((poriva)/100)*totcliente);
document.getElementById('totcliente').value = totcliente;
document.getElementById('totaliva').value = totaliva.toFixed(2);
document.getElementById('totalpre').value = (parseFloat(totcliente)+parseFloat(totaliva)).toFixed(2);
}
</script>
add your script a the end of the page juste before </body> and call the function :
<script type="text/javascript">
function calculatetotal(){
alert("I am an alert box!");
var mat = 0;
mat = parseFloat(document.getElementById('mat').value);
var mo = 0;
mo = parseFloat(document.getElementById('mo').value);
var uti = 0;
uti = parseFloat(document.getElementById('uti').value);
var ind = 0;
ind = parseFloat(document.getElementById('ind').value);
var poriva = 0;
poriva = parseFloat(document.getElementById('poriva').value);
var totaliva =0;
var totcliente =0;
totcliente = (mat+mo+uti+ind).toFixed(2);;
var totaliva = ((poriva)/100)*totcliente;
document.getElementById('totCliente').value = (mat+mo+uti+ind).toFixed(2);
document.getElementById('totaliva').value = totaliva;
document.getElementById('totalpre').value= parseFloat(totaliva)+parseFloat(totcliente);
}
calculatetotal();
</script>
</body>
</html>

How to know the number of textbox in a form using javascript

How do I determine the correct number of textbox (input type="text") in an html form using Javascript.
What I'm trying to do here is to compute the subtotal by providing the qty and price.
<script type="text/javascript">
function compute(){
var quant=new Array();
var price=new Array();
var stotal=new Array();
var tbox=new Array();
var elemlent=document.x.elements.length;
var dib=elemlent /3;
for(var i=0; i<dib; i++)
{
quant[i] = document.x.elements['qty[i]'].value;
price[i] = document.x.elements['cost[i]'].value;
stotal[i]= quant[i] * price[i];
tbox[i] = document.x.elements['subtotal[i]'];
if (tbox[i])
{
tbox[i].value = stotal[i];
}
}
}
</script>
<body>
<table border="1">
<form name="x">
<th>QTY</th>
<th>COST</th>
<th>SUBTOTAL</th>
<td>+</th>
<?php
for($i=0;$i<2;$i++){
?>
<tr>
<td><input type="text" name="qty[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="cost[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="subtotal[<?php echo $i; ?>]" value=""/></td>
<td><img src="add-icon.png" onmouseover="compute();"></td>
</tr>
<?php } ?>
</form>
</table>
</body>
I just can't seem to make this work when I add for loops.
Can you see what's wrong with my code?
Change:
['qty[i]']
to:
['qty[' + i + ']']
and similar for the other ones to make the above work. I suggest you change <input> elements to provide the id, something along these lines:
<input type="text" id="qty[<?php echo $i; ?>]" name="qty[<?php echo $i; ?>]" value=""/>
Then, instead of:
quant[i] = document.x.elements['qty[i]'].value;
use:
quant[i] = document.getElementById(['qty[' + i + ']']).value;
Note also that you are going to get a string, so I suppose you'd like to use parseInt and/or parseFloat:
http://www.w3schools.com/jsref/jsref_parseInt.asp
http://www.w3schools.com/jsref/jsref_parseFloat.asp
i.e. something like this:
quant[i] = parseFloat(document.getElementById(['qty[' + i + ']']).value);
Note, also, that you may want to consider checking for errors (e.g. if someone enters "qqaacc" in price field instead of "123.45").

Categories

Resources