I have PartialView
Here is code
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Выберите проект</label>
<select id="projectId" name="add_triangolazione" class="form-control">
</select>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">От:</label>
<input type="date" class="form-control" id="datefrom">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">До:</label>
<input type="date" class="form-control" id="dateto" placeholder="YYYY-MM-DD" data-date-split-input="true" >
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Наименование услуги:</label>
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">График работы:</label>
<div>
<label for="message-text" class="col-form-label">С:</label>
<input type="time" class="form-control" id="workTime">
</div>
<div>
<label for="message-text" class="col-form-label">По:</label>
<input type="time"" class="form-control" id="workTimeTo">
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Количество:</label>
<textarea class="form-control" id="quantity"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Тариф:</label>
<textarea class="form-control" id="rate" readonly></textarea>
</div>
It loading into modal via script
Here is script code
$(document).on('click', '#addShow', function () {
ShowAndPopulate();
});
function ShowAndPopulate() {
$('#addProposalManager').load('/Manage/AddProposalManager', function () {
let email = $('#userId').text();
let getProposalsUrl = '/manage/populateprojects';
model = {
email: email
},
$.ajax({
url: getProposalsUrl,
data: JSON.stringify(model),
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
var list = data;
$.each(list, function (i, d) {
$('#projectId').append('<option value="' + d.Id + '">' + d.Name + '</option>');
});
}
})
});
}
Also in this field
#Html.DropDownList("Service", null, "XXXX", htmlAttributes: new { #class = "form-control", #id = "serviceIdProject" })
I need to do something on value change
So I wrote this code at script
$('#serviceIdProject').change(function () {
alert("Gotcha!");
// ServiceChange();
});
But when I change value, nothing happens.
Where can be my problem?
Thank's for help
Try using event delegation and also you seem to be using the wrong ID for the select:
$(document).on('change' , '#projectId' , function () {
alert("Gotcha!");
// ServiceChange();
});
Related
I have my html form as shown below:
<div class="container">
<div class="form-group" ng-controller="studentController">
<form role="form" class="well form-horizontal" id="registerForm" name="forms.registerForm">
<div class="form-group">
<label class="col-md-4 control-label">First Name </label>
<input ng-model="formdata.firstname" required type="text" name="firstname">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Middle Name </label>
<input ng-model="formdata.middlename" required type="text" name="middlename" maxlength="1">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Last Name </label>
<input ng-model="formdata.lastname" required type="text" name="lastname">
</div>
<div class="form-group">
<label for="email" class="col-md-4 control-label">E-mail address</label>
<input ng-model="formdata.email" required type="email">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Student ID</label>
<input ng-model="formdata.studentid" required type="number">
</div>
<div required class="form-group">
<label class="col-md-6 control-label">
level
</label> <br>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="300" checked>
300 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="400">
400 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="500">
500 </label>
</div>
</div>
<div class="form-group" align="center">
<input type="file" ngf-select ng-model="formdataa.file" name="file" ngf-pattern="'application/pdf'" accept="'.pdf'" ngf-max-size="5MB" required ngf-model-invalid="errorFile">
</div>
<div class="container" align="center">
<button class="btn btn-register" ng-click="tempData()" ng-disabled="forms.registerForm.$invalid" >Submit</button>
</div>
Below is the angular javascript code to store the details of the form and the file in the server.
$scope.tempData = function(ev){
console.log($scope.formdata);
var confirm = $mdDialog.confirm()
.title('Are you sure you want to delete this user?')
.ok('YES')
.cancel('CANCEL');
$mdDialog.show({
locals:{formdata: $scope.formdata, dataToPassFile: $scope.formdataa}, //here where we pass our data
controller: _DialogController,
controllerAs: 'vd',
templateUrl: 'scripts/app/studentdialog/studentdialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
})
.then(
function(answer) {},
function() {
}
);
};
function _DialogController($scope, $mdDialog, formdata,dataToPassFile) {
$scope.closeDialog = function() {
$mdDialog.hide();
};
$scope.firstname = formdata.firstname;
$scope.lastname = formdata.lastname;
$scope.middlename = formdata.middlename;
$scope.studentid = formdata.studentid;
$scope.email = formdata.email;
$scope.type = formdata.type;
$scope.file = dataToPassFile.file;
console.log('FIle Passed' +dataToPassFile.file);
$scope.tfile = function () {
console.log("TFIle Called");
if ($scope.forms.registerForm.file.$valid && $scope.formdataa.file) {
$scope.upload($scope.formdataa.file);
}
};
$scope.upload = function (file) {
file.upload = Upload.upload({
url: $rootScope.baseURL + 'php/uploadT.php',
method: 'POST',
data: {
'file': file,
'userId': $scope.formdata.firstname,
'type': $scope.formdata.type
},
});
$scope.register = function () {
console.log("clicked");
$scope.loading = true;
AppServices.register($scope.formdata)
.then(function (result) {
if (Object.keys(result).length > 0) {
// update current users list
if (result.type == '300' || result.type == '400') {
$scope.users.300.push(result);
} else {
console.log(result);
$scope.users[result.type] = result;
}
$scope.forms.registerForm.$setPristine();
$scope.forms.registerForm.$setUntouched();
$scope.msg = {};
$scope.msg.successRegister = 'Registered Successfully';
} else {
$scope.msg = {};
$scope.msg.errorRegister = 'Email already exists!';
}
})
.finally(function (data) {
$scope.loading = false;
});
};
When the user clicks on Submit button, I want to create a confirmation page where it will give the user all the details again so the user can confirm and then actually submit the form. Kindly let me know how can I use localStorage for storing and retrieving the data at the same time for confirm page.
Thank you in advance!
UPDATE: I created a MDDialog and calling it when the button is clicked,I can see all the data as well in MDDialog now. When user clicks on OK, I want the data on the page(not the data on the MDDialog) to be submited in the backend(php), how can I do that?
Why not show this info on a modal, and call the confirmation function in the same controller where you are, after the modal is closed. This way you won't need any caching policy.
I have a forms.ImageField in my model called Post. When I create an instance of it, I do it via Ajax, while posting serialized data with data=$(this).serialize() to my PostCreateAPIView, which is a generic API CreateView of Django REST Framework, but this method serializes data only and ignores my image.
Here's my code:
My CreateAPIView:
class PostCreateAPIView(generics.CreateAPIView):
serializer_class = PostModelCreateSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
print(self)
serializer.save(user = self.request.user)
My Form:
class PostModelCreateForm(forms.ModelForm):
content = forms.CharField(
label="",
help_text="",#text to help
widget=forms.Textarea( attrs={
'cols' : "50", #size
'rows' : "6", #size
'placeholder' : 'Votre publication',
'style' : 'resize : none'
}))
group = forms.ChoiceField(choices=USER_GROUPS, label='')
class Meta:
model = Post #we define the model
fields = [
"content",
"group",
"photo"
]
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
this_ = $(this);
var formData = this_.serialize();
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
success : function(data){
},
error : function(data){
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id = 'post-form' class="post_form_class" method="POST" action="" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='6bgEU7jPVxXskBGJzP7KzSj9mz75k2dpSqG9Fn1kfghUeWQPTKCbm8JJc5za0ecl' />
<p></p>
<div id="div_id_content" class="form-group"> <div class="controls "> <textarea name="content" cols="50" rows="6" placeholder="Votre publication" style="resize : none" class="textarea form-control" required id="id_content">
</textarea> </div> </div> <div id="div_id_group" class="form-group"> <label for="id_group" class="control-label requiredField">
Group<span class="asteriskField">*</span> </label> <div class="controls "> <select name="group" class="select form-control" id="id_group"> <option value="1" selected>Département juridique</option> <option value="2">Département ingénieurs</option> <option value="3">Département Commerce</option> <option value="4">Nouveau</option>
</select> </div> </div> <div id="div_id_photo" class="form-group"> <label for="id_photo" class="control-label ">
Photo
</label> <div class="controls "> <input type="file" name="photo" class="clearablefileinput" id="id_photo" /> </div> </div>
<div class="row">
<div class='col-sm-2 '>
<input class="btn btn-primary submit_form" id="submit_form" type="submit" value="Publier"/>
</div>
<div class='col-sm-1 col-sm-offset-8 '>
<span class='post-chars-left' > </span>
</div>
</div>
</form>
N.B: I've tried formData = new FormData(this_); but I get this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement
Thanks to Luca, here is the answer:
$(document.body).on("submit", ".post_form_class",function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
method : "POST",
url : createPostUrl,
data : formData,
processData:false,
contentType:false,
success : function(data){
location.reload(true);
},
error : function(data){
console.log("ERROR:CH0x2 while fetching after creation form submit");
console.log("data :",data.status, data.statusText);
}
});
});
The serialize() function returns an empty string , This is my code :
Code to return form :
$.ajax({
url: 'api/form',
type: 'get',
crossDomain: true,
}).done(function(response){
fields = JSON.parse(response);
html = '';
$.each(fields, function(index,field){
html += field;
});
html += '<div class="btn-clear"></div><button class="btn payment">Pay</button></div>';
$("#cart-content").html(html);
}).fail(function() {
console.log('Failed');
});
Javascript code executed after user clicks payment button :
$("body").on('click','.payment',function() {
var frmData = $("#customer").serialize();
console.log(frmData);
});
But it log an empty string !!
The form after it's ajax loaded :
<form id="customer"><div class="form-group">
<label class="control-label">Full name</label>
<input name="name" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">E-mail</label>
<input name="email" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Mobile</label>
<input name="mobile" class="form-control" type="text">
</div><div class="form-group">
<label class="control-label">Country</label>
<select id="country" name="country" class="form-control" type="text"><!-- countries ... --></select>
</div></form>
Try your serialize like this
$("#form").submit(function () {
var data = $('#form').serialize();
Use the form ID as the target. Here I used #form. Submit the form, serialize the forms inputs.
I'm getting this error when I try to update a file on my form..."You did not select a file to upload." ...and the problem is that I really am selecting a new file to upload...help me pls, I don't understand what is happening ...here is my code:
FORM
<form class="col s12" id="update_form" required="" enctype="multipart/form-data" aria-required="true" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" required="" aria-required="true" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" required="" aria-required="true" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" required="" aria-required="true" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" required="" aria-required="true" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación/Imagen</span>
<input type="file" name="animation">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" id="animation" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" required="" aria-required="true" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
CONTROLLER
public function update_politic(){
$this->load->model("politic");
$params;
if ($this->input->is_ajax_request()) {
if (empty($this->input->post("animation"))){
echo "first";
$data = $this->politic->get_file_name($this->input->post("update_politic_hide"));
$file = $data->POLITIC_FILE;//recupero el nombre de la imagen
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["section"] = $this->input->post("section");
$params["animation"] = $file;
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
else {
echo "second";
$config['upload_path'] = "./public/uploads/";
$config['allowed_types'] = "*";
//$config['overwrite'] = "true";
$config['max_size'] = "500000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
//$file = "animation";
if (!$this->upload->do_upload("animation")) {
$data['uploadError'] = $this->upload->display_errors();
echo $this->upload->display_errors();
}
else {
$file_info = $this->upload->data();
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $file_info['file_name'];
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
}
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
"POLITIC_FILE" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
JAVASCRIPT
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
$.post(baseurl + 'admin/update_politic', chango,
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
function update_politic(id, name, lastname, section, side, charge, file) {
$("#update_politic_hdn").val(id);
$("#update_name").val(name);
$("#update_last_name").val(lastname);
$("#update_side").val(side);
$("#update_charge").val(charge);
$('[name=section]').val(section);
$("#animation").val(file);
$('select').material_select();
}
There are two name attributes having the same value animation.
<input type="file" name="animation">
and
<input class="file-path validate" id="animation" name="animation" type="text">
The second name attribute is overriding the first one. You need to give it a different name.
Change your Ajax code :
$("#update_politic_btn").click(function(event) {
var chango = new FormData($("#update_form")[0]);
// try this if above one not work
//var chango = new FormData($("#update_form"));
$.ajax({
url: baseurl + 'admin/update_politic',
type: 'POST',
data: chango,
async: false,
success: function (data) {
console.log(data);
list_politic();
},
cache: false,
contentType: false,
processData: false,
error : function() {
}
});
event.preventDefault();
});
I have a form, after document.ready() I load data into this form, but form values (device name) was cleared on mobile browsers, after tap on screen.
$.ajax({
type: 'GET',
url: "api.ashx",
data: "operation=device.get&deviceid=" + deviceid,
success: function(response) {
var apiResponse = jQuery.parseJSON(response);
if (apiResponse.result == 'true') {
$("#name").val(apiResponse.name);
if (apiResponse.online == 'true') {
$("#status").html('<span class="label label-success">online</span>');
} else {
$("#status").html('<span class="label label-red">offline</span> Был в сети: ' + apiResponse.lastvisit);
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form id="deviceinfoform" action="#" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label class="col-sm-3 control-label">Device name <span class="require">*</span>
</label>
<div class="col-sm-6 controls">
<input id="name" name="name" required="" type="text" placeholder="Device name" maxlength="100" class="form-control"></input>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Device status</label>
<div class="col-sm-6 controls">
<div id="status" class="form-control">
<span class="label label-success">online</span>
</div>
</div>
</div>
</div>
</form>
Problem is solved. The problem was in bootstrap-responsive-tabs plug-in.
fakewaffle.toggleResponsiveTabContent = function () {
var tabGroups = $('.nav-tabs.responsive');
$.each(tabGroups, function () {
var tabs = $(this).find('li a');
$.each(tabs, function () {
var href = $(this).attr('href').replace(/#/g, ''),
tabId = "#" + href,
panelId = "#collapse-" + href,
tabContent = $(tabId).html(),
panelContent = $(panelId + " div:first-child").html();
//!!!clear all dynamic content
$(tabId).html(panelContent);
$(panelId + " div:first-child").html(tabContent);
});
});
};
Updating to the latest version solved a problem.