I want to calculate the sum of two variables on twig in real time?
is this doable with twig or should I try with Javascript?
I have tried with twig using the code below but it doesnt work in reel time I should complete the form then return to the page(my form on 3 pages)
<div >
<label for="nbStudentClassA" >Number of studentA</label>
<div >
{{ form_widget(form.nbStudentA}}
</div>
</div>
<div >
<label for="nbStudentClassB" >Number of student B</label>
<div>
{{ form_widget(form.nbStudentB}}
</div>
</div>
<div
<label >Sum </label>
<div >
{% set sum = form.vars.value.nbStudentA + form.vars.value.nbStudentB %}
{{ sum }}
</div>
</div>
Server side script will not work in real time, you will need something like jQuery to accomplish this before you refresh the page. You can calculate using jQuery with ease. There are also javascript math plugins you can add that make doing math easier in JS based scripts.
$(document).ready(function() {
$(".calculate").click(function() {
var x = $('input[id="nbStudentClassA"]').val();
var y = $('input[id="nbStudentClassB"]').val();
var mult = x + y;
var add = (+x) + (+y);
var sub = (+x) - (+y);
var div = x / y;
$('.result').html("Multiply: " + mult + "<br /> Addition: " + add + "<br />Subtration: " + sub + "<br />Division : " + div);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Enter two numbers to calculate as an example: Addition, subtraction, multipication and division</label>
<div>
<label for="nbStudentClassA" >Number of student A</label>
<input id="nbStudentClassA" type="text" name="nbStudentClassA" />
</div>
<div>
<label for="nbStudentClassB" >Number of student B</label>
<input id="nbStudentClassB" type="text" name="nbStudentClassB" />
</div>
<div class="result"></div>
<button type="button" class="calculate">Calculate</button>
Related
I'm trying to filter some results I will get from an api using Semantic UI's dropdown search component.
The issue is that I don't know how to get the text I'm typing in the input field
The dropdown search I have:
<div class="ui fluid search selection dropdown" id="user-dropdown">
<input id="user-dropdown-input" name="country" type="hidden">
<i class="dropdown icon"></i>
<div class="default text">Search...</div>
<div class="menu" id="user-dropdown-menu">
<div class="item" data-value="af">
<span class="description">123</span>
<span class="text">User123</span>
</div>
<div class="item" data-value="af">
<span class="description">123</span>
<span class="text">User123</span>
</div>
<div class="item" data-value="af">
<span class="description">123</span>
<span class="text">User123</span>
</div>
</div>
</div>
How dropdown is initialized:
$(document).ready(function () {
$('.ui.dropdown').dropdown({
clearable: true,
fullTextSearch: true
});
});
What I tried:
$('#user-dropdown').on('keyup', function () {
let input = $('#user-dropdown');
console.log('Val: ' + input.dropdown().val());
// also tried: $('#user-dropdown-input').val()
// $('#user-dropdown-input').html()
// $('#user-dropdown-input').text()
});
Basically what I want is if I type "abc" to print the value "abc" into the console, but I don't know how to get that value.
what worked for me was searching the input used for search that looks like:
<input class="search" autocomplete="off" tabindex="0">
and I added a type to this input
document.getElementsByClassName('search').type = 'text';
and then got the value by class on keyup
$('.search').keyup(function() {
console.log($(this).val());
});
With Django I made a Show more comments button using ajax. This system works, but the problem is that there are form fields in the comments I brought in this way, and when I click the more button, csrf_token does not appear in this comment field. As such, I get a csrf_token error when I submit the form. I leave my codes below.
To solve this problem, I ran the form with the get method, but as such, the function in the views directs me to the page with JsonResponse. Another solution was to give the header information csrf_token, but that didn't solve the problem either.
blog_detail.html
<script>
$(document).ready(function(){
$('#load_form').submit(function(e){
e.preventDefault();
var limit = $(this).attr('limit')
var page = document.getElementById('pagination')
var blog_comment_list = $('#blog-comment-list')
var serializedData = $(this).serialize();
$.ajax({
type:'GET',
url: "{% url 'load-more-comments' %}",
data : serializedData,
success: function(response){
blog_comment_list.html(response.comment_html)
if (page.value >= limit){
$('#submit_button').hide()
}
page.value = parseInt(page.value)+1
},
})
})
})
</script>
<div id="blog-comment-list">
{% include 'front_end/blog/comment/partial-comment.html' %}
</div>
<form method="GET" id="load_form" limit="{{num_pages}}">
<input type="hidden" name="pk" value="{{details.id}}">
<input type="hidden" name="page" value="2" id="pagination">
<input type="submit" name="load" value="Load More" id="submit_button">
</form>
partial-comment-html
<div class="media-holder mt-5">
<h3 class="title mb-3">All Comments</h3>
{% for item in comments %}
<div class="infinite-container">
<div class="media mb-5">
<img class="img-fluid rounded-circle box-shadow mr-4" alt="image" src="{{item.owner.get_image_or_default}}" style="width: 100px;height: 100px;">
<div class="media-body">
<h6>{{item.owner.name}} {{item.owner.surname}}</h6>
<br>
<small><span style="font-size:14px;" class="stars-container stars-{% widthratio item.rate.rate 1 20 %}" id="stars">★★★★★</span></small>
<div class="comment-date"> <span class="date">{{item.created_date|naturaltime}}</span>
</div>
<p>{{item.content}} </p>
<div align="center">
{% if item.comments.all %}Cevapları Görüntüle ({{item.comments.count}}){% else %}Cevap Ver{% endif %}
</div>
<div class="generic-comment" id="generic-comment-id-{{item.id}}" style="display:none;">
<!-- -->
<div class="infinite-generic-comment">
<form action="{% url 'comment-answer' %}" method="POST" id="answer_form">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{item.id}}">
<div class="row">
<div class="col-9">
<input type="text" placeholder="Cevap Ver" name='generic_comment' class="form-control">
</div>
<div class="col-2">
<input type="submit" value="Cevap Ver" class="btn btn-outline-primary">
</div>
</div>
</form>
{% for comment in item.comments.all %}
<div class="media mb-2">
<img class="img-fluid rounded-circle box-shadow mr-4" alt="image" src="{{item.owner.get_image_or_default}}" style="width: 100px;height: 100px;">
<div class="media-body">
<h6>{{comment.owner.name}} {{comment.owner.surname}}</h6>
<div class="comment-date"> <span class="date">{{comment.created_date|naturaltime}}</span>
</div>
<p>{{comment.content}} </p>
</div>
</div>
{% endfor %}
</div>
<!-- -->
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<script>
var aTag = document.getElementsByClassName('show-answers')
for (let i = 0; i< aTag.length; i++){
aTag[i].addEventListener('click', (event) => {
var generic = document.getElementById(`generic-${event.target.id}`)
if (generic.style.display == 'none'){
$(`#generic-${event.target.id}`).slideDown('slow')
}
else{
$(`#generic-${event.target.id}`).slideUp('slow')
}
})
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(document).ready(function(){
$('#answer_form').submit(function(e){
e.preventDefault()
var serializedData = $(this).serialize()
var url = $(this).attr('action')
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
//headers: { "X-CSRFToken": getCookie("csrftoken") }
});
$.ajax({
type:'POST',
url: url,
data:serializedData,
success: function(response){
if (response.success){
$('#answer_form').trigger('reset')
Swal.fire(
'Başarılı!',
'Cevap onaya gönderildi',
'success'
)
}
}
})
})
})
</script>
views.py
def answer_comment(request):
if request.method=='POST':
comment = Comment.objects.get(id=request.POST.get('comment_id'))
comment.comments.create(owner=request.user, content=request.POST.get('generic_comment'))
return JsonResponse({'success':True},status=200)
return JsonResponse({'success':False}, status = 403)
Note: I tried the csrf_exempt decorator function, but still could not solve the problem.
The methods I use are available in the script tag in partial-comment-html. How can I solve this problem. As I said, when I press the load more button, the necessary form fields to respond to a comment are just below these comments and when load more with ajax, the csrf_token information is deleted in these form fields, and nothing happens in new comments.
Note 2: When {{csrf_token}} is entered, I added the hidden input field with javascript myself, but Django realized that I added it and prevented me.
my modal code
<form action="/update" method="post">
<div class="modal fade" id="duzen" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Moda1">Etiketi Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="okuyucu" class="form-control okuyucu" placeholder="okuyucu" required>
</div>
<div class="form-group">
<input type="text" name="x" class="form-control x" placeholder="x" required>
</div>
<div class="form-group">
<input type="text" name="y" class="form-control y" placeholder="y" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="idnew_table" class="idnew_table">
<button type="button" class="btn btn-secondary btn-pill" data-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-primary btn-pill">Güncelle</button>
</div>
</div>
</div>
</div>
</form>
my ajax code
<script>
$(document).ready(() => {
var x1="";
var y1="";
var okuyucu1="";
var id="";
$.ajax({
url: "http://localhost:10001/etiketokuyucu",
method: 'GET',
success: function(response){
if(response.length > 0){
for(let index = 0; index < response.length; index++) {
var newRow = $("<tr>");
var cols = "";
var okuyucu = '';
var x = '';
var y = '';
var id='';
cols += '<td>' + response[index].idnew_table+'</td>';
cols += '<td> '+ response[index].okuyucu +'</td>' ;
cols += '<td> '+ response[index].x +'</td>';
cols += '<td> '+ response[index].y +'</td>';
cols += '<td>'
+
'<div class="dropdown d-inline-block widget-dropdown">'+
'<a class="dropdown-toggle icon-burger-mini" href="" role="button" id="dropdown-recent-order1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static"></a>'+
'<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdown-recent-order1">'+
'<li class="dropdown-item edit">'+
'Düzenle'+
'</li>'+
'<li class="dropdown-item delete">'+
'Sil'+
'</li>'+
'</ul>'+
'</div>'+
'</td>' ;
newRow.append(cols);
$("#example .tbody").append(newRow);
}
}
}
})
})
my modal script code
<script>
$(document).ready(function(){
//showing data to modal for edit record
$('#example').on('click','.edit',function(){
var idnew_table = $(this).data('idnew_table');
var okuyucu= $(this).data('okuyucu');
var x = $(this).data('x');
var y = $(this).data('y');
console.log(idnew_table+"okuyucu="+okuyucu + "x=" +x+" y="+y);
var modal = $(this);
modal.find('#okuyucu').text(okuyucu);
modal.find('#x').text(x);
modal.find('#y').text(y);
/*$('#duzen').modal('show');
$('.okuyucu').val($(this).data('okuyucu'))
$('.x').val(x);
$('.y').val(y);
$('.idnew_table').val(idnew_table);
*/ });
//showing modal for delete record
});
I want to show my mysql data on modal but ı got an error.In this code first show true value in console okuyucu,x,y etc but in modal shows they are undefined.why are they not show true value in my console when they second run?It passes data from ajax to table and I read that value from script code but doesn't show in my modal
Thank you for your help
Your current code for appending value to table was having 2 class edit i.e : li and <a> so when you click on edit link both class where getting called and it was returning undefined .Also , your input inside modal doesn't have any id instead it only have namei have corrected your code .
Demo Code :
//demo data
var response = [{
"idnew_table": "1",
"okuyucu": "abc",
"x": "12",
"y": "fbg"
}, {
"idnew_table": "2",
"okuyucu": "abcd",
"x": "152",
"y": "f5bg"
}, {
"idnew_table": "3",
"okuyucu": "abce",
"x": "125",
"y": "fb5g"
}]
if (response.length > 0) {
for (let index = 0; index < response.length; index++) {
var newRow = $("<tr>");
var cols = "";
var okuyucu = '';
var x = '';
var y = '';
var id = '';
cols += '<td>' + response[index].idnew_table + '</td>';
cols += '<td> ' + response[index].okuyucu + '</td>';
cols += '<td> ' + response[index].x + '</td>';
cols += '<td> ' + response[index].y + '</td>';
cols += '<td>' +
'<div class="dropdown d-inline-block widget-dropdown">' +
'<a class="dropdown-toggle icon-burger-mini" href="" role="button" id="dropdown-recent-order1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" data-display="static"></a>' +
'<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdown-recent-order1">' +
'<li class="dropdown-item ">' + //<--remove class edit
'Düzenle'+
'</li>' +
'<li class="dropdown-item delete">' +
'Sil' +
'</li>' +
'</ul>' +
'</div>' +
'</td>';
newRow.append(cols);
$("#example .tbody").append(newRow);
}
}
//showing data to modal for edit record
$('#example').on('click','.edit',function(){
var idnew_table = $(this).data('idnew_table');
var okuyucu = $(this).data('okuyucu');
var x = $(this).data('x');
var y = $(this).data('y');
console.log(idnew_table + "okuyucu=" + okuyucu + "x=" + x + " y=" + y);
//find input under modal and set value of inputs
$("#duzen").find('input[name=okuyucu]').val(okuyucu);
$("#duzen").find('input[name=x]').val(x);
$("#duzen").find('input[name=y]').val(y);
$('#duzen').modal('show');
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.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" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<table id="example" border="1">
<thead>
<th>idnew_table</th>
<th>okuyucu</th>
<th>x</th>
<th>y</th>
<th>Action</th>
</thead>
<tbody class="tbody">
</tbody>
</table>
<form action="/update" method="post">
<div class="modal fade" id="duzen" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="Moda1">Etiketi Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name="okuyucu" class="form-control okuyucu" placeholder="okuyucu" required>
</div>
<div class="form-group">
<input type="text" name="x" class="form-control x" placeholder="x" required>
</div>
<div class="form-group">
<input type="text" name="y" class="form-control y" placeholder="y" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="idnew_table" class="idnew_table">
<button type="button" class="btn btn-secondary btn-pill" data-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-primary btn-pill">Güncelle</button>
</div>
</div>
</div>
</div>
</form>
I have this input repeating based on my items ['1','2'], then ng-model for input:
<form id="register-form" form ng-submit="successbloodstock.updateRemark()" >
<div class="input-group input-group">
<div class="input-group-addon" style="width:130px">
<small>EXPIRATION DATE</small>
</div>
<input class="form-control" type="date" name="expiry_date"
ng-model="newExpiry" required>
</div>
</form>
but after I submit the form it doesn't show the ng-model as array:
.controller('successbloodstockCtrl', function($scope,$timeout,$location,$route,$routeParams,$http) {
var app = this;
app.number=['asdf','asadf'];
app.updateRemark = function() {
var userObject = {};
userObject.expiry_date = $scope.newExpiry;
console.log($scope.newExpiry[$index])
}
}
this gives me undefined
I am trying to get the word BIBA. I am getting output like \n,\n,\nBIBA,\n But I only want "BIBA".
Please help me to get that name using xpath.
Thank you.
<div class="pdp-bname">
<input type="hidden" value="/wishlist/getWishListData" `enter code here`id="miniWishlistFormActionUrl">
<div class="prd-fav addToWishlist2">
<form id="addToWishlistForm202180385_9607" class="wishlistPdpAddOrRemove" action="/wishlist/addOrRemoveWishlist/202180385_9607" method="POST"> <input type="hidden" value="5f49e2f4-9c05-4a5a-83b9-6edbc780cbe5" id="ajaxCSRF">
<button type="submit" id="addwishlistId" class="go_link wishlistSubmitBtn wishlist ">
<!-- <label class="labletext">Add to wishlist</label> -->
</button>
<div>
<input type="hidden" name="CSRFToken" value="5f49e2f4-9c05-4a5a-83b9-6edbc780cbe5">
</div>
</form>
</div>
"
BIBA
"
</div>
I highly recommend to use Scrapy Item Loaders and Input and Output processors:
def strip_word(value):
value = value.strip()
return value
class MyItem(scrapy.Item):
my_word_field = scrapy.Field(
input_processor=TakeFirst(),
output_processor=MapCompose(strip_word)
)
How about this:
response.xpath('normalize-space(//div[#class="pdp-bname"])')