I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to:
HTML
<html>
<head>
<title>gffdfdf</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/static/jquery.formset.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="" method="post" class="">
{% csrf_token %}
<h2> Team</h2>
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} : {{ field }}
{% endfor %}
{{ form.player.management_form }}
<h3> Product Instance(s)</h3>
<table id="table-product" class="table">
<thead>
<tr>
<th>player name</th>
<th>highest score</th>
<th>age</th>
</tr>
</thead>
{% for player in form.player %}
<tbody class="player-instances">
<tr>
<td>{{ player.pname }}</td>
<td>{{ player.hscore }}</td>
<td>{{ player.age }}</td>
<td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
</tbody>
{% endfor %}
</table>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
<script>
var i = 1;
$("#input_add").click(function() {
$("tbody tr:first").clone().find(".data_input").each(function() {
if ($(this).attr('class')== 'tr_clone_add btn data_input'){
$(this).attr({
'id': function(_, id) { return "remove_button" },
'name': function(_, name) { return "name_remove" +i },
'value': 'Remove'
}).on("click", function(){
var a = $(this).parent();
var b= a.parent();
i=i-1
$('#id_form-TOTAL_FORMS').val(i);
b.remove();
$('.player-instances tr').each(function(index, value){
$(this).find('.data_input').each(function(){
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +index + "-" + tData
}
});
})
})
})
}
else{
$(this).attr({
'id': function (_, id) {
var idData= id;
var splitV= String(idData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
},
'name': function (_, name) {
var nameData= name;
var splitV= String(nameData).split('-');
var fData= splitV[0];
var tData= splitV[2];
return fData+ "-" +i + "-" + tData
}
});
}
}).end().appendTo("tbody");
$('#id_form-TOTAL_FORMS').val(1+i);
i++;
});
</script>
</body>
</html>
the above code creates a form with three fields i.e player name, highest score and age with a add more button
but according to this it should create the following :
<!-- First row of the table -->
<tr>
<td><input type="text" name="form-0-name" id="id_form-0-name" /></td>
<td>
<input type="number" name="form-0-quantity" id="id_form-0-quantity" />
</td>
<td><input type="number" name="form-0-price" id="id_form-0-price" /></td>
<td>
<input
id="input_add"
type="button"
name="add"
value=" Add More "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- Second row of the table -->
<tr>
<td><input type="text" name="form-1-name" id="id_form-1-name" /></td>
<td>
<input type="number" name="form-1-quantity" id="id_form-1-quantity" />
</td>
<td><input type="number" name="form-1-price" id="id_form-1-price" /></td>
<td>
<input
id="remove_button"
type="button"
name="remove_button1"
value=" Remove "
class="tr_clone_add btn data_input"
/>
</td>
</tr>
<!-- more inline formset are going to rendered here -->
But when I create another row in the form it creates another row with same name and id.
See:
<tbody class="player-instances">
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="input_add-0-undefined" type="button" name="add-0-undefined" value=" Add More " class="tr_clone_add btn data_input"> </td>
</tr>
<tr>
<td><input type="text" name="form-0-pname" id="id_form-0-pname"></td>
<td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td>
<td><input type="number" name="form-0-age" id="id_form-0-age"></td>
<td> <input id="remove_button-1-undefined" type="button" name="name_remove1-1-undefined" value="Remove" class="tr_clone_add btn data_input"> </td>
</tr></tbody>
Why does it not add the row with updated name and id ?
Update:
Models.py
class Player(models.Model):
pname = models.CharField(max_length=50)
hscore = models.IntegerField()
age = models.IntegerField()
def __str__(self):
return self.pname
class Team(models.Model):
tname = models.CharField(max_length=100)
player= models.ManyToManyField(Player)
def __str__(self):
return self.tname
Views.py
def post(request):
if request.POST:
form = TeamForm(request.POST)
print("form", form)
form.player_instances = PlayerFormset(request.POST)
if form.is_valid():
team= Team()
team.tname= form.cleaned_data['tname']
team.save()
if form.player_instances.cleaned_data is not None:
for item in form.player_instances.cleaned_data:
player = Player()
player.pname= item['pname']
player.hscore= item['hscore']
player.age= item['age']
player.save()
team.player.add(player)
team.save()
else:
form = TeamForm()
return render(request, 'packsapp/employee/new.html', {'form':form})
Forms.py
class PlayerForm(forms.Form):
pname = forms.CharField()
hscore= forms.IntegerField()
age = forms.IntegerField()
PlayerFormset= formset_factory(PlayerForm)
class TeamForm(forms.Form):
tname= forms.CharField()
player= PlayerFormset()
Related
I'm looking to add multiple products to a table from a dynamically generated list, where each item has a button to add it to the table. It's not working now because when I click a product, it adds it to the table and then if I click another item in the list, it just replaces the first item in the list. This list is dynamically generated because it's coming from a database.
html:
<form action="insert.php" method= "POST" name = "productsForm">
<table>
<tr>
<th><label>Customer Name:</label></th>
<th><label>Phone:</label></th>
<th><label>Email:</label></th>
<th><label>RO | PO:</label></th>
<th><label>Address:</label></th>
</tr>
<tr>
<td><input type="text" name="txtCustomerName" id = "txtCustomerName"></td>
<td><input type="text" name="txtPhone" id = "txtPhone"></td>
<td><input type="text" name="txtEmail" id= "txtEmail"></td>
<td><input type="text" name="txtRopo" id= "txtRopo"></td>
<td><input type="text" name="txtAddress" id= "txtAddress"></td>
</tr>
<tr>
<th><label>SKU:</label></th>
<th><label>Product Name:</label></th>
<th><label>Quantity:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price:</label></th>
</tr>
<tr>
<td><input type="text" name="txtSKU" id = "txtSKU"></td>
<td><input type="text" name="txtProductName" id= "txtProductName"></td>
<td><input type="text" name="txtQuantity" id= "txtQuantity"></td>
<td><input type="text" name="txtRetailPrice" id= "txtRetailPrice"></td>
<td><input type="text" name="txtListPrice" id= "txtListPrice"></td>
</tr>
<tr>
<td><input type="text" name="txtSKU1" id = "txtSKU1"></td>
<td><input type="text" name="txtProductName1" id= "txtProductName1"></td>
<td><input type="text" name="txtQuantity1" id= "txtQuantity1"></td>
<td><input type="text" name="txtRetailPrice1" id= "txtRetailPrice1"></td>
<td><input type="text" name="txtListPrice1" id= "txtListPrice1"></td>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal"><input type="button" value= "Add" id = "addTotals"></button> </th>
</tfoot>
</table>
<button type="submit" name="submitOrder">Submit</button>
</form>
JavaScript - this function makes the list:
function populateProductList(jsonArr){
var html = "";
html += `<ol id="myULProducts">`;
for(var x = 0; x < jsonArr.length; x++){
html += `
<li SKU = "${jsonArr[x].SKU}">
<a href="#" class="products">
<strong>Product SKU:</strong> ${jsonArr[x].SKU}
<br><strong>Product Name:</strong> ${jsonArr[x].product_name}
<br><strong>Retail Price:</strong> ${jsonArr[x].retail_price}
<br><strong>List Price:</strong> ${jsonArr[x].list_price}
<br><br></a>
<button type="button" class="btnAddProductToOrder">Add to Order</button>
</li>
</div>`
}
html += `</ol>`;
var ul = document.createElement("ul");
ul.innerHTML = html;
var tableContainer = document.getElementById("product-list-container");
tableContainer.innerHTML = "";
tableContainer.appendChild(ul);
tableContainer.addEventListener("click", function(evt){
//populateCardGroupList();
var target = evt.target;
//if statement to see if the classList has a button edit
if(target.classList.contains("btnAddProductToOrder")){
//get the id of the card group clicked
var selectedId = target.closest("li").getAttribute("SKU");
//get the card group attached to that id and pass it the rest of the json Array of objects
var selectedProduct = getProductId(selectedId, jsonArr);
populateOrderFormProducts(selectedProduct);
}
});
}
JavaScript - this function adds the clicked item in the list to the product table below
function populateOrderFormProducts(jsonArr){
document.getElementById("txtSKU").value = jsonArr.SKU;
document.getElementById("txtProductName").value = jsonArr.product_name;
document.getElementById("txtQuantity").value = 1;
document.getElementById("txtRetailPrice").value = jsonArr.retail_price;
document.getElementById("txtListPrice").value = parseFloat(jsonArr.list_price);
}
i cant get both values on selecting dropdown options. Only one output gives not both. Please help to solve this. i want to show value in output field when i select fahrenheiet it should give in celsius and vice versa.
<script type="text/javascript">
function findCelsius()
{
var vals = document.getElementById("convert").value;
if(vals = "F"){
var v = document.getElementById("vlues").value;
var celsius = (v - 32) * 5/9;
var result = Math.ceil(celsius);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Farenheit to Celsius!";
}
else if(vals = "C")
{
var va = document.getElementById("vlues").value;
var fah = (va * 9/5) + 32;
var result = Math.ceil(fah);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Celsius to Fahrenheit!";
}
}
</script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Conversion</title>
</head>
<body>
<h2>Convert Temprature</h2>
<form name="conversion">
<table>
<tr>
<td>
Enter a Value
</td>
<td>
<input type="number" name="vlue" value="" id="vlues">
<select id="convert" onChange="findCelsius()">
<option value="F">Farenheight(F°)</option>
<option value="C">Celsius(C°)</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="text" id="answer" name="result" value="">
</td>
</tr>
<tr>
<td>
Answer:
</td>
</tr>
<tr>
<td>
</td>
<td>
<span id="output"></span>
</td>
</tr>
</table>
</form>
</body>
</html>
If Condition declaration was wrong use == instead =
function findCelsius() {
var vals = document.getElementById("convert").value;
if (vals == "F") {
var v = document.getElementById("vlues").value;
var celsius = (v - 32) * 5 / 9;
var result = Math.ceil(celsius);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Farenheit to Celsius!";
} else if (vals == "C") {
var va = document.getElementById("vlues").value;
var fah = (va * 9 / 5) + 32;
var result = Math.ceil(fah);
document.getElementById("answer").value = result;
document.getElementById("output").innerHTML = "You Selected: Celsius to Fahrenheit!";
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Conversion</title>
</head>
<body>
<h2>Convert Temprature</h2>
<form name="conversion">
<table>
<tr>
<td>
Enter a Value
</td>
<td>
<input type="number" name="vlue" value="" id="vlues">
<select id="convert" onChange="findCelsius()">
<option value="">select</option>
<option value="F">Farenheight(F°)</option>
<option value="C">Celsius(C°)</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="text" id="answer" name="result" value="">
</td>
</tr>
<tr>
<td>
Answer:
</td>
</tr>
<tr>
<td>
</td>
<td>
<span id="output"></span>
</td>
</tr>
</table>
</form>
</body>
</html>
I have a text area which gets populated after click of a button .
<textarea rows="4" cols="50" id="4321">
{{ data.classi}}
</textarea>
Now i want something to happen after it gets populated . I have tried onchange and a few other options but they only work after the textarea is populated an we change its content .
I want it to happen right after the textarea is populated with json from back-end . How can this be done
$('#4321').on('change', function() {
alert( this.value ); // or $(this).val()
});
This doesn't work
I am pasting the entire code here in case it helps
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
<script src="jquery.json-view.js"></script>
<link href="jquery.json-view.css" rel="stylesheet"></link>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body ng-controller="DebugController">
<div>
<input type="text" ng-model="query" placeholder="Search Query">
<input type="text" ng-model="pog" placeholder="Enter No of POGs">
<button ng-click="onSearch()" class="button" id ="abcd">Search</button>
</div>
<textarea rows="4" cols="50" id="abc">
{{ data.classi}}
</textarea>
<div>
<h4>Parameters</h4>
<table>
<tr ng-repeat="x in data.p ">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Classifier Scores</h4>
<table>
<tr>
<th>Category URL</th>
<th>Additive Boost</th>
</tr>
<tr ng-repeat="x in data.classifier">
<td>{{ x[0] }}</td>
<td>{{ x[1] }}</td>
</tr>
</table>
</div>
<div>
<h4>Product Groups (POGs)</h4>
<table>
<tr>
<th>Id</th>
<th>Details</th>
<th>Score</th>
<th>HPSA Score</th>
<th>BF Score</th>
<th>Word Match</th>
<th>Classifier Score</th>
<th>QUL Score</th>
</tr>
<tr ng-repeat="x in data.items | limitTo: limit " >
<td><a href="{{ x.get }}">{{ x.id }}</td>
<td>
<p><b>{{ x.name[0] }}</b></p>
<p><u>Brand</u>: {{ x.Brand }}; <u>Category URL</u>: {{ x.mlnURL }};<u>Price</u>: Rs {{x.Price}} </p>
</td>
<td>
<p><b>{{ x.score }}</b></p>
Classifier Score: {{ x.cscore }} <br>
Document Score: {{ x.sscore }} </p>
</td>
<td>
<p><b> {{ x.hpsaScore_default }} </b></p>
</td>
<td>
<p><b> {{ x.bf_value }} </b></p>
</td>
<td>
</td>
<td>
<p> <b> {{ x.cscore }} </b></p>
</td>
<td>
</td>
</tr>
</table>
</div>
<div>
<h4>Solr Query</h4>
<p>{{ data.query }}</p>
</div>
<script>
var pog;
$(function() {
$('#abc').on('input', function() {
alert("hi");
});
});
</script>
</body>
</html>
The controller of the page
var app = angular.module('myApp', []);
app.controller('DebugController', function($scope, $http) {
$scope.onSearch = function () {
$scope.data = {}
number = $scope.pog
$scope.limit = number
$http.get('/search?q=' + $scope.query)
.then(function(response) {
console.log(response)
params = []
urls = []
for (p in response.data.params) {
params.push([p, response.data.params[p]])
}
for (i in response.data.bf_value) {
for(j in response.data.bf_value[i]) {
}
}
for( t in response.data.items ) {
p =""
for ( s in response.data.bf_value ) {
p+=response.data.bf_value[s][t]
}
response.data.items[t].bf_value = p
}
console.log(response.data.bf_value);
$scope.data = response.data
$scope.data.classi = response.data.classify
$scope.data.p = params
$scope.data.u = urls
});
}
});
Use the input event. (mdn)
$('#hello').on('input', function() {
console.log($(this)[0].value) // console logs the value of the textarea
});
$("#4321").change(function(){
alert("The text has been changed.");
});
This should work.
i want to verify my form value on submit, but it move directly to the action without executing the function onsubmit, can anyone please help me.
here is my html page:
...
<script src="{% static 'js/formulaire.js' %}" type="text/javascript"></script>
<script type="text/javascript">
function isValide(){
var resultat = true
if (!isAlpha(document.getElementById('titre').value) || document.getElementById('titre').value == "" {
resultat = false:
document.getElementById('titre').className="inp-form-error";
document.getElementById('err1').style.display="block";
document.getElementById('err2').style.display="block";
}
else {
document.getElementById('titre').className="inp-form";
document.getElementById('err1').style.display="none";
document.getElementById('err2').style.display="none";
}
if (!isFloat(document.getElementById('seuil').value) || document.getElementById('seuil').value == "" {
resultat = false:
document.getElementById('seuil').className="inp-form-error";
document.getElementById('err3').style.display="block";
document.getElementById('err4').style.display="block";
}
else {
document.getElementById('seuil').className="inp-form";
document.getElementById('err3').style.display="none";
document.getElementById('err4').style.display="none";
}
return resultat;
}
</script>
...
<form id="notif-form" name="form1" action="{% url 'mgmt_notif:verif_notif' %}" method="POST" onsubmit="return isValide();">
{% csrf_token %}
<table border="0" cellpadding="0" cellspacing="0" id="id-form" >
<tr>
<th valign="top">Titre :</th>
<td><input type="text" name="nom_notif" id="titre" class="inp-form" /></td>
<td>
<div id="err1" class="error-left"></div>
<div id="err2" class="error-inner">Verifier ce champs.</div>
</td>
</tr>
<tr>
<th valign="top">Seuil :</th>
<td><input type="text" name="rate" id="seuil" class="inp-form" /></td>
<td>
<div id="err3" class="error-left"></div>
<div id="err4" class="error-inner">Verifier ce champs</div>
</td>
</tr>
<tr>
<th valign="top">Description :</th>
<td colspan=2><textarea name="desc_notif" class="form-textarea"></textarea></td>
</tr>
<th> </th>
<td valign="top">
<input type="submit" value="Enregistrer" class="form-submit" />
<input type="reset" value="Annuler" class="form-reset" />
</td>
<td></td>
</tr>
</table>
</form>
and the formulaire.js file:
function isTel(valeurChamp){
var pattern = /^0[\d]{9}$/;
return pattern.test(valeurChamp);
}
function isAlpha(valeurChamp){
var pattern = /^[a-zéç| èùâëïöüâêûî\-\s]+$/i;
return pattern.test(valeurChamp);
}
function isMail(valeurChamp){
var pattern = /^[-+.\w]{1,64}#[-.\w]{1,64}\.[-.\w]{2,6}$/;
return pattern.test(valeurChamp);
}
function isFloat(valeurChamp){
var pattern = /^{0,1}d*.{0,1}d+$/;
return pattern.test(valeurChamp);
}
function isPassword(p1,p2) {
if (p1.value == '' || p2.value == '') {
return false;
}
else if (p1.value != p2.value) {
return false;
}
else if (p1.value != p2.value) {
return true;
}
else {
return false;
}
}
and thank
I have following table view
I want to hide that red squared area form that table . Since I'm using this data in further actions I want to hide not remove it. The markup for the table is:
<table class="table">
<thead>
<tr>
<th>Property_ID</th>
<th>IsChecked</th>
<th>Property Tile</th>
<th>Property Value</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<table id="template" class="table" style="display: none;">
<tr>
<td>
<span></span>
<input type="hidden" name="[#].Property_ID" />
</td>
<td>
<input type="checkbox" name="[#].IsChecked" value="true" />
<input type="hidden" name="[#].IsChecked" value="false" />
</td>
<td>
<span></span>
<input type="hidden" name="[#].Property_Title" />
</td>
<td>
<span></span>
<input type="hidden" name="[#].Property_Value" />
</td>
</tr>
</table>
this is javascript snippet to fill data to that table columns
<script type="text/javascript">
var type = $('#Type');
var category = $('#Category');
var country = $('#Country');
var product = $('#Product');
var table = $('#table');
$('#search').click(function () {
var url = '#Url.Action("FetchProductProperties")';
table.empty();
$.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), product: product.val() }, function (data) {
$.each(data, function (index, item) {
var clone = $('#template').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
var cells = clone.find('td');
cells.eq(0).children('span').text(item.ID);
cells.eq(0).children('input').val(item.ID);
cells.eq(1).children('input').first().prop('checked', item.CheckOrNot)
cells.eq(2).children('span').text(item.Name);
cells.eq(2).children('input').val(item.Name);
cells.eq(3).children('span').text(item.PropertyValue);
cells.eq(3).children('input').val(item.PropertyValue);
$('#table').append(clone.find('tr'));
});
});
});
</script>
Assuming you want to hide the column dynamically via javascript then add a class to that <td> element:
<table id="template" class="table" style="display: none;">
<tr>
<td>
<span></span>
<input type="hidden" name="[#].Property_ID" />
</td>
<td>
<input type="checkbox" name="[#].IsChecked" value="true" />
<input type="hidden" name="[#].IsChecked" value="false" />
</td>
<td>
<span></span>
<input type="hidden" name="[#].Property_Title" />
</td>
<td class="columnToHide">
<span></span>
<input type="hidden" name="[#].Property_Value" />
</td>
</tr>
</table>
Then you can call $('.columnToHide').hide(); from javascript after you have populated the search results:
$('#search').click(function () {
var url = '#Url.Action("FetchProductProperties")';
table.empty();
$.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), product: product.val() }, function (data) {
$.each(data, function (index, item) {
var clone = $('#template').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
var cells = clone.find('td');
cells.eq(0).children('span').text(item.ID);
cells.eq(0).children('input').val(item.ID);
cells.eq(1).children('input').first().prop('checked', item.CheckOrNot)
cells.eq(2).children('span').text(item.Name);
cells.eq(2).children('input').val(item.Name);
cells.eq(3).children('span').text(item.PropertyValue);
cells.eq(3).children('input').val(item.PropertyValue);
$('#table').append(clone.find('tr'));
});
});
$('.columnToHide').hide();
});
At any point you can show the column by using $('.columnToHide').show(); in your script.
Are you using bootstrap? If yes, add class "hide" to the th and td tag that you want to hide.