Jquery adding only one row not 4 - javascript

Hi there can someone please help me with this code:
So this is the blade
<table class="optionsForm" style="width:100%">
<thead>
<tr >
<th><button type="button" class="add">Add</button></th>
#for($c = 1; $c<=4; $c++)
<th id="column{{ $c}}">
<input type="text" name="columns[{{ $c }}]"
class="form-control" placeholder="Column {{ $c }} ">
</th> #endfor
<th><button type="button" style="width: 100px; height: 25px" class="addColumn">Add Column</button></th>
</tr>
</thead>
<tbody> #for($r = 1; $r<=4; $r++)
<tr class="prototype">
</tr> #endfor
</tbody>
</table>
and this one is the js code, I need to be able to add only one row, here it is adding 4 rows, I need first to be shown 4 rows, but than when I click add I need to be added only one row how can I achieve this can someone please help me with this thing I am stuck, thank you so much for any efforts.
$(document).ready(function () {
var id = 0;
// Add button functionality
$("table.optionsForm button.add").click(function () {
id++;
var master = $(this).parents("table.optionsForm");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.optionsForm button.remove").on("click", function () {
$(this).parents("tr").remove();
});
$("table.optionsForm button.addColumn").click(function () {
var $this = $(this), $table = $this.closest('table')
$('<th><input type="text" name="options" class="form-control" placeholder="Column"></th>').insertBefore($table.find('tr').first().find('th:last'))
var idx = $(this).closest('td').index() + 1;
$('<td><input type="radio" name="col' + idx + '[]" value="" /</td>').insertBefore($table.find('tr:gt(0)').find('td:last'))
});
});

The add button code is creating a collection of four elements with class "prototype" and then cloning four elements:
var prot = master.find(".prototype").clone()
To add a single element, try selecting the first DOM element from the collection and converting it to a JQuery object before applying clone:
var prot = $(master.find(".prototype")[0]).clone()
As a minimal test/demonstration case (not using blade)
var master = $("#master");
var prot = $(master.find(".prototype")[0]).clone();
master.append(prot);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="master">
<span class="prototype">proto 1</span><br>
<span class="prototype">proto 2</span><br>
<span class="prototype">proto 3</span><br>
<span class="prototype">proto 4</span><br>
</div>

Related

How can i get two input field values based on onclick function

I have a div in that div I have two input fields and update button like this:
<button type = "button" id = "add-botton" >Add Element </button>
<div id = "trace-div1" class = "trace">
<h4><span>Trace 1</span></h4>
<form>
<table>
<tbody>
<tr>
<td><label>X Axis: </label></td>
<td><input type="text" name="t_x_axis" class = "t_x_axis" id="x_axis_t1" size="50">
</td>
</tr>
<tr>
<td><label>Y Axis: </label></td>
<td><input type="text" name="t_y_axis" class = "t_y_axis" id="y_axis_t1" size="50"></td>
<td><button type = "button" name = "update-button-trace" class = "update-trace" id =
"update-botton-trace1" onclick="updatebtn(this)">Update </button></td>
</tr>
</tbody>
</table>
</form>
</div>
<script>
$(document).ready(function(){
$('#add-botton').click(function(){
var $div = $('div[id^="trace-div"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $trace1div = $div.clone(true).prop('id', 'trace-div'+num );
$trace1div.find('span').text('Trace ' + num);
$trace1div.find("input[name='t_x_axis']").attr("id", "x_axis_t"+num).val("");
$trace1div.find("input[name='t_y_axis']").attr("id", "y_axis_t"+num).val("");
$trace1div.find("button[name='update-button-trace']").attr("id", "update-button -
trace"+num);
$div.after( $trace1div);
});
});
function updatebtn(el){
var id = $(el).attr('id');
}
}
</script>
Here I am cloning my div multiple times with diff.id's ,my problem is when I click update button i need those respective two input values.
I tried like this but here I am getting all input value like if I have add 3 divs those respective all values coming here each div has 2 input fields :
<script>
function updatebtn(el){
var id = $(el).attr('id');
$('input[type=text]:visible').each(function(){
console.log($(this).val());
})
})
</script>
Thanks
You need to use DOM traversal to find the input elements related to the button which was clicked. The simplest way to do that, given that you're already using jQuery, would be to use a delegated event handler for the dynamic button elements along with closest() and find().
It's also worth noting that your use of id attributes within the dynamic content is creating a lot more problems than it solves. I'd strongly suggest you remove them all and use common classes on all elements. That way you don't have the headache of having to manually update all the incremental ids when adding new content.
Try this:
jQuery(function($) {
var $traceContainer = $('#traces');
$('#add-button').click(function() {
var $div = $traceContainer.find('.trace:last').clone()
$div.find("input[name='t_x_axis']").val("");
$div.find("input[name='t_y_axis']").val("");
$traceContainer.append($div);
$div.find('span').text('Trace ' + ($div.index() + 1));
});
$traceContainer.on('click', '.update-trace', function() {
var $container = $(this).closest('table');
var xAxis = $container.find('input[name="t_x_axis"]').val();
var yAxis = $container.find('input[name="t_y_axis"]').val();
console.log(xAxis, yAxis);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add-button">Add Element</button>
<div id="traces">
<div class="trace">
<h4><span>Trace 1</span></h4>
<form>
<table>
<tbody>
<tr>
<td><label>X Axis:</label></td>
<td><input type="text" name="t_x_axis" class="t_x_axis" size="50">
</td>
</tr>
<tr>
<td><label>Y Axis:</label></td>
<td><input type="text" name="t_y_axis" class="t_y_axis" size="50"></td>
<td><button type="button" name="update-button-trace" class="update-trace">Update </button></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
Finally, note that I added a div container around each .trace to make appending them and retrieving their index simpler. Also note that the form within each .trace seems redundant and can probably be removed.
You can use find value as $div.find('.t_y_axis').val()
$(document).ready(function(){
$('#add-botton').click(function(){
var $div = $('div[id^="trace-div"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $trace1div = $div.clone(true).prop('id', 'trace-div'+num );
$trace1div.find('span').text('Trace ' + num);
$trace1div.find("input[name='t_x_axis']").attr("id", "x_axis_t"+num).val("");
$trace1div.find("input[name='t_y_axis']").attr("id", "y_axis_t"+num).val("");
$trace1div.find("button[name='update-button-trace']").attr("id", "update-button-trace"+num);
$div.after( $trace1div);
console.log( 'last t_y_axis => ' , $div.find('.t_y_axis').val());
console.log( 'last t_x_axis => ' , $div.find('.t_x_axis').val());
});
});
function updatebtn(el){
var id = $(el).attr('id');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type = "button" id = "add-botton" >Add Element </button>
<div id = "trace-div1" class = "trace">
<h4><span>Trace 1</span></h4>
<form>
<table>
<tbody>
<tr>
<td><label>X Axis: </label></td>
<td><input type="text" name="t_x_axis" class = "t_x_axis" id="x_axis_t1" size="50">
</td>
</tr>
<tr>
<td><label>Y Axis: </label></td>
<td><input type="text" name="t_y_axis" class = "t_y_axis" id="y_axis_t1" size="50"></td>
<td><button type = "button" name = "update-button-trace" class = "update-trace" id =
"update-botton-trace1" onclick="updatebtn(this)">Update </button></td>
</tr>
</tbody>
</table>
</form>
</div>
try using the following function.since both the input text boxes have their id you can use the same to get the value of the inputs.
Hope it helps!
function updatebtn(el) {
var x1 = document.getElementById('x_axis_t1');
var y1 = document.getElementById('y_axis_t1');
alert('x-axis is ',x1.value, ' and y-axis is', y1.value)
}
you need to develop your updatebtn().
function updatebtn(el){
var element = $(el),
parent_table = element.parentsUntil('table');
x_axis = parent_table.find('.t_x_axis').val();
y_axis = parent_table.find('.t_y_axis').val();
}

Why is my code returning "undefined" on innerHtml?

I made a listener to attatch an id "selectedRow" to the row a user has clicked on. The intent from there is be able to manipulate the data in that row; Previously i was using content editable however I'm trying to make it more obvious to the user that they are editing a row (this is for a project) so i've created an editing panel to do so. I've however ran in to some problems with a lot of data being returned as undefined when using .innerHTML when sending the TD to the input boxes.
I've tried using .HTML instead
$('tr').click(function() {
if(document.getElementById("SELECTEDROW")) {
var oldRow = document.getElementById("SELECTEDROW");
oldRow.classList.remove("selected");
$("#SELECTEDROW").removeAttr('id');
}
$(this).attr('id', 'SELECTEDROW');
selectedRow = document.getElementById("SELECTEDROW");
table = selectedRow.parentNode;
console.log("Row " + selectedRow.childNodes[1].innerHTML + " Selected");
selectedRow.classList.add("selected");
editRow();
});
function editRow() {
var currentTD = selectedRow.childNodes;
var inputs = document.getElementById("inputs").childNodes;
var i = 0;
for (i = 0; i < currentTD.length; i++) {
inputs[i].innerHTML = currentTD.html;
}
console.log('Now Editing:' + currentTD[1].innerHTML);
document.getElementById("editingPanel").style.display = "block";
document.getElementById("content").style.height = "49%";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Password</th>
</tr>
<tr>
<td>1</td>
<td>Bill Robbins</td>
<td>Conductor</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>01921202384</td>
<td>XxbillyboyxX#bossman.com</td>
<td>CaTsRbAe1967</td>
</tr>
<tr>
<td>2</td>
<td>Kat Robbins</td>
<td>Admin</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>019232042454</td>
<td>katrobs#gmail.com</td>
<td>thR33mel0ns</td>
</tr>
</table>
</div>
<div id="editingPanel">
<div id="inputFields">
<form id="inputs">
<input id="input1" type="text" name=""/>
<input id="input2" type="text" name="">
<input id="input3" type="text" name="">
<input id="input4" type="text" name="">
<input id="input5" type="text" name="">
<input id="input6" type="text" name="">
<input id="input7" type="text" name="">
<input id="input8" type="text" name="">
</form>
</div>
<div id="editButtons">
<button onclick="addRow()">New Row</button>
<button onclick="editRow()">Save Row</button>
<button onclick="removeRow()">Delete Row</button>
</div>
</div>
The expected output would be for each td's text to be copied into the input boxes.
You need to get the children properly. You also need to assign the text to the value property of the input, not its innerHTML
function editRow() {
// You need to get elements by tag name, not childNodes
var currentTD = selectedRow.getElementsByTagName("td");
// You need to get elements by tag name, not childNodes
var inputs = document.getElementById("inputs").getElementsByTagName("input");
var i = 0;
for (i = 0; i < currentTD.length; i++) {
console.log(inputs[i]);
console.log(currentTD[i]);
// set the "Value" of an input box, not its "innerHTML"
// also you need to apply the [i] to the currentTD because it is a list
inputs[i].value = currentTD[i].innerHTML;
}
You can try this:
$("body").on("click","tr",function(){ //Just in case you are going to use dynamic content, because the click method doesn't work on dynamically created/added elements
for(let i=0;i<7;i++){
$("#input"+(i+1)).val($(this).children()[i].innerHTML); //You are using jQuery for a reason, to simplify code, so avoid using unnecessary JS where you can by using simplified jQuery
}
});

ng-repeat and ng-scrollbar doesn't work together

I'm just starting Angular JS and trying to have a scrollbar appearing as I add an element in the list which would be populated in the box of the contents.
I installed ng-scrollbar from here. https://github.com/asafdav/ng-scrollbar
HTML:
<link rel="stylesheet" href="../dist/ng-scrollbar.min.css" >
<style>
.scrollme {
max-height: 100px;
}
</style>
</head>
<body>
<div ng-app="DemoApp">
<div class="container" ng-controller="DemoController">
<table border="0" width="100%">
<div class="scrollme" ng-scrollbar rebuild-on="rebuild:me" is-bar-shown="barShown">
<tr>
<th width="2%"></th>
<th width="14%">Name</th>
<th width="85%">Address</th>
</tr>
<tr>
<td>
<img src="addImageButton.png" ng-click="addRow()" />
</td>
<td class="inlineBlock">
<input type="text" ng-model="row.name" />
</td>
<td>
<input ng-model="row.addr" />
</td>
</tr>
<tr ng-repeat="row in rowList">
<td>
<img src="removeImageButton.png"ng-click="removeRow($index)" />
</td>
<td>{{row.name}}</td>
<td>{{row.client}}</td>
</tr>
</div>
</table>
</div>
</div>
</body>
JavaScript:
(function () {
'use strict';
var app = angular.module('DemoApp', ['ngScrollbar']);
app.controller('DemoController', DemoController);
function DemoController($scope) {
// portfolio and broker tabs
$scope.row = {}
$scope.row.name = "";
$scope.row.addr = "";
$scope.rowList = [];
// adding a row to list
$scope.addRow = function() {
var data = {};
data.name = $scope.row.name;
data.addr = $scope.row.addr;
$scope.rowList.push(data);
$scope.row.name = "";
$scope.row.addr = "";
console.log($scope.rowList);
}
// removing a row from the list
$scope.removeRow = function(obj) {
console.log('end' + $scope.rowList);
if(obj != -1) {
$scope.rowList.splice(obj, 1);
}
}
$scope.$on('scrollbar.show', function(){
console.log('Scrollbar show');
});
$scope.$on('scrollbar.hide', function(){
console.log('Scrollbar hide');
});
// $scope.$on('loopLoded', function(evt, index) {
// if(index == $scope.me.length-1) {
// $scope.$broadcast('rebuild:me');
// }
// });
}
})();
It's part of my code so it might not fully make sense. But the way it works is that if I pressed the addImageButton, it would add a row which will add a row on the web. And conversely, removeImageButton will delete a row which will show on the web immediately. I need a scroll bar appearing once it reaches the height 100px. I checked the last answer of the ng-scrollbar is not working with ng-repeat
as well but it didn't work. Would be great if I could get some help with the detailed explanation. :) Thanks!
Figured out! I need to put the broadcast method in addRow and removeRow methods. Also, I had to put the out from the

getElementById( ) not working on Dynamically assigned id

I have gone through google and some of SO questions (such as this & this) as well but I didn't find the solution.
I am working for validation of a dynamically generated rows in a table,initially I am trying to validate the first td, loop and alert is working all fine but document.getElementById() is giving a null value. The script is at the very bottom of the page.
and here is the JS code.
edit: I have added the code, and what I am trying to do is display the error (Please fill) when field is left blank on the click of submit button and hide it when it is filled.
$(function(){
$(document).on("click",".addRowAux",function(){
/*var valanx1 = $(this).parents("tr").children("td:nth-child(2)").children("input").val();
var valanx2 = $(this).parents("tr").children("td:nth-child(3)").children("input").val();
var valanx3 = $(this).parents("tr").children("td:nth-child(4)").children("select").val();
var valanx4 = $(this).parents("tr").children("td:nth-child(4)").children("input").val();*/
var countrow= $("#annextable tr").length;
/*countrow++;*/
if(countrow<11)
{
$("#aux").append('<tr><td align="center">'+countrow+'</td><td align="center"><input type="text" name="ref_name[]" id="ref_name"/><span id="refNm_error">Please fill</span></td><td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td><td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td><td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td><td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td><td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td><td align="center"><span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td></tr>');
}
else
{
//countrow--;
alert("Can not add more then 10 record.");
}
});
});
$(document).on('click', '#removeRowaux', function () { // <-- changes
var countrow= $("#annextable tr").length;
if(countrow>3)
{
$(this).closest('tr').remove();
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{
tblObj.rows[i+1].cells[0].innerHTML = i+1;
tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1);
////alert(kj);
//document.getElementById("refNm_error").id ="refNm_error"+j;
}
}
else{
alert("you can not delete this")
}
});
$(document).on('click', '#hods', function () {
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1)
var j=tblObj.rows[i+1].cells[1].getAttribute("delThis");
document.getElementById("refNm_error").id ="refNm_error"+j;
}
});
$(function(){
$(document).on('change', '.rel_type', function() {
var relation = $(this).val();
if(relation =='OT'){
$(this).next("input").show();
$(this).next("input").val("Please Specify");
}
else{
$(this).next("input").hide();
$(this).next("input").val("")
}
});
});
function yoVal(){
var refNm =document.getElementsByName('ref_name[]');
for(var i=0;i<=refNm.length;i++) {
if(refNm[i].value==""){
alert("success");
}
else{
var ch ='refNm_error'+(i+1);
alert(ch);
//document.getElementById(ch).style.display = "none";
alert("fail")
}
}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="refForm">
<table width="99%" border="1" id="annextable" style="border-collapse:collapse" align="center">
<thead>
<tr style="background:#ddd;">
<th>S.No</th>
<th>Name</th>
<th>Designation</th>
<th>Address</th>
<th>Email</th>
<th>Mobile</th>
<th>PAN</th>
<th>Action</th>
</tr>
</thead>
<tbody id="aux">
<tr>
<td align="center">1</td>
<td align="center"><input type="text" name="ref_name[]" id="ref_name"/><br/><span id="refNm_error">Please fill</span></td>
<td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td>
<td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td>
<td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td>
<td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td>
<td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td>
<td align="center">
<span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td>
</tr>
</tbody></table>
<input type="button" onclick="yoVal()" value="Test" id="hods"/>
</div>
Because you are adding extra quotes in beginning and end in variable k. use:
var k = 'refNm_error' + (i+1);
You might need to reload the DOM after adding dynamic elements.
This link might help
Update, when you created your dynamic table rows for the table you didn't assign unique ids for input elements. So I updated the addRow handler:
$(document).on("click", ".addRowAux", function () {
to add unique input ids, like following:
$("#aux").append('<tr><td align="center">' + countrow + '</td><td align="center"><input type="text" name="ref_name[]" id="ref_name_' + countrow + '"/><span id="refNm_error_' + countrow + '">Please fill</span>...
and also I changed in the code:
<span id="removeRowaux">Remove</span>
to use class instead of an id:
<span class="removeRowaux">Remove</span>
Now the remove row handler listens to events from spans with class removeRowaux:
$(document).on('click', '.removeRowaux', function ()
Now the remove row functionality works and there are no spans with identical ids. So I don't think there was anything wrong with getElementById() in the code - it works fine :-)
Updated Fiddle

Using Javascript How to loop through a div containing checkboxes and get the value checked from each check box

I have a table with each row containing a cell that has 8 check boxes(Column4)
Here is an example
<table id="enc-assets" class="table">
<thead>
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4(CONTAINS OPTIONS)</th>
</thead>
<tbody>
<tr>
<td id="sc-isrc"></td>
<td id="sc-filename"></td>
<td id="sc-path" hidden></td>
<td id="sc-platforms">
<div id="sc-inline" style="display: inline-block;">
<div >
<div ng-repeat="p in products ">
<label id="enc"><input id="Platform" ng-checked="prod[p.name]" ng-model="prod[p.name]" ng-init="prod[p.name] = true" type="checkbox"/></label>
</div>
</div>
</div>
</td>
<td>
</td>
<td><br/><br/><button id="enqueuebtn" type="button" ng-click="Show(test)" class="btn-primary"></button></td>
</tr>
</tbody>
</table>
I am trying to loop through each row and assign values from each cell into an object .
I am having problems getting the value checked from the cell that contains the 8 check boxes. I can get values from the other cells just fine.
I have tried the following:
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms div div").each(function() {
var platform, selected;
selected = $(this).find('#Platform div label input').checked;
if (selected === true) {
platform = $(this).find('#enc').text();
This is the part that I am not sure if works:
selected = $(this).find('#Platform div label input').checked;
Do I have the correct nesting here to get the values from the check boxes?
Try this:
jsFiddle here
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms>div>div").each(function() {
alert( $(this).attr('id') );
var platform, selected;
selected = $(this).find('#Platform');
if(selected.is(':checked')) {
alert('Checked');
}
platform = $(this).find('#enc').text();
alert(platform);
}); //END each #sc-platforms>div>div
}); //END each #enc-assets tbody tr

Categories