I can't get Html.TextBoxFor value with JavaScript - 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
});

Related

How to pass selected value as extra parameter to ajax call

my coding part
$("#demo-input").tokenInput("data/autosuggest-search-city.php",
{
searchDelay: 2000,
minChars: 3,
tokenLimit: 10
});
I want to send the selected values as extra parameter to "data/autosuggest-search-city.php".
For example,
Initially I search and select one value from list
then again searching, this time I want to send the 1st selected value to server.
How to do this?
TokenInput plugin doesn't support that natively.
You can however make a simple workaround to update "AJAX url" whenever a token is added or removed from selection.
Use onAdd and onDelete callbacks to trigger "AJAX url" changes;
Get selected tokens using selector.tokenInput("get") method;
Set the new "AJAX url" by updating .data("settings").url of the element;
// cache the original url:
var token_url = "data/autosuggest-search-city.php";
$("#demo-input").tokenInput(token_url, {
searchDelay : 2000,
minChars : 3,
tokenLimit : 10,
onAdd : function(){
urlChange.call(this);
},
onDelete : function(){
urlChange.call(this);
}
});
function urlChange(){
var tokens = '', token_list = $(this).tokenInput("get");
// proceed if any token/s are selected:
if(token_list.length){
// loop through the selected tokens (if more than one is selected)
$.each(token_list, function(i, token){
// use token "id" (or "name" if you wish) and separate them with comma:
tokens += token.id + ',';
});
// update url:
$(this).data("settings").url = token_url + '?selected_tokens='+tokens.replace(/,+$/,'');
}else{
// leave original url if no tokens are selected:
$(this).data("settings").url = token_url;
}
};

How to add content via ajax using the popover boostrap

I tried to view different sources and also looked into the forums posting similar question, but it didnt quite help me with the issue that im facing.
I have a text input filed to which I'm adding a popover to show similar a list of names in the database. The inout field checks for validation, to see if the name entered is unique, if not it displays similar names available in the database that could be re-used.
here is the popover snippet:
$("#account_name_create").popover({
title: 'Twitter Bootstrap Popover',
content: function (process) {
this.accountCollection = new ipiadmin.collections.AccountCollection();
var newName = $("#new-account-form #account_name_create").val();
var userFilter = "accountName~'" + newName + "'";
this.accountCollection.fetch({
data: { "f": userFilter,
"sortby": null,
"type":"ipi",
"pageno":0,
"pagesize":2,
"reversesort" : true
},
cache: false,
success: function(model, response, options) {
var states = [];
map = {};
$.each(model.aDataSet, function (i, state) {
map[state.accountName] = state;
states.push(state.accountName);
});
process(states); //gives an error saying 'undefined is not a function (says process is undefined)'
},
error: function(model, response, options) {
console.log('error');
}
});
},
});
here is the html:
<input type="text" id="account_name_create" name="account_name" class="" size="40" />
I'm not sure how why it says 'process' as undefined. Also not sure if this would be the correct way of displaying the data in the popover.
Any ideas??
Thanks!
process doesn't have scope in the success function, only in the content function. If you want to call the process function from within the success function, you could define it somewhere outside of the jQuery call.

Remove Quotes from json_encoded string value

I am working on a project to implement jTable into a PHP framwework class.
It is going quite well. Now I am stuck at a problem where I would like to be able to make custom input fieds on the edit dialog.
We are already using the select2 plugin, now I want to implement this on the edit dialogs of jTable. As far as I understood it is possible to add custom fields to the edit dialog like this:
Name: {
title: 'Name',
width: '20%',
input: function (data) {
if (data.record) {
return '<input type="text" name="Name" style="width:200px" value="' + data.record.Name + '" />';
} else {
return '<input type="text" name="Name" style="width:200px" value="enter your name here" />';
}
}
}
Notice the code above is in JavaScript.
Basically what I do is that I build this javascript in php array and via json_encode I send it to the client.
My problem here is that when I do
$column_array['name']['input'] = function (data) {if ....and so on}
I get on the javascript side
input: "function (data) {... so on"
Please notice the double quotes, it is a string and not a function anymore.
What I would need is to remove this 2 double quotes after the input. (well that's my idea so far)
OR if any one got some experience with jTable] and knows a better way to implement custom fields like select2, chosen, jQuery multiselect, elfinder and stuff like that.
I can give tomorrow some code if needed, cause I am not at work anymore today.
Based on this concept:
// Create a function that takes two arguments and returns the sum of those arguments
var fun = new Function("a", "b", "return a + b");
// Call the function
fun(2, 6);
Output: 8
you may change your JSON a bit in to
Name: {
title: 'Name',
width: '20%',
input: { name: "input",
param: "data",
body: "if (data.record) {
return '<input type=\".... "
}
....
then you may define a function and execute it
var d = new Function(Name.input.name, Name.input.param, Name.input.body);
d(otherdata);
this will omit the awful eval(...) stuff. Caveat: it's still not a method of the given object.

How can I remove AutoNumeric formatting before submitting form?

I'm using the jQuery plugin AutoNumeric but when I submit a form, I can't remove the formatting on the fields before POST.
I tried to use $('input').autonumeric('destroy') (and other methods) but it leaves the formatting on the text fields.
How can I POST the unformatted data to the server? How can I remove the formatting? Is there an attribute for it in the initial config, or somewhere else?
I don't want to send the serialized form data to the server (with AJAX). I want to submit the form with the unformatted data like a normal HTML action.
I wrote a better, somewhat more general hack for this in jQuery
$('form').submit(function(){
var form = $(this);
$('input').each(function(i){
var self = $(this);
try{
var v = self.autoNumeric('get');
self.autoNumeric('destroy');
self.val(v);
}catch(err){
console.log("Not an autonumeric field: " + self.attr("name"));
}
});
return true;
});
This code cleans form w/ error handling on not autoNumeric values.
With newer versions you can use the option:
unformatOnSubmit: true
Inside data callback you must call getString method like below:
$("#form").autosave({
callbacks: {
data: function (options, $inputs, formData) {
return $("#form").autoNumeric("getString");
},
trigger: {
method: "interval",
options: {
interval: 300000
}
},
save: {
method: "ajax",
options: {
type: "POST",
url: '/Action',
success: function (data) {
}
}
}
}
});
Use the get method.
'get' | returns un-formatted object via ".val()" or
".text()" | $(selector).autoNumeric('get');
<script type="text/javascript">
function clean(form) {
form["my_field"].value = "15";
}
</script>
<form method="post" action="submit.php" onsubmit="clean(this)">
<input type="text" name="my_field">
</form>
This will always submit "15". Now get creative :)
Mirrored raw value:
<form method="post" action="submit.php">
<input type="text" name="my_field_formatted" id="my_field_formatted">
<input type="hidden" name="my_field" id="my_field_raw">
</form>
<script type="text/javascript">
$("#my_field_formatted").change(function () {
$("#my_field").val($("#my_field_formatted").autoNumeric("get"));
});
</script>
The in submit.php ignore the value for my_field_formatted and use my_field instead.
You can always use php str_replace function
str_repalce(',','',$stringYouWantToFix);
it will remove all commas. you can cast the value to integer if necessary.
$("input.classname").autoNumeric('init',{your_options});
$('form').submit(function(){
var form=$(this);
$('form').find('input.classname').each(function(){
var self=$(this);
var v = self.autoNumeric('get');
// self.autoNumeric('destroy');
self.val(v);
});
});
classname is your input class that will init as autoNumeric
Sorry for bad English ^_^
There is another solution for integration which doesn't interfere with your client-side validation nor causes the flash of unformatted text before submission:
var input = $(selector);
var proxy = document.createElement('input');
proxy.type = 'text';
input.parent().prepend(proxy);
proxy = $(proxy);
proxy.autoNumeric('init', options);
proxy.autoNumeric('set', input.val())''
proxy.change(function () {
input.val(proxy.autoNumeric('get'));
});
You could use the getArray method (http://www.decorplanit.com/plugin/#getArrayAnchor).
$.post("myScript.php", $('#mainFormData').autoNumeric('getArray'));
I came up with this, seems like the cleanest way.
I know it's a pretty old thread but it's the first Google match, so i'll leave it here for future
$('form').on('submit', function(){
$('.curr').each(function(){
$(this).autoNumeric('update', {aSign: '', aDec: '.', aSep: ''});;
});
});
Solution for AJAX Use Case
I believe this is better answer among all of those mentioned above, as the person who wrote the question is doing AJAX. So
kindly upvote it, so that people find it easily. For non-ajax form submission, answer given by #jpaoletti is the right one.
// Get a reference to any one of the AutoNumeric element on the form to be submitted
var element = AutoNumeric.getAutoNumericElement('#modifyQuantity');
// Unformat ALL elements belonging to the form that includes above element
// Note: Do not perform following in AJAX beforeSend event, it will not work
element.formUnformat();
$.ajax({
url: "<url>",
data : {
ids : ids,
orderType : $('#modifyOrderType').val(),
// Directly use val() for all AutoNumeric fields (they will be unformatted now)
quantity : $('#modifyQuantity').val(),
price : $('#modifyPrice').val(),
triggerPrice : $('#modifyTriggerPrice').val()
}
})
.always(function( ) {
// When AJAX is finished, re-apply formatting
element.formReformat();
});
autoNumeric("getArray") no longer works.
unformatOnSubmit: true does not seem to work when form is submitted with Ajax using serializeArray().
Instead use formArrayFormatted to get the equivalent serialised data of form.serializeArray()
Just get any AutoNumeric initialised element from the form and call the method. It will serialise the entire form including non-autonumeric inputs.
$.ajax({
type: "POST",
url: url,
data: AutoNumeric.getAutoNumericElement("#anyElement").formArrayFormatted(),
)};

.uploadifySettings not working as expected

I'm using uploadify and the function to change the settings doesn't seem to be working.
I'm basing my code from the following example:
#(‘#someID’).uploadifySettings(’scriptData’, {‘name’ : some.val()});
So here's what I'm doing:
// INITIALIZATION
$("#"+elementId).uploadify({
// other data
"scriptData": {
"token": token
}
});
Later on I want to update the scriptData:
$("#"+elementId).uploadifySettings("scriptData",{"token": "pleasework"});
... but this is not working, it's still using the scriptData set during the initialization.
What am I doing wrong?
UPDATE: I need to do this because I need to handle tokens. Here's the worflow:
1- Get a token
2- Init uploadify with this token
3- Upload a file
4- Get another token asynchronously
5- Add the token to the already initialized uploadify (bugged)
6- Go to 3
I tried doing this on initialization:
"scriptData": {
"token": $(".token").val()
}
... and update .token on step 4
This doesn't work either
UPDATE 2: Also if I do:
"scriptData": {
"token": getAToken()
}
with
function getAToken(){
alert("abcd");
return "sometoken";
}
... I can see that the function getAToken only gets called once (only 1 alert)
This works for me, adding a unique nonce to every file upload
function setScriptData(){
$("#product_attachment").uploadifySettings("scriptData",
{
'_fsg_distro_session' : '<%= u cookies["_fsg_distro_session"] %>',
'authenticity_token' : '<%= u form_authenticity_token if protect_against_forgery? %>',
'nonce' : new Date().getTime() + "<%= #current_user.id %>"
}
);
console.debug($("#product_attachment").uploadifySettings("scriptData"));
}
$("#product_attachment").uploadify({
uploader : '/uploadify/uploadify.swf',
script : '/products/temp_upload',
cancelImg : '/uploadify/cancel.png',
fileDataName : 'asset[temp_file]',
'queueID' : 'fileQueue',
onComplete : function(event, ID, fileObj, response, data){ fileOnCompleteHandler(event,data); },
onSelect : setScriptData,
auto : true,
multi : false,
buttonImg : '/images/attach.png',
fileNameMaxLength : 30
});
I am using the latest Uploadify (2.1.0) and JQuery (1.4.1)
I've looked at the source and I notice that uploadifySettings() has an optional, undocumented (it does not appear here) third parameter. Apparently if you set it to true as in $("#"+elementId).uploadifySettings("scriptData",{"token": "pleasework"}, true); it will clobber the existing settings for scriptData and perhaps that will have some impact.
But based on the source I can't exactly tell what impact a change in settings necessarily has.
uploadifySettings:function(settingName, settingValue, resetObject) {
var returnValue = false;
jQuery(this).each(function() {
if (settingName == 'scriptData' && settingValue != null) {
if (resetObject) {
var scriptData = settingValue;
} else {
var scriptData = jQuery.extend(settings.scriptData, settingValue);
}
var scriptDataString = '';
for (var name in scriptData) {
scriptDataString += '&' + name + '=' + escape(scriptData[name]);
}
settingValue = scriptDataString.substr(1);
}
returnValue = document.getElementById(jQuery(this).attr('id') + 'Uploader').updateSettings(settingName, settingValue);
});
That code is from version 2.1.0.
Is there a way to potentially decide on the settings before initialization?
Also, I found this existing SO question: Uploadify updateSettings problems.
Try defining the function in-line at initialization? IE:
"scriptData": {
"token": function() { return $("#token").val(); }
}
I'm not sure why this would be different than some of your other solutions though.
FOUND THE SOLUTION:
I had a mistake in the "onSelect" function. I had misspelled the element id name, instead file_upload I had fileUpload and thats why it didnt update the scriptData parameter. I know its a silly mistake but easy to be made. Here is the whole onSelect function:
'onSelect' : function(event,data) {
$("#file_upload").uploadifySettings('scriptData', {'id' : $('#name_of_the_element').val()}
);
}
So check if this is the problem

Categories