Replacing two variables after filling a form - javascript

I'm not much of a Javascript expert, but sometimes I need to turn to it.
I have a script which allows the user to choose two dates (from and to) to create a report.
<div onmouseover="myFunction()">
<input id="id_from_date" name="from_date" type="text">
<input id="id_to_date" name="to_date" type="text">
</div>
<script>
function myFunction() {
$('#id_from_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
$('#id_to_date').datetimepicker({
format: 'd-m-Y',
lang: 'pl',
pickTime: false,
timepicker: false,
weeks: true,
dayOfWeekStart: 1,
closeOnDateSelect: true
});
var from = document.getElementById("id_from_date").value;
var to = document.getElementById("id_to_date").value;
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
document.getElementById("link").setAttribute("href", url.replace(/11-11-1111/, from), url.replace(/12-12-1212/, to))
}
</script>
<a id="link" type="button" class="btn btn-success">go!</a>
I'm at the end of my tether here. The code replaces the first variable, id_from_date, with the date a user chooses. Unfortunately, it ignores the second variable, id_to_date. Can anyone please give me a hint why it happens so?
I cannot leave var url withour any initial values, because the application crashes without anything given while opening the view.
The whole project is created in Django and the view for the report is:
def report_from_to(request, from_date, to_date):
from datetime import datetime
strfrom = datetime.strptime(from_date, "%d-%m-%Y")
strto = datetime.strptime(to_date, "%d-%m-%Y")
report = Braki.objects.filter(Q(date__gte=strfrom), Q(date__lte=strto))
return render(request, 'logistyka_tabela_brakow/report_from_to.html', {'report': report})
the form:
class ReportForm(forms.Form):
from_date = forms.DateField()
to_date = forms.DateField()
fields = '__all__'
the url is obviously:
url(r'report_from_to/(?P<from_date>[0-9]{2}-[0-9]{2}-[0-9]{4})/(?P<to_date>[0-9]{2}-[0-9]{2}-[0-9]{4})',
'logistyka_tabela_brakow.views.report_from_to', name='report_from_to'),

The syntax of setAttribute is
element.setAttribute(name, value);
You are calling it with 3 arguments, so the third one gets ignored.
document.getElementById("link")
.setAttribute("href",
url.replace(/11-11-1111/, from),
url.replace(/12-12-1212/, to)
);
This should do it
var url = '{% url 'logistyka_tabela_brakow.views.report_from_to' '11-11-1111' '12-12-1212' %}';
url = url.replace(/11-11-1111/, from);
url = url.replace(/12-12-1212/, to);
document.getElementById("link").setAttribute("href", url);

Related

I can't get Html.TextBoxFor value with JavaScript

I am facing a very interesting problem.
the control I use
<input id="DOSYA_NO" name="DOSYA_NO" class="form-control" />
I can get the input value with the code below.
$("#gelenevrakFoto").click(function () {
alert($('#DOSYA_NO').val());
});
but this way the input value is empty.
$("#gelenevrakFoto").fileinput({
uploadUrl: "/Dosya/Upload?policeId=" + $('#POLICE_ID').val() + "&Kategori=GELENEVRAK&dosyaNo=" + $('#DOSYA_NO').val(),
maxFileCount: 10,
showBrowse: true,
browseOnZoneClick: true
});
Please I would like you to help on the subject. Thanks.
Try using callback function
You can also set uploadUrl as a function callback which will return a
string. In that case, the function will get executed at runtime just
before every ajax call. This will enable you to set a dynamic upload
url based on runtime / dynamic conditions.
https://plugins.krajee.com/file-input/plugin-options#uploadUrl
$("#gelenevrakFoto").fileinput({
uploadUrl: function() {
let params = {
policeId: $('#POLICE_ID').val(),
dosyaNo: $('#DOSYA_NO').val(),
Kategori: 'GELENEVRAK'
};
return "/Dosya/Upload?" + $.param(params); // $.param for good practice
},
maxFileCount: 10,
showBrowse: true,
browseOnZoneClick: true
});

Unmask datetime - inputmask

Using Inputmask vanilla js version.
Having problems with unmasking datetime format:
var expDate = document.getElementById('expDate');
Inputmask({
alias: 'datetime',
inputFormat: 'mm/yy',
placeholder: 'month/year',
autoUnmask: true,
clearMaskOnLostFocus: false
}).mask(expDate);
autoUnmask not working, expDate.value returns 12/12, though it should be returning 1212.
I have created a minimal example and the autoUnmask option is working, maybe there are some conflicts with alias: 'datetime' or inputFormat: 'mm/yy'. Read next documentation that is available on the plugin web site:
aliases
With an alias you can define a complex mask definition and call it by using an alias name. So this is mainly to simplify the use of your masks. Some aliases found in the extensions are: email, currency, decimal, integer, date, datetime, dd/mm/yyyy, etc.
First you have to create an alias definition. The alias definition can contain options for the mask, custom definitions, the mask to use etc.
When you pass in an alias, the alias is first resolved and then the other options are applied. So you can call an alias and pass another mask to be applied over the alias. This also means that you can write aliases which "inherit" from another alias.
Some examples can be found in jquery.inputmask.xxx.extensions.js
format
Instead of masking an input element it is also possible to use the inputmask for formatting given values. Think of formatting values to show in jqGrid or on other elements then inputs.
var formattedDate = Inputmask.format("2331973", { alias: "datetime", inputFormat: "dd/mm/yyyy"});
Like you can see, datetime is a defined alias (you can check the definition on inputmask.date.extensions.js), and inputFormat is used for other purposes. On the next example, there is one input with autoUnmask option configured on true and the other with the default value of false:
// Get the inputs fields
var expDate1 = document.getElementById('expDate1');
var expDate2 = document.getElementById('expDate2');
// Apply masks on the inputs.
Inputmask({
alias: 'date',
autoUnmask: true,
clearMaskOnLostFocus: false
}).mask(expDate1);
Inputmask({
alias: 'date',
clearMaskOnLostFocus: false
}).mask(expDate2);
// Alert values.
function getValuesFromInputs()
{
var msg = "Value of Input1 with autoUnmask=true: " + expDate1.value;
msg += "\n"
msg += "Value of Input2 with autoUnmask=false: " + expDate2.value;
alert(msg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/dependencyLibs/inputmask.dependencyLib.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.extensions.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/inputmask/inputmask.date.extensions.js"></script>
<input type="input" id="expDate1"/>
<input type="input" id="expDate2"/>
<button type="button" onclick="getValuesFromInputs()">Get Values</button>
outputFormat: ddmm does what i needed, but it's not mentioned in documentation of this plugin.

how to store & read arbitrary url inside Input field

i have the following inside my asp.net mvc view:-
<input type="submit" id="addswitch" data-targeturl="#Url.Action("showSwitches","Rack")" class="btn btn-small btn-primary" value="Add">
the idea is that i need to store the realted URL insdie an arbitrary value which i name it data-targeturl.
then inside my script , which will fire when the user clicks on the above input field as follow:-
$('body').on("click", "#addserver,#addsd,#addfirewall,#addrouter,#addswitch", function () {
$("#showAddDialog").dialog({
title: "Add Exsisting " + dialogtitle,
width: 'auto', // overcomes width:'auto' and maxWidth bug
maxWidth: 600,
height: 'auto',
modal: true,
fluid: true, //new option
resizable: false
});
var URL = this.data-targeturl;
but currently i am getting the following error:-
ReferenceError: targeturl is not defined
var URL = this.data-targeturl;
You need to use .data() or dataset
var URL = $(this).data("targeturl");
//OR
//var URL = this.dataset.targeturl;
instead of
var URL = this.data-targeturl

Change date field value while submitting the form in django

I have a form
forms.py
class RegistrationForm(BaseRegistrationForm):
name = forms.CharField(label='Name of the Entrepreneur', max_length=120)
ename = forms.CharField(label='Name of the Enterprise', max_length=120)
sector = forms.CharField(label='Industry Sector', max_length=50, widget=forms.Select(choices=zip(SECTOR_CHOICES, SECTOR_CHOICES)))
subsector = forms.CharField(label='Sub-sector', max_length=50, widget=forms.Select(choices=zip(SUBSECTOR_CHOICES, SUBSECTOR_CHOICES)))
address1 = forms.CharField(label='Address Line 1', max_length=100)
address2 = forms.CharField(label='Address Line 2', max_length=100, required=False)
city = forms.CharField(label='City/Town', max_length=50)
state = forms.CharField(label='State', max_length=50)
country = forms.CharField(label='Country', max_length=50)
postal_code = forms.CharField(label='Pin Code', max_length=10, required=False)
estd = forms.DateField(label='Establishment Details')
contact = forms.IntegerField(label='Contact Number')
For the DateField variable I have written javascript
JavaScript Code:
<script type="text/javascript">
$(function() {
$('#id_estd').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
In the estd field it shows mm/yy (ex: 02/2014)
While submitting the form I should submit the value like mm/dd/yy. So How can I change the value while submitting the form??
No use with the javascript or something else. There is a snippet in django use it.
https://djangosnippets.org/snippets/1688/
Save the snippet code in some file called widgets.py and import the class name in your forms.py file and follow the below code:
import datetime
class myForm(forms.Form):
# ...
date = forms.DateField(
required=False,
widget=MonthYearWidget(years=xrange(1990,datetime.date.today().year+1))
)
Hope it works.
It is a better idea to use one format for humans, and another alternate one for processing. JQuery UI Datepicker allows an alternate field to be populated with a different format: http://jqueryui.com/datepicker/#alt-field
Basically rename your existing datepicker field, add a hidden input named estd with an id id_estd (default name and id Django would assign) and add the following lines while initializing your datepicker:
altField: "#id_estd",
altFormat: "mm/dd/yy"
Why use javascript to change the value? Just set the format in django.
class MyForm(Form):
# the default format is %Y-%m-%d
estd = forms.DateField(
widget=forms.widgets.DateInput(format="%m/%Y")
)
Docs for the DateInput widget; https://docs.djangoproject.com/en/1.7/ref/forms/widgets/#dateinput
Date/Time input format settings are detailed here; https://docs.djangoproject.com/en/1.7/ref/settings/#date-input-formats

adding element with duplicate id 'FileULoader' FileUploader

createContent : function(oController) {
var oFileUploader = new sap.ui.commons.FileUploader({
id: "FileULoader",
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
oFileUploader.attachUploadComplete(oController.doFileLoadComplete);
//var uploadBtn=new sap.ui.commons.buttons{this.creatId("upLoadFile"),}
var oMatrix = new sap.ui.commons.layout.MatrixLayout({
layoutFixed : true,
width : '400px',
columns : 1 });
var text = new sap.ui.commons.TextView({text:"Confirm that the data will be wiped out once you upload new data file."});
oMatrix.createRow(oFileUploader);
oMatrix.createRow(text);
var oDialog = new sap.ui.commons.Dialog({
title:"FileUpload",
resizable:false,
modal:true,
showCloseButton:true,
contentBorderDesign:"Box",
content:[
oMatrix
],
buttons:[
new sap.ui.commons.Button({text:"Confirm", tooltip:"Confirm",press:function(e){oController.doFileUpload();oDialog.close();}}),
new sap.ui.commons.Button({text:"Cancel", tooltip:"Cancle",press:function(e){oDialog.close();}}),
]
});
return oDialog;
i used in two views . when i call the fileUploader the error turns out。
i have to use the id to identify the fileloder controller. to get the input file information .
update:
_uploadCourse:function(){
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("courseUP",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
_uploadCourse : function() {
if (!this.dialogUploadFile) {
this.dialogUploadFile = sap.ui.jsfragment("certiUploadFile",
"adminView.dialogUploadFile", this);
}
this.dialogUploadFile.open();
},
this is how i use the fragment. but is still go wrong with thew same error;
#Allen Zhang
You mentioned you used the code in two views. You can't create a dialog twice with the same id of Fileupload control. Use different id for different views.
Updated:
Define id for your fragment usage:
<core:Fragment id="myFrag" fragmentName='my.frag' type='JS' />
Define fileupload id by calling createId:
var oFileUploader = new sap.ui.commons.FileUploader({
id: this.createId("FileULoader"),
//uploadUrl : "UploadFileServelet", // URL to submit the form to
name: "simpleUploader", // name of the input type=file element within the form
// uploadOnChange: true, // immediately upload the file after selection
buttonOnly: false,
buttonText: "Upload"
}).addStyleClass("downloadBtn");
Also see my answers about fragment usage and get control inside fragment.
Is an option that you do not use id for the file uploader control, and do it like this?
createContent : function(oController) {
this.oFileUploader = new sap.ui.commons.FileUploader({
To access it, you do
view.oFileUploader
where view is the javascript handle of one of your two views.
-D

Categories