multiple form generated jquery doesn't submit - html

I'm building a website (e-commerce like) with Django.
At some point I display a list of items and for each item there is a form with submit button Order and Quantity picker.
I've implemented filter function that delete the html code of my items list and rebuild it with the matching items with jquery.
The new forms generated by this function do nothing when the submit button is clicked
Here is a part of the code I use in my function (I use an ajax call to generate a json of matching items and then I display them in the table list) :
$.each(code_json, function(index, value){
var string = "<tr id="+ value.material +"><td>"+ value.manufNo +"</td><form method='POST' action='/add_to_cart/"+value.material+"/"+ value.node+"/{{language}}'><td><input type='submit' class='btn' value='Commander' style='color:blue;'></td><td><input id='qty' type='number' name='qty' class='form-control' value='1'></td></form></tr>";
$("#header").after(string);
});
I know that usually with Django you have to add {% csrf_token %} for each form. However it throw an error page usually when missing and here it doesn't show anything
Edit : I tried to bind an onclick event on the submit button dynamically created. In this I did a $.post in jquery to simulate the submit of the form but nothing happend
$(document).on('click', '.btnStandard', function(event) {
console.log($(this).attr('id'));
$.post('/add_to_cart/'+$(this).attr('id'),
{
qty: $("#qty"+$(this).attr('id')).val()
},function(data,status,xhr){
alert("Data : "+data+", status: "+status+", xhr: "+xhr);
});
It print in console $(this).attr('id') but it doesn't do anything else
Thank you for your help

It doesn't explain why I have this problem but I found a workaround to solve my problem.
Instead of dynamically generate forms, I generate them with template and then I hide them all. Later, I make those I need visible when I need thanks to css.

Related

AngularJS - bind ng-model with button click

I've got an irritating problem with data binding using ng-model and button.
The principle of operation of my site:
My HTML site displays a list of projects (loaded from external .json file).
Each row has a button named Edit which displays a modal containing some <input type="text" filled with relevant data about project (like project.name, project.date etc.)
Initial value of input is equal to object data (text-input called Name will contain project.name etc.)
Object is modified only if you click Save button and confirm the operation (confirm(sometext) is okay).
Closing the modal, not clicking the button or pressing cancel on confirmation box should prevent data from being updated.
Editing input (let's say that project.name is "Project2" and I modify it by adding 3 numbers resulting in "Project2137"), closing modal and opening it again should result in "Project2" text inside input (because object wasn't modified, only input)
So far I understand that single text input should look like this
<input type="text" id="editName" class="form-control" ng-model = "project.name">
Using ng-model means that they are binded. That's what I know. However editing input means that object is updated as soon as I enter some data.
I tried to fiddle with ng-model-options but I didn't find any possible solutions.
I tried to do it programmatically as well using
<input type="text" id="editName" class="form-control" value = {{project.name}}>
....
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
And function:
$rootScope.edit = function(project)
{
if(confirm("Are you sure to save changes?"))
{
project.name = angular.element(document.getElementById('editName')).val();
// ...and so on with other properties
This solution is kinda close to what I wanted to achieve (object is updated only on confirm), but I faced another problem: input loads data from object only once at the beginning instead of each time the modal is opened which is against rule #5
Is there any way to fix this using either ng-model bind or custom function? Or maybe there is some other, easier way?
--EDIT--
Here I don't have any problem with saving the data using a button, everything works well and clicking Save is reflected in a projects list. (well until I hit a F5 key).
The problem is that input text is not properly binded to project and that's what I want to fix.
Sample data (pseudocode)
project1.name = "Proj1"
project2.name = "Proj2"
I click an Edit button on row #1
Text input displays "Proj1". Everything is fine.
I change input by adding some random characters like "Proj1pezxde1"
Text input is now "Proj1pezxde1"
I do not click Save button.
I close the modal.
Project summary still displays "Proj1". Okay.
I click an edit button on first row
10. Text input is "Proj1pezxde1" even though I didn't modify an object.
Text input should read data from object again (each time I open this modal) and thus display "Proj1"
That's the problem I want to fix. Sorry for being a little bit inaccurate.
You can create a copy of the project object in modal controller and use this object to bind with the input element of the modal
$scope.copyProj = angular.copy($scope.project);
Assign the copy object properties to project only when save is clicked.
As per my understanding after reading the provided descriptions, you have a list of projects, which is being used as in an repeater and you want to bind each projects data to a Text box and a Button.
Have you tried initializing your Projects object following way?
$scope.projects = [
{ 'name': 'proj1', 'id': '1' },
{ 'name': 'proj2', 'id': '2' }
];
Then you can do something like below to show your data
<div ng-repeat="project in projects">
<div>
<input type="text" class="form-control" ng-model = "project.name">
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
</div>
</div>
The simplest way to do this in my opinion is using a second object that is a copy of the project, and after confirmation applying the changes to the original project object.
For example, a simple "pseudo code" of a controller:
function MyCtrl($scope) {
$scope.projects = [...];
$scope.currentProject = null;
$scope.edit = function(project) {
$scope.currentProject = angular.copy(project); // This will create a copy so the changes in $scope.currentProject will not reflect.
// Open dialog with input bound to $scope.currentProject
if (confirm) {
// Assign all properties from currentProject to project
angular.extend(project, $scope.currentProject);
}
}
}
So , as I understand from your question , you need to update the project data only if it is saved. To do that you can maintain a copy of the actual object which get updated only it is saved like below :
Here we are using angular.copy(), which does a deep copy of the source object.
$scope.original = {name : "xyz"};
$scope.project = angular.copy(original);
//Call this when the user confirms to save , here we are replacing the
//original copy with the latest object that needs to be saved.
$scope.save = function () {
$scope.original = angular.copy($scope.project);
}
//Call this when closing the modal or clicking cancel or when losing
//focus, this will reset the changes to the original copy.
$scope.reset = function () {
$scope.project = angular.copy(original);
}

show tempdata message of mvc5 as bootbox alert message

I am new at MVC and I want to show an alert message from the Controller tempdata as bootbox alert message
How can it be done? Please somebody help me with an example
Say you have TempData["Message"]
In your view assign it to some hiddenField as below
#{
var message=TempData["Message"] as string;
}
<input type="hidden" value="#message" id="hdnMessage"/>
Now write a document.ready function and check if the hidden field has value and if yes show your message as below:
$(document).ready(function(){
if($("#hdnMessage").val()!="")
{
var msg=$("#hdnMessage").val();
bootbox.alert(msg);
$("#hdnMessage").val('');//empty the value so that it won't show everytime
}
});
Assuming a <script> tag is used in the view, you can directly inject the value from TempData into JavaScript. Something like this would work:
#if(TempData.ContainsKey("Message"))
{
<script>
$(function(){
bootbox.alert('#TempData["Message"]');
});
</script>
}
This won't work in a .js file, as those aren't parsed by the Razor engine.
You could put this in a partial view, or include it somewhere in _Layout, or simply use it in the view you're currently working in. The only important bit it to remember that it needs to be rendered after jQuery, bootstrap.js, and bootbox.js.

Empty action attribute on a form with angularJS

I'm trying to submit a form the normal way in a AngularJS application but I encounter an issue : it seems that I must specify the action attribute.
According to the HTML specifications (http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm) :
If action is the empty string, let action be the document's address of
the form document.
But AngularJS refuses to submit the form if the action attribute is not filled.
A work-around I found would be to use action="#" but this is not an acceptable solution since I might use the hash and I don't want it to be rewritten.
Has anyone ever experienced this issue ?
Edit : I don't want to use angular for this form, I just want to submit it the "old" way
I created a small directive to solve this:
.directive('form', ['$location', function($location) {
return {
restrict:'E',
priority: 999,
compile: function() {
return {
pre: function(scope, element, attrs){
if (attrs.noaction === '') return;
if (attrs.action === undefined || attrs.action === ''){
attrs.action = $location.absUrl();
}
}
}
}
}
}]);
Seems to be good for me. It looks for a form where the action is empty, and sets it to the current url.
Actually, it doesn't set the action - it sets the attr value, so the actual form directive thinks it's got one.
Update by #Reimund is good - I have actually had to do the same.
New Update - I have added the option to add a noaction attribute to the form element; this enables you to return to a "normal" angular situation. Otherwise this directive will submit forms twice if using ajax.
In the library, you can see that Angular listens to the event submit of your forms without action : https://github.com/angular/angular.js/blob/b9fa5c5a6781f4e1ec337f27d55c69db491a6555/src/ng/directive/form.js#L331
You can comment this line, it works, but I'm against editing the code of libraries.
Few lines after, you can see that Angular listening to the event $destroy enabling to remove the action on this event.
Therefore, to avoid modifying Angular, you can just trigger this event of your form:
angular.element(document).ready(function(){
angular.element(document.querySelector("#loginForm")).triggerHandler("$destroy")‌​;
});
The reason of this behavior is described few lines above:
we can't use jq events because if a form is destroyed during submission the default action is not prevented.
And the related issue is: https://github.com/angular/angular.js/issues/1238
You can use ng-submit.
Form
<form name="test" action="" ng-submit="submit()">
What's your name? <input ng-model="name" /><br />
<button>Send</button>
</form>
<br />
My name is: {{name}}
JS
var app = angular.module('App', []);
app.controller('AppCtrl', function($scope) {
$scope.submit = function() {
$scope.name = $scope.name + ' Doe';
}
});
Plunker http://plnkr.co/edit/rqAwxWmozrzwwj4oAU5k?p=preview
Normally I simply make button with ng-click handler.
<button ng-click="Generate()">Submit</button><br>

How to call a function on click in x-editable form (Twitter Bootstrap)

I have a input text field inside a div(x-editable form). I need to call a Jquery function on the button click. How to do so.?
This is my div
<div class="input-append"><input type="text" id="WorkloadName" placeholder="enter your workload name" name=""></div>
This is my jquery function for x-editable form
jQuery.noConflict();
(function($) {
$(function() {
jQuery.fn.editable.defaults.mode = 'inline';
jQuery('#WLElementName').editable();
});
})(jQuery);
In x-editable form after clicking the textfield a form will appear, i need to call the function on the click of the submit button (blue button with tick mark, I could not post the image here since I don't have enough reputation score)
I tried calling the function using the class name of the button but its not coming. please help me to fix this
In your .editable declaration, add a dictionary parameter
url: function(params) {}
and perform your task in there.
See http://vitalets.github.com/x-editable/docs.html#editable for further documentation.

Zimra - How I can handle HTML forms in zimlets?

I try to create a tab Zimlet that contains a HTML form. I just want to now how I can handle submit button in my form or how can I submit a form with ajax toolkit.
Let me have a general suggestion...
Try to do everything base on zimbra standards
You can check and download examples to be familiar with the default way to do the different jobs...
Back to your question, how is your form made? is it a normal html form or created dynamically by javascript?
If html, just set the onclick of your submit form to the zimlet's function and define whatever you wanna do inside that function
<input onClick="yourzimlet.prototype.OkFunction();" type="button" >
yourzimlet.prototype.OkFunction= function(){
//do somthing...
}
if in javascript, you have (at-least) two ways
1-using normal onclick
var formTag = document.createElement("form");
//add form elements to formTag...
var inputTag = document.createElement("input");
inputTag.type= 'button';
inputTag.setAttribute("value", "submit ... ");
inputTag.onclick = function() { yourzimlet.prototype.OkFunction();}
formTag.appendChild(inputTag);
yourzimlet.prototype.OkFunction= function(){
//do somthing...
}
2-using zimbra javascript API
Instead of having a form with normal onclick, better (depends on your situation) to create a form dynamically using javascript and add a dwtButton as submit button
http://files.zimbra.com/docs/zimlet/zcs/7.2.0/jsdocs/symbols/DwtButton.html
You can define a listener for the form's submit button and then do whatever you want to do in your listener function
In all conditions you can have access to the form's elements and their values by their id