This is what I am currently trying to achieve:
I am trying to clone a form and change the input name. How would I pull this off.
JS:
$(document).ready(function() {
var counter = 0;
var MAX_FIELDS = 3;
var MIN_FIELDS = 1;
var form = $('.force-group');
$('#add').on('click', function(e) {
if (counter < MAX_FIELDS) {
//$(".form-group").clone().appendTo("#forceForm");
$.each(form, function(i) {
var clone = $('.force-group').first().clone();
clone.children().val("");
$(this).parent().append(clone);
if (counter == 0) {
$("b:eq(1)").html("<b> Force 2</b>");
};
if (counter == 1) {
$("b:eq(3)").html("<b> Force 3</b>");
};
if (counter == 2) {
$("b:eq(5)").html("<b> Force 4</b>");
};
});
counter++;
};
});
html:
<#import "template.ftl" as layout />
<#layout.template title="Force" js="/js/force.js" css="/css/force.css">
<h3 class = "text-center">Total Force</h3>
<hr>
<div class="col-md-6 col-md-offset-3 col-xs-8 col-xs-offset-2">
<div class="force-selector input_fields_wrap">
<a id = 'add' href="#" class="btn btn-primary col-md-5">Add Force</a>
<a id = 'remove' href="#" class="btn btn-warning col-md-5 col-md-offset-2">Remove Force</a>
</div>
</div>
<div class="col-md-6 col-md-offset-">
<div class="col-xs-12">
<div class = "well" id="force-input">
<form id = "forceForm" class = "form-horizontal" method = "POST" autocomplete="off">
<fieldset>
<h4 class="text-center" id="form-title"><strong>Input</strong></h4>
<div class="form-group force-group">
<label class = "control-label col-md-2"><b>Force 1</b></label>
<label class = "control-label col-md-2">Magnitude</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0force" autocomplete="off">
</div>
<label class = "control-label col-md-2">Angle</label>
<div class = "col-md-3 force-info">
<input type = "text" class="form-control" name="0angle" autocomplete="off">
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<div class = "col-md-5">
<table id = "forceChart" class="table table-striped table-hover">
<thead>
<tr class="table">
<th class="head-pad">Total Force</th>
</tr>
</thead>
<tbody>
<tr class="table">
<td class="pad">Net Force:</td>
</tr>
</tbody>
</thead>
<tbody>
<tr class="table">
<td class="pad">Direction:</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class = "col-md-4 col-md-offset-4 col-xs-6 col-xs-offset-3">
<div class="form-group">
<div class = "col-md-6 col-xs-offset-3">
<input id = "calculate" class = "btn btn-success btn-block" type="submit" value="Calculate!">
</div>
</div>
</div>
This is the jsfiddle link right here:
Click here for the link.
PS: I am using a templater so the jsfiddle will look kinda bad.
I am new to jQuery and I have been searching around a solution but I seem to get stuck with it.
I tried using the .last() with the attr edit but that seems not to do anything.
To change an input name just use attr() method
$('input').attr('name', 'yourNewname');
and I remarque that you have input without Id so you should use one of those methods:
1/ give each input an Id for example #input1 #input2
$('#input1').attr('name', 'yourNewname1'); // change the name of first input
$('#input2').attr('name', 'yourNewname2'); // change the name of first input
or
you can use eq()
$('input').eq(0).attr('name', 'yourNewname1'); // change the name of first input
$('input').eq(1).attr('name', 'yourNewname2'); // change the name of first input
To change any attribute including name you can do this
$('#myInputFieldId').attr('name','new_name')
Hope it helps
Try this: $('input[name="0angle"]').attr('name', 'new-name');
Related
hi I am trying to follow the below tutorial for my formset only i find problem in part:
container.insertBefore (newForm, addButton)
and the error that presents me is the following:
calculos.js: 195 Uncaught TypeError: Cannot read properties of undefined (reading 'childNode')
I've already tried everything but can't find the childNode
JS
let parteForm = document.querySelectorAll(".part-form")
let container = document.querySelector("#part-form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing
addButton.addEventListener('click', addForm)
function addForm(){
//e.preventDefault()
let newForm = parteForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
//parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode)
//#part-form-container.insertbefore(div.part-form,)
totalForms.setAttribute('value', `${formNum+1}`)
}
HTML
<form method="POST" id="part-form-container">
{% csrf_token %}
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row mb-3">
<div class="col-md-12">
<div class="mb-3">
<label for="verticalnav-email-input">Summary</label>
{{presupuestosparteform.resumen}}
</div>
</div>
</div>
<h4 class="card-title">Parts list</h4>
<p class="card-title-desc">Add the parts that you need to include.</p>
<input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" />
<div class="table-responsive">
<table class="table table-bordered table-nowrap align-middle" id="childTable1">
<tbody>
{{ formset.management_form }}
{% for form in formset %}
<div class="part-form">
<tr>
<td>
{{form.codigo}}
</td>
<td>
{{form.descripcion}}
</td>
</tr>
</div>
{% endfor %}
</tbody>
</table>
</form>
Maybe I don't understand your code but to me seems that some closing "div" tags are missing. My suggestion is to reorganize your code and clean it.
Now for what concern the bug
(https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore):
The insertBefore() method of the Node interface inserts a node before
a reference node as a child of a specified parent node.
You just have to make sure that the cointer contains the element you want to insert before, so i think that just closing open div tags will solve.
I also noticed that there is no element with Id="id_form-TOTAL_FORMS", so the setAttribute can't work.
let parteForm = document.querySelectorAll(".part-form")
let container = document.querySelector("#part-form-container")
let addButton = document.querySelector("#add-form")
let totalForms = document.querySelector("#id_form-TOTAL_FORMS")
let formNum = parteForm.length-1 // Get the number of the last form on the page with zero-based indexing
addButton.addEventListener('click', addForm)
function addForm(){
//e.preventDefault()
let newForm = parteForm[0].cloneNode(true)
let formRegex = RegExp(`form-(\\d){1}-`,'g')
formNum++
newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)
container.insertBefore(newForm, addButton)
//parentnode.insertbefore(newnode,elnodoantesdelcualseinsertanewnode)
//#part-form-container.insertbefore(div.part-form,)
}
<form method="POST" id="part-form-container">
<label for="verticalnav-email-input">Summary</label>
<h4 class="card-title">Parts list</h4>
<p class="card-title-desc">Add the parts that you need to include.</p>
<input type="button" class="btn btn-block btn-default btn-success mb-4" id="add-form" onclick="addForm()" value="+ Add part" />
<tbody>
<div class="part-form">
<tr>
<td>Data-1</td>
<td>Data-2</td>
</tr>
</div>
</tbody>
</table>
</form>
This is a stupid question but I am getting frustrated and hoping for some help. Why won't my values output to the console after submitting? Anyone notice issues?
var todos = "";
// user clicked on the add button in the to-do field add that text into the to-do text
$('#add-todo').on('click', function(event) {
event.preventDefault();
//values per text box
todos = $("#todo-input").val().trim();
//test values from textbox
console.log(todos);
HTML
<div class ="col-4">
<form role = "form">
<div class = "form-group row">
<div class = "To-Do-List">
<label for="todo-input">Add Your To Do List Here:</label>
</div>
<input class="form-control" id="todo-input" type = "text">
<tbody id = "table_body">
</tbody>
</div>
</form>
</div>
<div class="button">
<button class ="btn btn-danger" id="add-todo" type="submit">Add</button>
</div>
You only need close whit "})"
var todos = "";
// user clicked on the add button in the to-do field add that text into the to-do text
$('#add-todo').on('click', function(event) {
event.preventDefault();
//values per text box
todos = $("#todo-input").val().trim();
//test values from textbox
console.log(todos);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="col-4">
<form role = "form">
<div class = "form-group row">
<div class = "To-Do-List">
<label for="todo-input">Add Your To Do List Here:</label>
</div>
<input class="form-control" id="todo-input" type = "text">
<tbody id = "table_body">
</tbody>
</div>
</form>
</div>
<div class="button">
<button class ="btn btn-danger" id="add-todo" type="submit">Add</button></div>
I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot:
Screenshot of the Page
I was successful in doing this applying the following code:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find('input:text').val('') //Clear the Input fields of the cloned DIV
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:0px;clear:both"></div>
<div style="float:right">
<span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span>
</div>
<div style="height:0px;clear:both"></div>
<div>
<div id="ext_int_div_1">
<div class="section">
<fieldset class="scheduler-border">
<legend class="scheduler-border">External Interface 1</legend>
<div class="sectionContent" style="border:0px solid grey;width:75%">
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Name</label>
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="vl_name_1" id="vl_name_1" placeholder="Name"/>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connectivity Type</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1">
<option value="VIRTIO">VIRTIO</option>
<option value="">None</option>
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connection point Ref</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_con_ref_1" id="vl_con_ref_1" />
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
</div>
</fieldset>
<div style="height:2px;clear:both;"></div>
</div>
</div>
</div>
<input type="hidden" name="vl_count" id="vl_count" value="1" />
Now i have a new issue, i need to make sure that the ID's of the elements withing the DIV are unique too, for example the the ID = "vl_name_1" for the first input box must be changed to "vl_name_2" when creating the creating the clone.
I tried the following example and added the snipped within my addVL() function just to see if any changes happen to my div's:
$("#ext_int_div_1").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + clone.id); });
However, the above code got me nothing ( i am pretty sure the above piece of code is rubbish since i have no clue what it is doing).
Help appreciated here.
Thank you
I hope the snippet below helps.
$(document).ready(function () {
$sharerCount = 1;
$('#addSharer').click(function() {
if($sharerCount < 5) {
$('#sharer_0').clone().attr('id', 'sharer_' + $sharerCount).insertAfter('.sharers:last').find("*[id]").attr('id', 'input_' + $sharerCount).val("").clone().end();
$sharerCount += 1;
}
else {
$('#addSharer').prop('disabled', 'true');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form">
<div class="form-group">
<label class="control-label col-sm-3 col-xs-12">Share With<span class="red-text">*</span></label>
<div class="col-sm-9 col-xs-12">
<div id="sharer_0" class="field-group sharers">
<input id="input_0" type="text" class="form-control field-sm">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9 col-xs-12">
<button id="addSharer" type="button" class="btn btn-success">Add Another</button>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
I did the following and solved my problem:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find("*[id]").each(function(){
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength-1], vl_cnt);
$(this).attr('id', newId);
});
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
Thank you #ProblemChild for giving me the pointer in the right direction, I cannot upvote #ProblemChild for providing partial solution.
I am working on a web development project and I am using bootstrap tabs there. I am dynamically creating them using add and remove input field section, according to that number of inputs I am creating the tabs in the same page using ajax.
In that tabs I have the same form with same input fields. There is a input field with autocomplete function in that form. I am taking data from mysql to that field. My problem is autocomplete is only working in the first tab not in the others. Autocomplete field label is Responsible
This is my function.
function autocompletT() {
var min_length = 0;
var keyword = $('#responsible_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh2.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#responsible_id_list').show();
$('#responsible_id_list').html(data);
$('#responsible_id_list li').click(function() {
var txx = $(this).text();
var tcust = $(this).val();
});
}
});
} else {
$('#responsible_id_list').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#responsible_id').val(item);
// hide proposition list
$('#responsible_id_list').hide();
}
Portion of My code
<div class="col-md-6 entire_div">
<div class="panel with-nav-tabs panel-primary">
<div class="panel-heading">
<ul class="nav nav-tabs">
<?php
for ($row = 0; $row < $agenda_size; $row++) {
$p_agenda = $mAgenda[$row];
$row_plus = $row + 1;
?>
<li><?php echo $p_agenda; ?></li>
<?php
}
?>
</ul>
</div>
<div class="panel-body">
<div class="tab-content">
<?php
for ($row = 0; $row < $agenda_size; $row++) {
$p_agenda = $mAgenda[$row];
$row_plus = $row + 1;
?>
<div class="tab-pane fade" id="<?php echo $row_plus;?>">
<!-- form -->
<form class="ws-validate">
<div class="form-group">
<label for="responsible_id" class="control-label">Responsible</label>
<input type="text" class="form-control" id="responsible_id" name="zip" placeholder="Select Responsible Person" onkeyup="autocompletT()" >
<ul id="responsible_id_list"></ul>
</div>
<div class="form-group">
<button id="submit_btn" class="btn btn-primary">Add</button>
<!-- <input id="submit_btn" type="submit" value="Add"> -->
</div>
</form>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="mytable" class="table table-bordred table-striped">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>Action</th>
<th>Start Date</th>
<th>Due Date</th>
<th>Status</th>
<th>Responsible</th>
</thead>
<tbody>
</tbody>
</table>
<div class="delete_b_class">
<button id="delete_row" class="btn btn-danger">Delete Row</button>
</div>
</div>
</div>
</div>
<div class="submit_all_div">
<input class="submit_all_b" id="submit" onclick="myDataSendFunction()" type="button" value="Submit">
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
ids are unique
Each element can have only one id
Each page can have only one element with that id
classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Probably, you are creating so many #responsible_id and #responsible_id_list with your php code.
So, as IDs must be unique. use the a unique ID for each search field (which is responsible_id ) and list (which is responsible_id_list ) here.
You can get a idea from here:- remove onkeyup="autocompletT" function from the input and add jquery event like this. then find the next responsible_id_list then populate list and append list to it.
$('.responsible_id').keyup(function(){
var min_length = 0;
var keyword = $(this).val() ;
///others codes
//say
var list='';
$(this).next('.responsible_id_list').html(list);
})
You might need to re-initialize the autocomplete on the inputs every time. Go through this question to get a braoder picture. This should solve your concerns
I want to retain the selected check boxes as is even when I am
changing my search query. Initially I am posting some query in search
and selecting one of the resulted values, Now if I change my search
query, then New values will be my result. But I want to retain the
checkbox selected for the previous values...
`
//Demo of Searching and Sorting Table with AngularJS
var myApp = angular.module('myApp',[]);
myApp.controller('TableCtrl', ['$scope', function($scope) {
$scope.allItems = getDummyData();
$scope.resetAll = function()
{
$scope.filteredList = $scope.allItems ;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
}
$scope.add = function()
{
$scope.allItems.push({EmpId : $scope.newEmpId, name : $scope.newName, Email:$scope.newEmail});
$scope.resetAll();
}
$scope.search = function()
{
$scope.filteredList = _.filter($scope.allItems,
function(item){
return searchUtil(item,$scope.searchText);
});
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
}
$scope.resetAll();
}]);
/* Search Text in all 3 fields */
function searchUtil(item,toSearch)
{
/* Search Text in all 3 fields */
return ( item.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.Email.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || item.EmpId == toSearch
)
? true : false ;
}
/*Get Dummy Data for Example*/
function getDummyData()
{
return [
{EmpId:2, name:'Jitendra', Email: 'jz#gmail.com'},
{EmpId:1, name:'Minal', Email: 'amz#gmail.com'},
{EmpId:3, name:'Rudra', Email: 'ruz#gmail.com'}
];
}
.icon-search{margin-left:-25px;}
<br /> <br />
<div ng-app="myApp">
<div ng-controller="TableCtrl">
<div class="input-group">
<input class="form-control" ng-model="searchText" placeholder="Search" type="search" ng-change="search()" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
</div>
<table class="table table-hover data-table sort display">
<thead>
<tr>
<th class="EmpId"> <a href="" ng-click="columnToOrder='EmpId';reverse=!reverse">EmpId
</a></th>
<th class="name"> Name </th>
<th class="Email"> Email </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in filteredList | orderBy:columnToOrder:reverse">
<td><input type="checkbox" name="test" />{{item.EmpId}}</td>
<td>{{item.name}}</td>
<td>{{item.Email}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-xs-3">
<input type="text" ng-model="newEmpId" class="form-control" placeholder="EmpId">
</div>
<div class="col-xs-3">
<input type="text" ng-model="newName" class="form-control" placeholder="Name">
</div>
<div class="col-xs-4">
<input type="email" ng-model="newEmail" class="form-control" placeholder="Email">
</div>
<div class="col-xs-1">
<button ng-click="add()" type="button" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</div> <!-- Ends Controller -->
</div>
`Fiddle
Try to add ng-model="item.selected" to your checkbox tag
<td><input ng-model="item.selected" type="checkbox" name="test" />{{item.EmpId}}</td>
Works for me, hope it helps.
Looks like this is happening because you are resetting the items here:
if($scope.searchText == '')
{
$scope.filteredList = $scope.allItems ;
}
and allItems doesn't tell anywhere if the checkbox needs to be selected on not. I would suggest you to update the code where you are creating the checkboxes, something like:
<td><input type="checkbox" name="test" ng-model=item.selected ng-checked=item.selected/>
Note that I have updated the item to have a 'selected' field which will tell if that item is selected or not(default could be false). While creating the checkbox I have linked the model using ng-model=item.selected
Updated fiddle at http://jsfiddle.net/3a3zD/194/