Removing form array element - javascript

I have a form which has same products but with different attributes.
The form looks something similar to this:
<form>
<table>
<tr>
<td> Line-1 </td>
<td> <input type='text' name='ítem[1][Size]'</td>
<td> <input type='text' name='ítem[1][Color]'</td>
<td> <input type='text' name='ítem[1][Price]'</td>
</tr>
<tr>
<td> Line-2 </td>
<td> <input type='text' name='ítem[2][Size]'</td>
<td> <input type='text' name='ítem[2][Color]'</td>
<td> <input type='text' name='ítem[2][Price]'</td>
</tr>
<tr>
<td> Line-3 </td>
<td> <input type='text' name='ítem[3][Size]'</td>
<td> <input type='text' name='ítem[3][Color]'</td>
<td> <input type='text' name='ítem[3][Price]'</td>
</tr>
<tr>
<td> Line-4 </td>
<td> <input type='text' name='ítem[4][Size]'</td>
<td> <input type='text' name='ítem[4][Color]'</td>
<td> <input type='text' name='ítem[4][Price]'</td>
</tr>
</table>
</form>
PHP Sample Code:
for($i = 0;$i < count($_POST);$i++){
var_dump($_POST[$i]);
}
Error:
Notice: Undefined offset: 0 in C:\xampp\htdocs\test\testing.php on line 5
If I was to remove item[2] dynamically using js, on submit php would throw an error because it cant find number 2. How could go about this?
Perhaps I'm not doing it right?

In your PHP Code, use foreach as has been suggested:
foreach($_POST['item'] as $item){
echo $item['Size'] . "<br />";
echo $item['Color'] . "<br />";
echo $item['Price'] . "<br />";
echo "<hr />"
}
EDIT:
Another question how would i go about re-changing row numbers once I
deleted row number 2?
This is done in JS or JQuery. Something like:
var i = 1;
$.each($("tr"), function(){
$(this).next("input[name*='Size']").attr("name", "item[" + i + "][Size]");
$(this).next("input[name*='Color']").attr("name", "item[" + i + "][Color]");
$(this).next("input[name*='Price']").attr("name", "item[" + i + "][Price]");
i++;
});

Related

javascript .innerHTML() inserts outside div

I have a table and a button, when the button is pressed it adds a new input into the table inside a div, when I add the input manually inside the div and test it it works, but when the script adds it it goes outside the table.. why is that? how can i fix this issue?
html:
..
<script> var x=0; </script>
...
<table>
<tr>
<td>From:</td>
<td><input type="text" name="from" /></td>
</tr>
<tr>
<td>To (email):</td>
<td><input type="text" name="to0" /></td>
<td><input type='button' onclick='newMail()' value='Add recipient'/> </td>
</tr>
<div id="add">
<tr>
<td>To (email):</td> <!-- this works -->
<td><input type="text" name="to0" /></td>
</tr>
</div>
<tr>
<td align="center" colspan="2"><input type="submit" value="send"></td>
</tr>
</table>
JS:
function newMail()
{
x=x+1;
var input =
" <tr>"+
" <td>To (email):</td>"+
" <td><input type='text' name='to"+x+"' /></td>"+
" </tr>";
document.getElementById("add").innerHTML += input;
}
the function works and adds the input and everything, but it goes outside the table, whilst the one inside the div that i manually added works fine and is displayed normally.
Try this one: https://jsfiddle.net/0dh52827/
JAVASCRIPT
$( document ).ready(function() {
$("#add_recipient").click( function() {
x = x + 1;
console.log(x);
var input =
" <tr>" +
" <td>To (email):</td>" +
" <td><input type='text' name='to" + x + "' /></td>" +
" </tr>";
$("#add").prepend(input);
});
});
HTML:
<script>
var x = 0;
</script>
<table id="add">
<tr>
<td>From:</td>
<td>
<input type="text" name="from" />
</td>
</tr>
<tr>
<td>To (email):</td>
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td>To (email):</td>
<!-- this works -->
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td align="left">
<input type="submit" value="send">
</td>
<td align="right">
<input id="add_recipient" type='button' value='Add recipient' />
</td>
</tr>
JQUERY Prepend is designed for things like this.
Check this please
function newMail() {
x = x + 1;
var input =
" <tr>" +
" <td>To (email):</td>" +
" <td><input type='text' name='to" + x + "' /></td>" +
" </tr>";
document.getElementById("add").innerHTML += input;
}
<script>
var x = 0;
</script>
<table>
<tr>
<td>From:</td>
<td>
<input type="text" name="from" />
</td>
</tr>
<tr>
<td>To (email):</td>
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td>To (email):</td>
<!-- this works -->
<td>
<input type="text" name="to0" />
</td>
</tr>
<tbody id="add"></tbody>
<tr>
<td align="left">
<input type="submit" value="send">
</td>
<td align="right">
<input type='button' onclick='newMail()' value='Add recipient' />
</td>
</tr>
The element with id="add" is a <div> in a <table> (which is not properly placed but might work in some browsers). Adding code to it has at least an undefined behavior.
You should instead remove the <div> tag and give the <tr> tag the id="add" attribute and then use document.getElementById("add").appendChild() method to add a new html node. To create this node, don't use text but document.createElement() like described in MDN

jQuery dynamic functions with variable params

I'm trying to make a little program that uses generated (dynamically) tables, I will explain an example:
I have a blank page with only and input (number type) and a div:
<input id='numoftables' type='number'>
<div id='tablescontainer'></div>
I need create N tables with the following structure:
<table>
<tr>
<td>
<div style='text-align:left;'>
<h3>
<span class='label label-default'>Table #N</span>
</h3>
</div>
</td>
<td>
<input id='secondNum' type='number' class='form-control input-md' value='1'>
</td>
</tr>
</table>
<div class='table-responsive text-left'>
<table id='tableN' class='table table-striped condensed'>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
</tr>
</thead>
<tbody>
<tr>
<td align='middle'>
<b>M</b>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<input type='number' class='form-control input-md'>
</td>
<td>
<div class='input-group date' id='fecha'>
<input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required>
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'></span>
</span>
</div>
</td>
<td align='middle'>
<img class='delete' src='img/delete.png' >
</td>
</tr>
</tbody>
</table>
</div>
<hr>
It's generate something similar of this (with setting a value of 3 on input with id 'numoftables'):
But I want to make dynamic elements (with dynamic id's), please see this:
Red boxes will have the dynamic number, 1 to N; N is the value of the input with id 'numoftables'.
Green boxes represents the numbers of rows (I call this number, M) of the tableN.
How can I to generate all of this dynamically :(?
I have a crazy code, like this:
$("#tablescontainer").html(null);
for (i=1;i<=$("#numoftable").val();i++)
{
$("#tablescontainer").append("<table><tr><td><div style='text-align:left;'><h3><span class='label label-default'>Table #N</span></h3></div></td><td style='position:relative;top:7px !important;left:8px;'><input id='secondNum' type='number' style='width:64px;' class='form-control input-md' value='1'></td></tr></table><div class='table-responsive text-left'><table id='tableN' class='table table-striped condensed'><thead><tr><th>Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th><th>Col 6</th></tr></thead><tbody><tr><td align='middle'><b>M</b></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><input type='number' class='form-control input-md'></td><td><div class='input-group date' id='fecha'><input id='fechainput' maxlength='10' data-date-format='DD/MM/YYYY' type='date' class='form-control' placeholder='Fecha DD/MM/AAAA' required><span class='input-group-addon'><span class='glyphicon glyphicon-calendar'></span></span></div></td><td align='middle'><img width='20' class='delete' src='img/delete.png' ></td></tr></tbody></table></div><hr><script>$('#numcarr"+i+"').click(function(e){$('#tabla"+i+" > tbody:last').html(null);for (j=1;j<=$(\"#numcarr"+i+"\").val();j++){$('#tabla"+i+" > tbody:last').append('<tr><td align=\"middle\"><b>"+i+"</b></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><input min=\"1\" max=\"10\" id=\"numcaballos\" type=\"number\" class=\"form-control input-md\"></td><td><div class=\"input-group date\" id=\"fecha\"><input id=\"fechainput\" maxlength=\"10\" data-date-format=\"DD/MM/YYYY\" type=\"date\" class=\"form-control\" placeholder=\"Fecha DD/MM/AAAA\" required><span class=\"input-group-addon\"><span class=\"glyphicon glyphicon-calendar\"></span></span></div></td><td align=\"middle\"><img width=\"20\" class=\"delete\" onclick=\"$(this).parent().parent().remove()\" src=\"img/delete.png\"></td></tr>')}});</script>");
}
I don't know how can I solve this, write less code, make it dynamically :c
Thanks!
see the result in by inspect the table and secondNum: jsfiddle
jQuery
$(function(){
$("#numoftables").on("change", function(){
$("#tablescontainer").html("");
var num = $(this).val();
var table = $("#copy").html();
for (var i=1; i <= num; i++){
var newTable = table.replace("secondNum", "id='secondNum"+i).replace("uniqueTable", "uniqueTable"+i);
$("#tablescontainer").append(newTable);
}
});
});
CSS
#copy{
display: none;
}
Now you have to do other things in the similar fashion, like showing
the the table number. use a different id which may not use in the
content and replace it in the jquery.

Jquery/javascript calculation issue in array of records

I am doing some calculations in my php script. its done in jquery/javascript. I have a small issue with my following script. The actual scenario is its getting the Total INR value, In the Add (%) field i add the percentage. So the system calculates and add this percentage to the Total Value. Its perfect in the first row of record. But in the second row, its taking the value of the first row. Iam making a small mistake. My script is following. Pls help me on this.
<script type='text/javascript' src='http://code.jquery.com/jquery-2.1.3.js'></script>
<script type='text/javascript'>
//<![CDATA[
function getIndexedElement(item, index) {
if (item.length) {
if (index < item.length) {
return item[index];
} else {
return false;
}
} else {
if (index === 0) {
return item;
}
}
return false;
}
function isNum(value) {
return 123;
}
function calcTotals() {
var grandTotal = 0;
var i = 0;
while (getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i)) {
add_percentageObj = getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i);
addon_valueObj = getIndexedElement(document.forms['cart'].elements['addon_value[]'], i);
total_inr_valueObj = getIndexedElement(document.forms['cart'].elements['total_inr[]'], i);
totalObj = getIndexedElement(document.forms['cart'].elements['add_value[]'], i);
priceunitObj = getIndexedElement(document.forms['cart'].elements['price_unit[]'], i);
qtyObj = getIndexedElement(document.forms['cart'].elements['qty[]'], i);
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = Math.round((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1;
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
//c.value=Math.round((b.value/100) *a.value ).toFixed(2);
} else if (addon_valueObj.value) {
totalObj.value = Math.round((addon_valueObj.value * 1) + total_inr_valueObj.value * 1);
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
} else {
totalObj.value = Math.round((addon_valueObj.value * 1) + total_inr_valueObj.value * 1);
grandTotal = grandTotal + parseFloat(totalObj.value);
//priceunitObj.value = total1Obj.value/qtyObj.value;
}
i++;
}
document.getElementById('grand_total').value = grandTotal;
return;
}
</script>
</head>
<body>
<form name='cart' method='post' class='single' action='generate_quot_cust_edititems_save_complete.php?tender_id=14'>
<input type='hidden' name='sum_input' id='sum_input' value=''>
<div align="center">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr bgcolor="#E6E6FA">
<td width=4%>Qty</td>
<td width=5%>Unitprice</td>
<td width=8%>Total INR</td>
<td width=5%>Add (%)</td>
<td width=7%>Add Value</td>
<td width=6%>Total Value</td>
<td width=8%>Total</td>
<td width=8%>Price/Unit</td>
</tr>
</table>
</div>
<div align="center" class="base">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr>
<td width='4%'>
<input size='1' class='qty' type='text' name='qty[]' id='qty[]' value='20' readonly/>
</td>
<td width='5%'>
<input size='5' type='text' name='unitprice[0]' value='678.000' readonly/>
</td>
<input size='4' type='hidden' id='total_inr[]' name='total_inr[]' value='883332.313' />
<td width='8%'>
<input size='10' type='text' id='total_inr[]' name='total_inr[]' value='883332.300' />
</td>
<td width='5%'>
<input class='' size='4' type='text' id='add_percentage[]' name='add_percentage[]' value='0' onchange='calcTotals()'>
</td>
<td width='7%'>
<input class='txt' type='text' size='7' id='addon_value[]' name='addon_value[]' value='0' onchange='calcTotals()'>
</td>
<td width='6%'>
<input class='total' data-value='883332' size='6' type='text' id='add_value[]' name='add_value[]' value=''>
</td>
<input type="hidden" class="inrvalue" id="inrvalue" name="inrvalue" value="65.1425">
<input type="hidden" class="deptip" id="dept-input" />
<input type="hidden" class="priceip" id="price-input" />
<td width="8%">
<input size="9" type="text" data-value="" name='total1[]' id='total1[]' value="16271.993" readonly class="total1" />
</td>
<td width='8%'>
<input class='price_unit' size='7' type='text' id='price_unit[]' name='price_unit[]' value='813.600' readonly>
</td>
</tr>
</table>
</div>
<div align="center" class="base">
<table width="100%" border="1" style="border-collapse: collapse;" cellpadding="1" cellspacing="1">
<tr>
<td width='4%'>
<input size='1' class='qty' type='text' name='qty[]' id='qty[]' value='360' readonly/>
</td>
<td width='5%'>
<input size='5' type='text' name='unitprice[1]' value='569.000' readonly/>
</td>
<td width='8%'>
<input size='10' type='text' id='total_inr[]' name='total_inr[]' value='13343789.700' />
</td>
<td width='5%'>
<input class='' size='4' type='text' id='add_percentage[]' name='add_percentage[]' value='0' onchange='calcTotals()'>
</td>
<td width='7%'>
<input class='txt' type='text' size='7' id='addon_value[]' name='addon_value[]' value='0' onchange='calcTotals()'>
</td>
<td width='6%'>
<input class='total' data-value='883332' size='6' type='text' id='add_value[]' name='add_value[]' value=''>
</td>
<td width="8%">
<input size="9" type="text" data-value="" name='total1[]' id='total1[]' value="16000.803" readonly class="total1" />
</td>
<td width='8%'>
<input class='price_unit' size='7' type='text' id='price_unit[]' name='price_unit[]' value='44.447' readonly>
</td>
</tr>
</table>
</div>
<table width='100%'>
<tr>
<td width='3%'> </td>
<td width='4%'> </td>
<td width='17%'> </td>
<td width='5%'> </td>
<td width='5%'> </td>
<td width='6%'> </td>
<td width='5%'> </td>
<td width='7%'> </td>
<td width='8%'> </td>
<td width='5%'> </td>
<td height=35><b>Grand Total: <input type='text' style='font-weight: bold' name='gTotal' id='grand_total' value='1766664.000' readonly /></b></td>
</tr>
<tr>
</table>
<br>
</div>
<table border='0' width='13%'>
<td>
<input type='submit' value='--Save Data--' />
</td>
Element ID's have to be unique. If you refer to an element by id, and there are multiple elements with the same ID, then you likely only going to get the first one back. Also, I suspect that elements["name"] does not give an array back, but a unique element.
Instead try using something like this instead:
cartForm = document.forms['cart'];
...
add_percentageObj = getIndexedElement(cartForm.getElementsByName('add_percentage[]'), i);
An element name does not have to be unique. I see that you are already using both id and name anyhow on your elements.
Also I would suggest writing a function like this (untested):
function getCartElement(name, index) {
namedElements = document.forms['cart'].getElementsByName(name);
if (index >= namedElements.length) return null;
return namedElements[index];
if (item.length) {
}
Anyway, the rest of your code would look like something like this:
while (getCartElement('add_percentage[]', i) != null) {
add_percentageObj = getCartElement('add_percentage[]', i);
addon_valueObj = getCartElement('addon_value[]', i);
...
Note that I made sure that your function returns a consistent datatype, not one time boolean, another time an element instance ... this does mean however that you will require to check for null values.
Reference:
getElementsByName
getElementsById
elements
Also read this other stackoverflow article

Display radio button checked if json value is match to condition

I've following Json data
{"1":"2","2":"2"} this can be change as per conditions.
I'm trying to implement radio button checked if Json contain value same as radio button.
in Json first Value is radio name and 2nd is value that needs to match.
success : function(result){
//alert(JSON.stringify(result));
var contact = JSON.parse(result);
alert("First: " + contact + " Second: " + contact);
$('input[type=radio][name="' + group[contact[1]] + '"][value="' + contact[1] + '"]').prop('checked', true);
}
Following is my html form
<table width="50%" border="1" align="center" cellpadding="2" cellspacing="1" >
<th><td colspan='2'> <font color='#006699' size='3' face='Arial, Helvetica, sans-serif'><strong> Assign User Role </br></br></strong></font></td></th>
<tr bgcolor="#FFFFFF">
<td><strong>Select User:</strong></td>
<td><input type="text" name="assigned_to" id="assigned_to" /></td>
</tr>
<tr bgcolor="#FFFFFF">
<td><strong>Page Group</strong></td>
<td><strong>User Role </strong></td>
</tr>
<?php
foreach($groups as $key=>$value)
{ ?>
<tr bgcolor='#FFFFFF'>
<td><strong><?php echo $value; ?></strong></td>
<td>
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group1" value="1" />Viewer
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group2" value="2" />Approver
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group3" value="3" />Editor
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group3" value="4" />Adder
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group4" value="5" />Super Editor
<input type="radio" name="group[<?php echo $key; ?>]" id="chk_group5" value="6" />Blocked
</td>
</tr>
<?php
}
?>
</tr>
<tr></tr> <tr></tr> <tr></tr>
<tr bgcolor="#FFFFFF">
<td></td>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
Traverse through radio elements collection using each() of jquery, check for matched radio value with json provided value and add check to matched radio.
According to your json as :
{"1":"2","2":"2"}
Insert below code in sucess function of ajax
success : function(result){
for(key in result){
$('input[type=radio]').each(function(){
if($(this).val() === result[key]){
$(this).prop('checked', true);
}
}
}
}

fill text fetched from database into text fiels on selection of radio buttons

I am fetching data from database , for each of row data fetched I am creating a radio button against the row. The details of a land-sites are fetched here.
I have a form for booking these land sites, which takes land-site details and name and email of user.
So when a user selects a radio button, the details of land-site should be automatically filled in the form, How to achieve this.
<html>
<body>
<?php
$phase=$_GET["q"];
$sql ="select id, phase,size, facing, sply, status from plot where status='avail' and phase='$phase'";
$ret=mysql_query($sql, $connect);
echo "<form>";
echo"<div style='overflow-y:scroll;height:200px;float:left;' ><table border=1 >
<tr>
<td>select </td><td>phase</td> <td>site no.</td> <td>plot-size</td> <td>face</td> <td>sply</td> <td>status</td>
</tr>" ;
while($row = mysql_fetch_array($ret, MYSQL_ASSOC))
{
echo "<tr>".
"<td><input type='radio' name='book' value='book' onClick=\"whichForm('send_to_one');\" /></td>".
"<td>{$row['phase']} </td>".
"<td>{$row['id']} </td>".
"<td> {$row['size']} </td>".
"<td> {$row['facing']} </td>".
"<td>{$row['sply']} </td> ".
"<td>{$row['status']} </td> ".
"</tr>";
}
echo "</table></div>";
mysql_close($connect);
?>
<div id="send_to_one" style="float:right;padding:30px">
<table>
<tr>
<td>Name :</td><td><input type="text" name="name" value=""/></td>
</tr>
<tr>
<td>Mobile:</td><td><input type="text" name="mobile" value="" /></td>
</tr>
<tr>
<td>Email :</td> <td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>Phase : </td> <td><select name="phase" id="phase">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td>
</tr>
<tr>
<td>Site :</td> <td> <input type="text" name="site" value="" id="site" /></td>
</tr>
<!--
<tr><td><span id="status"></span></td></tr>
-->
<tr>
<td><input type="radio" name="status" value="blocked" class="radioBtn" onclick="advance.disabled=true" /> block</td>
<td><input type="radio" name="status" value="booked" class="radioBtn" onclick="advance.disabled=false" /> book </td>
</tr>
<tr>
<td>Advance paid </td> <td><input type="text" name="advance" value="" id="textField" /></td>
</tr>
<tr><td><input type="submit" value="submit" /></td> <td> <input type="reset" value="clear all" /> </td></tr>
</table>
<?php echo "</form>"; ?>
</div>
<!-- div ends here -->
</body>
</html>

Categories