How to use same JavaScript function in multiples Dropdownlists - javascript

I have multiple dropdown list added dynamically, and they get their own id, I have a function where I call OnChange event to pass some value based on selected in Dropdown list, but at the moment i am just doing this with the first select.
JS:
$("#id_detallepedido_set-0-producto").change(function () {
producto_id = $(this).val();
var url = '/control/price/'+producto_id;
$.ajax({
type: "GET",
url: url,
data: {
'producto': producto_id
},
success: function (data) {
console.log('Funciono!');
console.log(data);
$("#id_detallepedido_set-0-precio").val(data);
},
error: function(data) {
alert('error' + data);
//console.log(data);
}
});
});
"id_detallepedido_set-0-producto" is the id for the first Dropdownlist, and "id_detallepedido_set-0-precio" is the id for the field I pass the value based on selected value, there is anyway to use this function in every dropdown list added dynamically?
And I'm adding those dropdown list with Django Form here:
Html:
<table class="table" id="tPedidos">
{{ detalle.management_form }}
{% for form in detalle.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="formset_row-{{ formset.prefix }}">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>

Instead of handling dropdown change event using id, you can handle it using class. so it will execute for all dropdown.
But as you said your dropdown is added dynamically, you need to create click event globally.
let say you have 3 dropdown, then just add class = "mydropdownclass". and add class = "mytextfield" to your text control.
<table>
<tr>
<td>
<select id="t1" class="mydropdownclass">
<option value="1">101</option>
<option value="2">102</option>
</select>
</td>
<td>
<input type="text" class="test" />
</td>
<td>
<input type="text" class="mytextfield" />
</td>
</tr>
<tr>
<td>
<select id="t2" class="mydropdownclass">
<option value="1">101</option>
<option value="2">102</option>
</select>
</td>
<td>
<input type="text" class="test" />
</td>
<td>
<input type="text" class="mytextfield" />
</td>
</tr>
</table>
<script>
$(document).on("change", ".mydropdownclass" , function() {
producto_id = $(this).val();
var controlId = $(this).attr('id');
//Updat textbox value
$(this).closest("tr").find('.mytextfield').val($(this).val());
var url = '/control/price/'+producto_id;
$.ajax({
type: "GET",
url: url,
data: {
'producto': producto_id
},
success: function (data) {
console.log('Funciono!');
console.log(data);
$("#"+controlId).val(data);
},
error: function(data) {
alert('error' + data);
//console.log(data);
}
});
});
</script>
you can check updated code [link]
https://jsfiddle.net/hubs3m0n/

If elements are added dynamically you can attach an event to document like this.
$(document).on('change', '[write common selector here]', function callback() {})

make a static class which will be same for every element and do in that way
$(".commonClass").change(function () {
producto_id = $(this).val();
var url = '/control/price/'+producto_id;
$.ajax({
type: "GET",
url: url,
data: {
'producto': producto_id
},
success: function (data) {
console.log('Funciono!');
console.log(data);
$("#id_detallepedido_set-0-precio").val(data);
},
error: function(data) {
alert('error' + data);
//console.log(data);
}
});
});

Related

How to increment a value on a button click in JQuery?

Another query on a JQuery function as a newbie in this. With the help of you guys I was able to modify the code to return the corresponding value from an input tag.
The problem that I am facing now is that on the Add button click I want the <p class="item-quantity">0</p> to display the value returned by the JQuery .get() in the corresponding row.
Here's my HTML:
{% for item in menu_category %}
<tr class="item">
<td><p class="item-name">{{item.item_Name}}</p></td>
<td><p class="item-price">{{item.item_Price}}</p></td>
<td>
<button type="button" class="btn btn-primary add-item" data-name="{{item.item_Name}}" data-price="{{item.item_Price}}" data-id="{{item.item_Id}}">+</button>
</td>
<td><p class="item-quantity">0</p></td>
<td>
<button type="button" class="btn btn-primary remove-item" data-name="{{item.item_Name}}" data-price="{{item.item_Price}}" data-id="{{item.item_Id}}">-</button>
</td>
</tr>
{% endfor %}
And my function:
<script>
$(function() {
$('.add-item').on('click', function() {
$.get('{{ url_for("func_add_to_cart") }}',
{
item_id: $(this).attr("data-id"),
},
function(data) {
$(this).parents().find(".item-quantity").html(data);
});
return false;
});
});
</script>
Thanks for your help!

popup the model on select change option in a table

I have a table and inside it I have a select
<tbody>
#foreach($cheques as $key => $cheque)
<tr data-id="{{ $cheque->id }}">
<td>{{ $cheque->reference }}</td>
<td>{{ $cheque->amount }}</td>
<td>{{ $cheque->owner }}</td>
<td>{{ $cheque->receiver }}</td>
<td>{{ $cheque->date_entree->format('d/m/Y') }}</td>
<td>{{ $cheque->date_payment->format('d/m/Y') }}</td>
<td>
<select name="statue" class="form-control" id="statue">
<option value="0" {{ $cheque->statue == "0" ? 'selected':'' }}>{{ __('messages.cheques.waiting') }}</option>
<option value="1" {{ $cheque->statue == "1" ? 'selected':'' }}>{{ __('messages.cheques.payed') }}</option>
<option value="2" {{ $cheque->statue == "2" ? 'selected':'' }}>{{ __('messages.cheques.not_payed') }}</option>
<option value="3" {{ $cheque->statue == "3" ? 'selected':'' }}>{{ __('messages.cheques.transfered') }}</option>
</select>
</td>
<td>
<i class="fa fa-edit"></i>
<i class="fa fa-trash-alt"></i>
</td>
</tr>
#endforeach
</tbody>
and i want when ever the select statue change i want to pop the model and this is what i done
$("#statue").on('change', function(e){
e.preventDefault();
var tr = $(this).parents('tr');
var id = $(tr).data('id');
var statue = $(this).val();
bootbox.confirm({
size: "small",
message: "{{__('messages.cheques.statue_confirmation')}}",
buttons: {
confirm: {
label:"{{__('messages.buttons.confirm')}}",
className: 'btn-sm btn-danger'
},
cancel: {
label:"{{__('messages.buttons.cancel')}}",
className: 'btn-sm btn-defaul'
}
},
callback: function(result){
if(result){
if(statue == 3){
$("#transfer-cheque-form").find("#id").val(id);
$("#transfer-cheque").modal();
}else{
$.post('change-statue/'+id, {_token:$('meta[name="csrf-token"]').attr('content'), statue:statue}, function(data){
if(data.success){
}
});
}
}
}
});
});
but the problem is the model popup only on the first item on the table otherwise nothing happens
i'm using an template ready who has a dynamic table with pagination
I suspect the issue is you are grabbing it by id of statue. The id is supposed to only correspond with one item on the page (id's should be unique). What you probably want to do is add a class to your select and modify your jquery selector to select that class instead.
<select name="statue" class="form-control" id="statue" class="statue-select">
$(".statue-select").on('change', function(e) {
...
});
Firstly an HTML DOM can only contain single with an ID. You can do :
$('select[name="statue"]').on('change', function(e) {
...
});
If your elements are getting appended/manipulated dynamically on ajax pagination for example, you can do :
$(document).on('change', 'select[name="statue"]', function(e) {
...
});
You should not have a static ID in the select element, you can solve the problem adding a function to listen the select change
function myFunction(event){
//TODO
}
<select onchange="myFunction(event)">

(symfony2) how to persist an entity using ajax

i'm coding a simple forum, and i want that the user add the message without refreshing the page, i dont know about ajax , i tried to make things work but when i click on the submit button nothing happens, any help please ??
here is my cotroller :
$request = $this->get('request');
$entityManager = $this->getDoctrine()->getManager();
$msga = new Msg();
$form = $this->get('form.factory')->create(new MsgType());
$form->handleRequest($request);
if ($form->isValid())
{
if($request->isXmlHttpRequest())
{
$msga->setContenu($form->get('contenu')->getData());
$msga->setDateEcriture($date);
$msga->setNbvote(0);
$msga->setUser($user);
$msga->setForum($forum);
$entityManager->persist($msga);
$entityManager->flush();
return $this->render('otaotaBundle:Forum:forum.html.twig', array(
'forum'=>$forum,
'msg'=>$msg,
'msgUF' =>$msgByUser,
'id' => $forum->getIdForum(),
'form' => $form->createView(),
'action' => "add",
));
}
}
and the view:
{% extends "::base.html.twig" %}
{% block body %}
<form action="{{path("show_forum", {id: id} )}}" method="post" novalidate>
Date de création :
<h7>{{forum.datedebforum|date("Y-m-d")}}</h7><br/><br/>
{{forum.description}}<br/><br/><br/>
<table>
{% for m in msg %}
<tr>
<td>
{{m.dateEcriture|date("Y-m-d")}}<br/>
{{m.nbVote}}
{{m.contenu}}
<br/><br/>
</td>
<td>
{% for ms in msgUF %}
{%if ms.idMsg == m.idMsg %}
<a class="link" href="{{ path('delete_msg',{id: ms.idMsg}) }}">supprimer</a>
{% endif %}
{% endfor %}
</td>
</tr>
{% endfor %}
</table>
<br/>
{% if is_granted('IS_AUTHENTICATED_REMEMBERED') %}
{{ form_widget(form._token) }}
<textarea name="textarea" id="contenu"></textarea>
<input type="submit" value="Repondre" />
<script>
$(document).ready(function() {
$('form').submit(function(event) {
// prevents the browser from "following" the link
event.preventDefault();
var $url = $("form").attr("action");// + '.json';
var $value = $('#contenu').val();
$.ajax({
type: "POST",
url: $url,
data: $value
});
});
});
</script>
{% endif %}
</form>
{%endblock%}
i want that the message shows up after the submitting without refreshing

How to add n forms using jquery

Here I found the following helpful javascript to dynamically add a form to my python/django template. Here is the code:
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
// Make a variable and assign to it a string convertd to an integer. The string is the variable
// with the the #id assigned to it. The value of this attribute is saved. The value will equal
// the current number of forms
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
// Find the element with the given class, and clone it after loading the 0 index get request.
// Var row is now a cloned row.
var row = $('.dynamic-form:first').clone(true).get(0);
$(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden');
$(row).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, formCount);
$(this).val('');
});
$(row).find('.delete-row').click(function() {
deleteForm(this, prefix);
});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
function deleteForm(btn, prefix) {
$(btn).parents('.dynamic-form').remove();
var forms = $('.dynamic-form');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, i);
});
}
return false;
}
Then I have my following template.
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% crispy form form.helper %}
{% load staticfiles %}
{% block extrahead %}
{% endblock %}
{% block blurb %}
<h1>Upload Samples</h1>
<p>Upload A Single Sample, Or A Batch Of Samples</p>
{% endblock %}
{% block form %}
<style>
tr th {text-align:center;}
</style>
<!-- Display formset -->
<form id="myForm" method="post" action="">
{{ formset.management_form }}
<div class='table'>
<table class='no_error' id='id_forms_table' border="2px" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
{% for form in formset %}
<tr id="{{ form.prefix }}-row" class="dynamic-form">
<td></td>
<
<td {% if forloop.first %} class="hidden"{% endif %}>
<a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row"><input type='button' value='Remove Row' class='delete-row'></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
<!-- Dynamic Formset javascript -->
<script type="text/javascript">
$(function () {
$('.add-row').click(function() {
return addForm(this, 'form');
});
$('.delete-row').click(function() {
return deleteForm(this, 'form');
})
$('.add-10-rows').click(function() {
return addForm(this, 'form');
})
})
</script>
<input type='button' value='Add Row' class='add-row'>
<input type='button' value='Add 10 Rows' class='add-10-rows'>
<div style='padding-top:20px'>
<input class='btn btn-primary' type='submit' value='Upload' />
</div>
{% endblock %}
This works great, but now I would like to adjust this to allow for the addition of n rows. I will make a form that takes in an interger, then when a button is pressed, I would like to add that number of forms instead of one at a time. I am quite new to javascript/jquery, but I figured the psudo code would look something like this:
function addNForms(btn, prefix, n){
for(var i = 0; i < n; i++){
// Perform the same logic as addForm.
}
}
Unfortunately I have not been able to figure it out. I have performed the function logic n times in a for loop, but the result was that only one form at a time was being made. Which part of the addForm function can I put in a for loop to achive this goal?

Getting post data from html table inside a form? Django

I have a dynamically populated html table that can be edited by an user (they can add rows delete them, etc -this is managed through javascript-).
The problem is, even when the table is inside the form, the server doesn't get any post data from it.
Here is the code for the template:
{% extends 'base.html' %}
{% block content %}
<script>
function add_row(){
var table = document.getElementById("body");
var row = table.insertRow(table.rows + 1);
var cell = row.insertCell(0);
var combo1 = document.createElement("select");
var option;
{% for opt in options_all %}
option = document.createElement("option");
option.setAttribute("value", "{{ opt.id }}");
option.text="{{ opt.description }}";
combo1.add(opcion);
{% endfor %}
cell.appendChild(combo1);
}
</script>
<form action='.' method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type="button" value="New row" onclick="add_row()">
<table id="table_id">
<thead>
<tr>
<th>
Options
</th>
</tr>
</thead>
<tbody id="body">
</tbody>
</table>
<input type='submit' value='Submit'>
</form>
{% endblock %}
How can I get the data from the select elements?? Thanks!!
Edit: I have checked the request element and request.post doesn't have the desired data
SOLVED.
You have to specify a name for each select element inside the table. (Not the option elements)

Categories

Resources