How to create a running total input field in django form? - javascript

How to create a running total using javascript in django form.
This is my model:
class Contra(models.Model):
date = models.DateField(default=datetime.date.today)
account = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='contraledgers')
class Particularscontra(models.Model):
contra = models.ForeignKey(Contra,on_delete=models.CASCADE,related_name='contras')
particular = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='particularcontra')
amount = models.DecimalField(max_digits=10,decimal_places=2,null=True)
This is my form:
class ContraForm(forms.ModelForm):
class Meta:
model = Contra
fields = ('date','account')
widgets = {
'date': DateInput(),
}
def __init__(self, *args, **kwargs):
super(ContraForm, self).__init__(*args, **kwargs)
self.fields['account'].widget.attrs = {'class': 'form-control select2',}
class ParticularscontraForm(forms.ModelForm):
class Meta:
model = Particularscontra
fields = ('particular','amount')
def __init__(self, *args, **kwargs):
super(ParticularscontraForm, self).__init__(*args, **kwargs)
self.fields['particular'].widget.attrs = {'class': 'form-control select2',}
self.fields['amount'].widget.attrs = {'class': 'form-control',}
Contra_formSet = inlineformset_factory(Contra, Particularscontra,
form=ParticularscontraForm, extra=6)
This
I tried this previously but was unsuccessful:
{% block content %}
<div class="content-wrapper">
<!-- <div class="container"> -->
<section class="content-header">
<!-- <div class="col-md-12 col-md-offset-4"> -->
<h1>
<strong>Company : {{company_details.Name}}</strong>
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<!-- <li>Company list</li> -->
<li class="">Company list</li>
<li class="active">Create Simple Unit</li>
</ol>
<!-- </div> -->
</section>
<section class="content">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- Horizontal Form -->
<div class="box">
<div class="box-header with-border">
{% if not form.instance.pk %}
<h3 class="box-title"><strong>Create Contra</strong></h3>
{% else %}
<h3 class="box-title"><strong>Update Contra</strong></h3>
{% endif %}
</div>
<!-- /.box-header -->
<!-- form start -->
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body form-responsive no-padding">
<br>
<br>
<div class="col-md-2">
<div class="form-group">
<label for="PAN1" class="col-md-4 control-label">Account<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{ form.account }}
</div>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="State1" class="col-md-4 control-label">Date<i class="material-icons" style="font-size:16px;color:red">*</i></label>
<div class="col-md-8">
{{form.date}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="box box-success">
<div class="box-body table-responsive no-padding">
<table class="table">
{{ contras.management_form }}
<thead>
<tr>
<th class="col-md-6">Particulars<i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount<i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody id="calculate">
{% for form in contras.forms %}
<tr class='{% cycle "row1" "row2" %} formset_row'>
<td class="col-md-6">{{ form.id }} {{ form.particular}}</td>
<td class="col-md-6 amounts">{{ form.amount}}</td>
</tr>
{% endfor %}
</tbody>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6" id="totaled"><input type="text" name="total"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default" type="reset" value="Reset">Reset</button>
{% if not form.instance.pk %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Create</button>
{% else %}
<button type="submit" class="btn btn-info pull-right" value="Submit">Update</button>
{% endif %}
</div>
<!-- /.box-footer -->
</form>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add contra',
deleteText: 'remove',
prefix: 'contras'
});
</script>
<script type="text/javascript">
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
</script>
</section>
</div>
{% endblock %}
This is the javascript code I tried:
<script type="text/javascript">
$(document).ready(function(e){
$('#calculate tbody').change(function(){
var totals = 0;
$(".amounts").each(function(){
totals = totals + parseInt($(this).val());
})
$(".totaled").val(totals);
});
});
</script>
I am using inline formset in my template I want to display the running total of all the amount given in my inline form..
How is that possible to do it in django?
any guess?
Thank you

Not sure if someone is still looking for an answer to this. This is the code I used. 'total' is the id of a span element, where the running total is shown.
$("input.numberinput").change(function(){
sum=0
$("input.numberinput").each(function(){
sum += parseInt($(this).val());
})
$('#total').text(sum);
})

Select each td class amounts, iterate and add over them.
$(document).ready(function() {
let tableInstance = $('#calculate td.amounts');
let totals = 0;
tableInstance.each(function() {
totals = totals + Math.floor($(this).text() * 100) / 100;
});
$(".totaled :input").val(totals);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<table class="table" id="calculate">
<thead>
<tr>
<th class="col-md-6">Particulars <i class="material-icons" style="font-size:16px;color:red">*</i></th>
<th class="col-md-6">Amount <i class="material-icons" style="font-size:16px;color:red">*</i></th>
</tr>
</thead>
<tbody>
<tr class="row1 formset_row">
<td class="col-md-6">1</td>
<td class="col-md-6 amounts">5.2</td>
</tr>
<tr class="row2 formset_row">
<td class="col-md-6">2</td>
<td class="col-md-6 amounts">5.5</td>
</tr>
<tr>
<td class="col-md-6"></td>
<td class="col-md-6 totaled"><input type="text" name="total"></td>
</tr>
</tbody>
</table>

Related

$(document).ready(function () $ is not defined when sending jsonresponse from django app

I'm having this issue when sending a json response from my django app to a table using javascript/jquery.
I've seen other threads that say this is error is due to jquery not being used, and that we should add the link to jquery such as the following within the tags but i don't have head tags.
Query link:
<script src="http://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js></script>
<script src="http://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js></script>
my welcome.html file with javascript and table html at the end:
{% extends 'base.html' %}
{% load static%}
{% comment %} <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> {% endcomment %}
{% comment %} <script src="http://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script> {% endcomment %}
{% block content %}
<!-- Upload File Section-->
<section class="page-section mt-5" id="import-form">
<div class="container">
<!-- Upload Section Heading-->
<h2
class="page-section-heading text-center text-uppercase text-secondary mb-0"
>
Upload Data
</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Upload Data Section Form-->
<div class="row justify-content-center">
<div class="col-lg-8 col-xl-7">
<form id="upload-file" name="upload-file",
enctype="multipart/form-data" method="POST" action="{% url 'supplychain:airpollution' %}">
{% csrf_token %}
<!-- Year input-->
<div class="form-floating mb-3">
<input
class="form-control"
id="year"
name="year"
type="number"
placeholder="year"
data-sb-validations="required"
/>
<label>Year</label>
<div class="invalid-feedback" data-sb-feedback="name:required">
A name is required.
</div>
</div>
<!-- Data input-->
<div class="form-floating mb-3">
<input
class="form-control"
id="file"
name="file"
type="file"
data-sb-validations="required"
/>
<label>File</label>
<div class="invalid-feedback" data-sb-feedback="email:required">
An email is required.
</div>
<div class="invalid-feedback" data-sb-feedback="email:email">
Email is not valid.
</div>
</div>
<!-- Submit success message-->
<div id="success">{{ message_success }}</div>
<div class="form-group">
<button class="btn btn-primary btn-xl" id="upload" type="submit">Upload</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- Table Section-->
<section class="page-section mt-5" id="data-table">
<div class="container">
<!-- Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Data Table</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Table-->
<div class="row">
<div class="col-lg-8 mx-auto">
<table id="our-table" class="table">
<thead>
<tr>
<th scope="col">Pollutant</th>
<th scope="col">Country</th>
<th scope="col">Avg</th>
<th scope="col">Min</th>
<th scope="col">Max</th>
<th scope="col">Limit</th>
<th scope="col">Units</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</div>
</div>
</div>
</section>
{% endblock %}
{% block js %}
<!-- Page level plugins -->
<script src="http://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js></script>
<script src="http://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js></script>
<script>
$(document).ready(function () {
$.get("airpollution_table_data", function (data) {
console.log(data)
});
})
</script>
{% endblock %}
edit Solution
I added jquery before using datatables and error has gone!:
<script src="{% static 'vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script>
$(document).ready(function () {
$.get("airpollution_table_data", function (data) {
console.log(data)
});
})
</script>

reload page asynchronously after success ajax

i'm trying to add a new entered value to a table after success method runs using ajax , i've used ModelForm . i want to add the new entry to the table body row ! , i've tried alot , but still i cant figure it out ! i most appreciate your helps
class MainGroup(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
main_type = models.CharField(max_length=40,unique=True)
date = models.DateTimeField(auto_now_add=True)
my views.py
#login_required
def create_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
form = MainGroupForm()
if request.is_ajax() and request.method == 'POST':
form = MainGroupForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.admin = request.user
obj.save()
return JsonResponse({'success':'success'})
else:
return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'})
context = {
'form':form,'lists':lists
}
return render(request,'products/create_maingroup.html',context)
const form = document.getElementById('main_form')
form.addEventListener("submit",submitHandler);
function submitHandler(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'products:create-maingroup' %}',
data : $('#main_form').serialize(),
dataType: 'json',
success: successFunction,
});
}
function successFunction(data) {
console.log(data.success=='success')
if (data.success=='success') {
form.reset();
obj = $('#main_form').serialize();
//i have to append new entred values here
//but i dont know how to get inputs and set the admin
//name who created the post !
alertify.success("added")
}
else if(data.error_code=='invalid'){
for(var key in data.error_msg){
if(key == 'main_type'){
document.getElementById('main_error').removeAttribute('hidden')
document.getElementById('main_error').innerHTML = data.error_msg[key][0]
}
}
}
}
my html page
<div class="col-md-12">
<div class="card card-info">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-toggle="collapse" data-target="#main_form" aria-expanded="false" aria-controls="main_form">
<i class="fas fa-minus"></i>
</button>
</div>
<h3 class="text-center">add new data</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form id="main_form" role="form" method="POST">{% csrf_token %}
<div class="card-body">
<div class="form-group row">
<label for="mainGroup" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
{{form.main_type | attr:'id:mainGroup'}}
<p id="main_error" class="alert alert-danger" aria-disabled="true" hidden></p>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success">add</button>
</div>
</form>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="text-center">list of names</h3>
</div>
<div class="card-body table-responsive">
<table id="maingroupid" class="table table-bordered table-striped text-center">
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
<th>actions</th>
</tr>
</thead>
<tbody id="tableData">
{% for i in lists %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.admin}}</td>
<td>{{i.main_type}}</td>
<td>{{i.date | date:'d-m-Y h:i A'}}</td>
<td align="center">
<button class="btn btn-info bg-info" onclick="editMain({{i.id}})" data-toggle="modal" data-target="#myModal"><i class="far fa-edit"></i></button>
<button class="btn btn-danger bg-danger" onclick="deleteMain({{i.id}})"><i class="far fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</tfoot>
</table>
</div>
</div>
</div>
is it possible without refreshing the page and display the new data please ? i need it so much
You could return the new table once edited
context = {} # whatever your context is
return render(request, 'path/to/table/template.html', context=context)
template.html is the table element of your template
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
<th>actions</th>
</tr>
</thead>
<tbody id="tableData">
{% for i in lists %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.admin}}</td>
<td>{{i.main_type}}</td>
<td>{{i.date | date:'d-m-Y h:i A'}}</td>
<td align="center">
<button class="btn btn-info bg-info" onclick="editMain({{i.id}})" data-toggle="modal" data-target="#myModal"><i class="far fa-edit"></i></button>
<button class="btn btn-danger bg-danger" onclick="deleteMain({{i.id}})"><i class="far fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</tfoot>
Then on success within ajax use
success: function (data, status) {
$('#maingroupid`).html(data);
}

Bootstrap radio button isn't working in flask

I am using Bootstrap 4 radio button radio button in a flask application. and below is the snippet I used
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
and the javascript code
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
Initially,I tried with simple html radio buttons and was able to trigger Javascript function toggleElements(). However, after replacing the normal radio buttons with the bootstrap radio, nothing is triggered.
Below is the entire html code
{% from 'helper/forms.html' import render_field with context %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sharjah Tourism Search Results</title>
<script src="{{ url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="{{ url_for('static',filename='styles/home.css')}}"/>
<script type="text/javascript">
function toggleElements() {
alert('hurray');
if(document.getElementBId('twitter').checked) {
document.getElementById('twitterrows').style.display = 'block';
document.getElementById('facebookrows').style.display = 'none';
}
if(document.getElementById('facebook').checked) {
document.getElementById('facebookrows').style.display = 'block';
document.getElementById('twitterrows').style.display = 'none';
}
}
</script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{{ url_for('home')}}"><strong>Search</strong></a>
<button class = "navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-7"
aria-controls="navbarSupportedContent-7" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent-7">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="{{url_for('add_url')}}">Add<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('file_render')}}">Import</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">
Websites
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="{{ url_for('list_urls') }}">List</a>
<a class="dropdown-item" href="{{ url_for('list_crawled_websites')}}">Selected</a>
</div>
</li>
</ul>
</div>
</nav>
<!-- Header -->
<div class="container">
<br />
<div class="row">
<!-- Logo -->
<div class="col-sm">
<img class="w-50 h-60" src="{{url_for('static',filename='images/sctda_logo.jpg')}}" />
</div>
<!-- Search Bar -->
<div class="col-sm-5 searchbar">
<form action="{{url_for('fetch_results')}}" method="POST">
<div class="input-group">
<input type="search" placeholder="Search" class="form-control" name="search" id="search" value="{{data['search_term']}}" class="w-75 h-75" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary btn-sm"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
</div>
</div>
<div id="container">
<div class="row">
{%set data = data['results'] %}
<div class="col-md-4">
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> Internal
</label>
</div>
<hr>
{% set internals = data['internal'] %}
{% if internals is defined and internals|length %}
{% for internal in internals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ internal['title'] }}</h5>
<p class="card-text">{{ internal['description'] }}</p>
{{ internal['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
{% set externals = data['external'] %}
{% if externals is defined and externals|length %}
<div class="btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary active">
<input type="radio" checked autocomplete="off"> External
</label>
</div>
<hr>
{% for external in externals %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ external['title'] }}</h5>
<p class="card-text">{{ external['description'] }}</p>
{{ external['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div class="col-md-4">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-secondary">
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter
</label>
<label class="btn btn-outline-secondary" >
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook
</label>
</div>
<hr>
(<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="twitter"/> Twitter,
<input type="radio" onclick="javascript:toggleElements();" name="toggle" id="facebook"/> Facebook)
<div id="twitterrows">
{% set tweets = data['twitter'] %}
{% if tweets is defined and tweets|length %}
{% for tweet in tweets %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ tweet['title'] }}</h5>
<p class="card-text">{{ tweet['description'] }}</p>
{{ tweet['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
<div id="facebookrows">
{% set posts = data['facebook'] %}
{% if posts is defined and posts|length %}
{% for post in posts %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ post['title'] }}</h5>
<p class="card-text">{{ post['description'] }}</p>
{{ post['title'] }}
</div>
</div>
<br/>
{% endfor %}
{% else %}
<div class="card">
<div class="card-body">
<h5 class="card-title">No Records Found</h5>
</div>
</div>
<br/>
{% endif %}
</div>
</div>
</div>
</div>
<center>Developed by School of Information Technology Team,Skyline University College</center>
</body>
</html>
I strongly suspect with the order of scripts being called under the head tag. Can someone help me to fix this please.
make sure you have included the correct version of bootstrap. Please check if there is any error in the browser console.
https://getbootstrap.com/docs/4.4/components/input-group/#checkboxes-and-radios.
I am suspecting that the javascript click is not properly binded to the click event.
I fixed it by replacing the three script tags in the above html page with the below
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

HTML Table, retrieving data from row and displaying it elsewhere

I'm trying to make it so when you click on a row in the table, depending what row you press, it will display that data into the other panel. So when I click the first row, the Number in the table fills out the number in the other panel, under "Readings". As well as the Name in the table, filling out the Name field under "Readings". How would I go about doing this?
<!-- begin row -->
<div class="row">
<!-- begin col-2 -->
<div class="col-md-2">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Table</h4>
</div>
<div class="panel-body">
<table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="gradeA">
<td>1</td>
<td>First</td>
</tr>
<tr class="gradeA">
<td>2</td>
<td>Second</td>
</tr>
<tr class="gradeA">
<td>3</td>
<td>Third</td>
</tr>
<tr class="gradeA">
<td>4</td>
<td>Fourth</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- end panel -->
</div>
<!-- begin col-2 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-stuff-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Form</h4>
</div>
<div class="panel-body">
<form class="form-horizontal" action="/" method="POST">
<legend>Readings</legend>
<div class="form-group">
<label class="col-md-4 control-label">Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" placeholder="1" disabled />
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name:</label>
<div class="col-md-8">
<input type="device" class="form-control" value="Name here" />
</div>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-10 -->
</div>
<!-- end row -->
There you go pal
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<!-- begin row -->
<div class="row">
<!-- begin col-2 -->
<div class="col-md-2">
<!-- begin panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Table</h4>
</div>
<div class="panel-body">
<table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="gradeA">
<td>1</td>
<td>First</td>
</tr>
<tr class="gradeA">
<td>2</td>
<td>Second</td>
</tr>
<tr class="gradeA">
<td>3</td>
<td>Third</td>
</tr>
<tr class="gradeA">
<td>4</td>
<td>Fourth</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- end panel -->
</div>
<!-- begin col-2 -->
<div class="col-md-6">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-stuff-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Form</h4>
</div>
<div class="panel-body">
<form class="form-horizontal" action="/" method="POST">
<legend>Readings</legend>
<div class="form-group">
<label class="col-md-4 control-label">Number:</label>
<div class="col-md-8">
<input
type="text"
id="numberInput"
class="form-control"
placeholder="Number"
disabled />
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Name:</label>
<div class="col-md-8">
<input
type="text"
id="deviceInput"
class="form-control"
value="Name here" />
</div>
</div>
</div>
</div>
<!-- end panel -->
</div>
<!-- end col-10 -->
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- end row -->
<script>
(function () {
var table = document.querySelector('#data-table');
var number = document.querySelector('#numberInput');
var device = document.querySelector('#deviceInput');
table.addEventListener('click', onTableClick);
function onTableClick (e) {
//console.log(e.currentTarget);
var tr = e.target.parentElement;
//console.log(tr.children);
var data = [];
for (var td of tr.children) {
data.push(td.innerHTML)
}
number.value = data[0];
device.value = data[1];
}
})();
</script>
</body>
</html>
With vanilla Javascript (there are data-binding libraries that can handle this), table rows do have click events. So you can create a function that handles that click event.
You can either use the onclick attribute or addEventListener method of HTML elements. You can explicitly state the input to the function or calculate it. So say the function name is updateOther, you could do updateOther(1,'First') or updateOther(this). The latter will pass the row element that was clicked and you can extract the pertinent information.
$(document).ready(function(){
$(".gradeA").click(function(){
var currentRow = this;
var number = $(this).find("td")[0].innerText;
var name = $(this).find("td")[1].innerText;
$("form input[type='text']").val(number);
$("form input[type='device']").val(name);
})
});

How can I clearly switch between two forms in one template (Django)?

When several html forms (signup and login) in one template, login_signup.html
Also I have two views (signup and login) which direct template, login_signup.html.
This is how it works.
When I do login (http://example.com/login), it direct to login_signup.html and show just login form. (hide signup form)
When I do signup (http://example.com/signup), it direct to login_signup.html and show just signup form. (hide login form)
I implement it using javascript
$(document).ready(function(){
if ((window.location.pathname).indexOf('login') >= 0) {
$('#signupbox').hide();
$('#loginbox').show();
} else {
$('#loginbox').hide();
$('#signupbox').show();
}
});
Problem is though, when I want go to signup page(http://example.com/signup), it shows login forms in very few second and hide it and show signup form. I think this is not good User Interface.
How can I deal with it clearly?
Here is my whole template and javascript code.
login_signup.html
{% extends 'chacha_dabang/skeleton/base.html' %}
{% load pipeline%}
{% block content %}
<div class="container">
<div id="loginbox" class="mainbox">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
<div class="panel-body">
<div id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}">
{% csrf_token %}
<!-- id / pw -->
<div class="input-group">
<span class="input-group-addon"><i class="icon-user"></i></span>
<input id="id_username" type="text" class="form-control" name="username" value="" placeholder="username">
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon-lock"></i></span>
<input id="id_password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div class="form-group">
<!-- Button -->
<div class="btn-controls">
<div class="row">
<input id="btn-login" class="btn btn-success" type="submit" name="login_submit" value="로 그 인" />
<input type="hidden" name="next" value={{ request.GET.next}} />
<a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" class="btn btn-primary col-xs-12"><i class="icon-facebook"></i> 1초만에 페이스북으로 로그인 </a>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div class="signup">
아직 차차다방 회원이 아니세요? &nbsp
가입하기
</div>
<div class="forget">
비밀번호를 잊어버리셨나요?
</div>
</div>
</div>
</form>
</div> <!-- <div class="panel-body" > -->
</div> <!-- <div class="panel panel-info"> -->
</div> <!-- <div id="loginbox"> -->
<!-- Sign up Form -->
<div id="signupbox" class="mainbox">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Sign Up</div>
</div>
<div class="panel-body">
<form id="signupform" class="form-horizontal" role="form" method="post" action="{% url 'users:signup' %}">
{% csrf_token %}
<!-- signup -->
<div id="signupalert" class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<!-- id / pw -->
<table id="signup-table">
<col width="30%">
<col width="70%">
<tr>
<td class="label-tag">{{ form.username.label_tag }}</td>
<td class="value">{{ form.username }}</td>
{{ form.errors.username }}
</tr>
<tr>
<td class="label-tag">{{ form.password1.label_tag }}</td>
<td class="value">{{ form.password1 }}</td>
{{ form.errors.password1 }}
</tr>
<tr>
<td class="label-tag">{{ form.password2.label_tag }}</td>
<td class="value">{{ form.password2 }}</td>
{{ form.errors.password2 }}
</tr>
<tr>
<td class="label-tag">{{ form.name.label_tag }}</td>
<td class="value">{{ form.name }}</td>
{{ form.errors.name }}
</tr>
<tr>
<td class="label-tag">{{ form.gender.label_tag }}</td>
<td class="value">{{ form.gender }}</td>
{{ form.errors.gender }}
</tr>
<tr>
<td class="label-tag">{{ form.birth.label_tag }}</td>
<td class="value">{{ form.birth }}</td>
{{ form.errors.birth }}
</tr>
<tr>
<td class="label-tag">{{ form.phone_number.label_tag }}</td>
<td class="value">{{ form.phone_number }}</td>
{{ form.errors.phone_number }}
</tr>
<tr>
<td class="label-tag">{{ form.job.label_tag }}</td>
<td class="value">{{ form.job }}</td>
{{ form.errors.job}}
</tr>
</table>
<div class="form-group">
<!-- Button -->
<div class="btn-controls">
<div class="row">
<input id="btn-signup" class="btn btn-success" type="submit" name="signup_submit" value="가 입 하 기" />
<a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" class="btn btn-primary col-xs-12"><i class="icon-facebook"></i>1초만에 페이스북으로 로그인</a>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12 control">
<div class="login">
이미 차차다방 회원이신가요? &nbsp
로그인하기
</div>
</div>
</div>
</form>
</div> <!-- <div class="panel-body"> -->
</div> <!-- <div class="panel panel-info"> -->
</div> <!-- <div id="signupbox"> -->
</div> <!-- <div class="container"> -->
{% endblock %}
{% block custom_js %}
{% javascript "login_signup" %}
{% endblock %}
login_signup.js
$("#signuplink").click(function(){
$('#loginbox').hide();
$('#signupbox').show();
});
$("#loginlink").click(function(){
$('#signupbox').hide();
$('#loginbox').show();
});
$(document).ready(function(){
if ((window.location.pathname).indexOf('login') >= 0) {
$('#signupbox').hide();
$('#loginbox').show();
} else {
$('#loginbox').hide();
$('#signupbox').show();
}
});
Try:
<div id="signupbox" class="mainbox" style="display: none">
<div id="loginbox" class="mainbox" style="display: none">
Then use javascript:
$(document).ready(function(){
if ((window.location.pathname).indexOf('login') >= 0) {
$('#loginbox').css("display", "auto");
} else {
$('#signupbox').css("display", "auto");
}
});
But I still recommend use different html file to handle signup and login.

Categories

Resources