Issue replacing input value in array - javascript

I did an example about replacing the input value when the row is deleted but is not working (this is not a static example).
<script src="./edit_files/prototype.js" type="text/javascript"></script>
<script src="./edit_files/application.js" type="text/javascript"></script>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="cristianoronaldo#realmadrid.com"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="ONLY THE INPUT WILL BE test#hotmail.com IF I CLICK ON DELETE"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
Here is the application.js file:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
I tried this code but only works if I remove the first row.
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
$('should_change_value').update("test#hotmail.com");
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
Here is the live example in jsfiddle
Here is the example download on Github but is not replacing the input value correctly

Ok I got it, you want to change the input value when the row is deleted, so do this:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
var element_text2 = $(element).up('.contact').down('.should_change_value',0);
element_text2.className = 'should_change_value';
element_text2.value = 'test#hotmail.com';
if (should_destroy) { $(element).next('.should_destroy').value = 1;}
$(element).up('.contact').hide();
}

Related

add text field dynamically in to a html table

$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" name="Tape_Code[]" value=""/>delete</div>';
var x = 1;
$(addButton).click(function() {
if (x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<?php
include_once 'dpconnect.php';
$que=mysqli_query($MySQLiconn,"select Backup_Name from admin_backup_list ");
if(isset($_POST['confirm'])) {
$Date=date('d/m/y');
$Backup_Name=$_POST['Backup_Name'];
$Tape_Code = $_POST['Tape_Code'];
$Operator_Approval = $_POST['Operator_Approval'];
$Operator_Remark = $_POST['Operator_Remark'];
$abc=mysqli_query($MySQLiconn,"insert into backup_details(Date, Backup_Name, Tape_Code,Operator_Approval,Operator_Remark)values('$Backup_Name','$Tape_Code','$Operator_Approval','$Operator_Remark')");
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<?php $Date=date( 'd/m/y'); ?>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Date</td>
<td width="94">Backup_Name</td>
<td width="94">No Of Tapes</td>
<td width="53">Tape Code</td>
<td width="71">Operator Approval</td>
<td width="144">Operator Remark</td>
</tr>
<?php if ($que->num_rows > 0) { while ($row = mysqli_fetch_array($que)) { ?>
<tr>
<td>
<?php echo $Date; ?>
</td>
<td>
<?php echo $row[ 'Backup_Name']; ?>
</td>
<td>
<input type="text" name="No_Of_Backup">
</td>
<td>
<div class="field_wrapper">
<input type="text" name="Tape_Code" value="" />add
</div>
</td>
<td>
<input type="text" name="Operator_Approval">
</td>
<td>
<input type="text" name="Operator_Remark">
</td>
<td colspan="8">
<input type="submit" name="confirm" value="Confirm">
</center>
</td>
</tr>
<?php } } ?>
</table>
</form>
</body>
</html>
I'm doing this code in php. I need a help to add text fields dynamically in to the table's particular column. I have done the code using JavaScript also. But the problem is when I add field in one row, all rows are updating with extra fields. I need a help. How can I insert those data to MySQL?
The problem with your code is that you are using the class selector to select the elements. Class selector returns array like object of all the elements having that class.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
you can find out which element was clicked if you change your code similar to below one.
add
and in the script
function addButton(ev) {
var clickedElement = console.log(ev.target);
}
Now you have the element which was clicked by user and you can find the parent td/tr and append html for textbox.
In $Tape_Code = $_POST['Tape_Code']; You will get array of text input you have to insert it in database in form that you want.
$Tape_Code = $_POST['Tape_Code']
foreach($Tape_Code as $code){
echo $code;
}

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

jQuery remove row with matching file name as hidden

I have a markup like this
<table id="data">
<tr>
<td>Name</td>
<td>Test</td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file.doc">
</td>
<td><input type="text" value="Test 1"></td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file1.docx">
</td>
<td><input type="text" value="Test 2"></td>
</tr>
<tr>
<td>
<input type="hidden" id="file-name" value="file.pdf">
</td>
<td><input type="text" value="Test 3"></td>
</tr>
</table>
Remove File
In that markup you can see I have file name as hidden fields and under the table I have a remove file tag. So the thing is like this when I will click on the remove file then it will remove that entire row(tr tag) inside where the filename
file.doc is present. So for that I have made my js like this
<script type="text/javascript">
$(document).ready(function() {
$('#remove').click(function(e) {
var FileName = 'file.doc';
var GetRowVal = $('table#data td #file-name').val();
if(GetRowVal == FileName ) {
var Parent = $(GetRowVal).parent().remove();
}
else {
console.log(' error');
}
});
});
</script>
But it is not removing the row. So can someone kindly tell me whats the issue here? Any help and suggestions will be really apprecaible. Thanks
There are duplicate id's in your Html,just correct that issue and try below answer :
<script type="text/javascript">
$(document).ready(function() {
$('#remove').click(function(e) {
e.preventDefault();
var FileName = 'file.doc';
$('input[type="hidden"]').each(function(){
if( $(this).val() == FileName )
{
$(this).closest('tr').remove();
}
});
});
});
</script>
Following code return Array of Jquery Object.
Then function .val() cannot have meaning.
$('table#data td #file-name');
You have two probles in this code:
first : Ids are not unique.
second:
var GetRowVal = $('table#data td #file-name').val();
will hold only value eg. file.doc
so you can't later
remove the object in this line:
var Parent = $(GetRowVal).parent().remove();
so to repair it first change id to class like here:
<input type="hidden" class="file-name" value="file.doc">
and later You can modify your code:
$(document).ready(function() {
$('#remove').click(function(e) {
var GetRowVal = $(".file-name[value='file.doc']");
$(GetRowVal).parent().parent().remove();
});
});
Here jsfiddle

Search table contents using javascript

I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?
Here's a jsfiddle http://jsfiddle.net/SuRWn/
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th>
</tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td >
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
Javascript:
<script type="text/javascript">
//<!--
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for ( var i = 0; i < rows.length; i++ ) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if ( fullname ) {
if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
//-->
</script>
checking with chrome console, it seems that innerHtml for the 'fullname' is returning an error:
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
That's because the first tr tag you have is in the thead and it doesn't have any td at all. Changing the start of your loop to 1 will fix that:
for ( var i = 1; i < rows.length; i++ ) { //... and so on
yuvi is correct in his answer. I've incorporated this in a fiddle - http://jsfiddle.net/dBs7d/8/ - that also contains the following changes:
Inputs with course and subject grouped into individual rows.
td tags align underneath th tags.
Code refactored to improve readability.
Instead of checking the html of the td tags I've changed it to check the value attribute of the input tags. This means you can change the value of the input and still search.
I also changed the style alteration to use backgroundColor. This can easily be reverted to display.
See this link.
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th>Course</th>
<th>Subject</th>
<th>COURSE CODE</th>
<th>COURSE NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="course" /></td>
<td><input type="text" value="subject" /></td>
</tr>
<tr>
<td><input type="text" value="course1" /></td>
<td><input type="text" value="subject1" /></td>
</tr>
<tr>
<td><input type="text" value="course2" /></td>
<td><input type="text" value="subject2" /></td>
</tr>
</tbody>
</table>
Search here (with jQuery):<input type="text" size="30" value="" onKeyUp="doSearchJQ(this);" /><br />
Search here:<input type="text" size="30" value="" onKeyUp="doSearch(this);" />
Javascript:
function doSearchJQ(input) {
var value = $(input).val();
if (value.length > 0) {
$("#results tbody tr").css("display", "none");
$('#results input[value^="' + value + '"]').parent().parent().css("display", "table-row");
} else {
$("#results tbody tr").css("display", "table-row");
}
}
function doSearch(input){
var value = input.value;
var table = document.getElementById('results');
var tbody = table.querySelector("tbody");
var rows = tbody.querySelectorAll("tr");
var visible, row, tds, j, td, input;
for (var i = 0; i < rows.length; i++) {
visible = false;
row = rows[i];
tds = row.querySelectorAll("td");
for (j = 0; j < tds.length; j++) {
td = tds[j];
input = td.querySelector("input");
console.log(input.value.indexOf(value));
if (input.value.indexOf(value) > -1) {
visible = true;
break;
}
}
if (visible) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
}
}
With jquery it's more compact function. But you can use clear javascript doSearch.
Why don't you use JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:
The plugin is well-documented, and widely used. It should be very easy to drop in into an existing application, and style it accordingly.
Hope this helps!

Clone a table row and remove values in JavaScript

I have a set of text inputs fields which I want to be cloned when the user clicks the "add" button. My problem is that the fields are being cloned with the input from the user. Using Javascript, how do I reset the value of the text input fields so they may be cloned without cloning the user input text.
This is my code...
<table width="766" border="0" cellspacing="0" cellpadding="0" id="albumTable">
<tr id="clone">
<td width="230"><input type="text" name="dj_1" /></td>
<td width="230"><input type="text" name="affiliations_1" /></td>
<td width="230"><input type="text" name="rating_1" /></td>
<td width="230"><input type="text" name="comments_1" /><input type="hidden" name="count" value="1" class="count"/></td>
<td width="286" style="position:absolute; top:110px; left: 670px;"><input name="button" type="button" id="Add" value="ADD ROW" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table>
<script type="text/javascript">
function addRow(r){
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
var cInp = cRow.getElementsByTagName('input');
var countRow = cRow.getElementsByClassName('count');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[i].getAttribute('name').replace(/\d/g,(allRows.length+1)))
}
for(var j=0;j<countRow.length;j++){
countRow[j].setAttribute('value',countRow[j].getAttribute('value').replace(/\d/g,(allRows.length+1)))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
Something like this:
var cln = document.getElementByID("clone");
var clns = cln.getElementsByTagName("td");
for(var i = 0; i <clns.length; i++)
{
clns[i].innerHTML = "";
}
In the first for loop, just add this:
cInp[i].value='';

Categories

Resources