I use an autocomplete to introduce the description of a product and get the ProductID and the Price with a javascript function:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#Description").change(function () {
$("#ProductID").val(Description_autocomplete_hidden.value);
$("#Price").load('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) });
});
});
});
</script>
The ProductID works fine, the action, e.g., “\Product\GetPrice\4” is correctly called but I am unable to assign the product price to the $(“#Price”).
The razor code:
<div class="row">
<div class="label">#Html.Label("Product")</div>
<div class="input">#Html.AutoComplete("Description","","Product","_Shared")</div>
</div>
<div id ="ProductID"></div>
<br />
<div class="row">
<div class="label">#Html.Label("Price")</div>
<div class="input">#Html.Editor("Price")</div>
</div>
The GetPrice() in the Product controller:
public string GetPrice(int id)
{
return unitOfWork.ProductRepository.GetByID(id).Pvp1.ToString();
}
#Carlos is Right! The .load() function tries to set the inner HTML which doesn't work for a text field. You need to set textBox's value to make it work. Simply replace your line $("#Price").load('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) });
});
With this:
$.get('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) },
function(result) {
//set the value here
$("#Price").val(result);
});
Look here:
http://api.jquery.com/load/
jQuery uses the browser's .innerHTML property to parse the retrieved
document and insert it into the current document.
According to what is written there, jQuery load method cannot be used to set value attribute of your input.
Please use this: http://api.jquery.com/jQuery.ajax/
It will give you more options. Also in success callback you can use returned value wherever you want, in your case to assign value to input:
$("#Price").val(data);
$(document).ready(function () {
$(function () {
$("#Description").change(function () {
$("#ProductID").val(Description_autocomplete_hidden.value);
$.ajax({
url: '#Url.Action("GetPrice", "Product")',
data: { id: parseInt($("#ProductID").val()) },
dataType: 'text',
type: 'get',
success: function (data) {
$("#Price").val(data); //
}
});
});
});
});
try this
Related
I have an ajax function that I have to click twice to work. I would like it to just work with one click. It was working before I added a click event that checks the text of what I'm clicking and uses it as part of the URL. My problem likely resides there. I need a fresh perspective on what might be wrong.
Jquery:
function ajaxShow(){
$('#formats a').click(function(e) {
var txt = $(e.target).text();
console.log(txt);
$.ajax({
url : "./enablereports/" + txt + ".html",
data: "html",
contentType:"application/x-javascript; charset:ISO-8859-1",
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
},
success : function (data) {
$("#rightDiv").html(data);
}
});
});
}
HTML:
<body>
<div id="wrapper">
<div id="enablestuff" class="yellowblock">
<h3 id="title" class="header">Enable Formats</h3>
</div>
<div id="formats" class="lightorangeblock">
ADDSTAMP<br>
SCLGLDNB<br>
SCLGLVNB<br>
</div>
</div>
<div id="rightWrap">
<div id="rightDiv">
</div>
</div>
</body>
It's cause you're binding the jQuery handler inside of your onclick function - just remove the entire onclick attribute and bind your handler outside the function.
$('#formats a').click(function(e) {
e.preventDefault();
var txt = $(e.target).text();
console.log(txt);
$.ajax({
url : "./enablereports/" + txt + ".html",
data: "html",
contentType:"application/x-javascript; charset:ISO-8859-1",
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
},
success : function (data) {
$("#rightDiv").html(data);
}
});
});
And the HTML
<div id="formats" class="lightorangeblock">
ADDSTAMP<br>
SCLGLDNB<br>
SCLGLVNB<br>
</div>
The problem is that each of the anchor elements has an inline event handler that points to ajaxShow, which then sets up the actual event handler for future clicks.
Instead, eliminate the inline handlers and just set up the actual handler without the ajaxShow wrapper.
I would also suggest that you don't use <a> elements since you aren't actually navigating anywhere, so the use of the element is semantically incorrect and will cause problems for people who rely on assistive technologies to use the web. Instead, since you want line breaks in between each "link", use <div> elements and just style them to look like links.
Lastly, you've used the name attribute on one of your last div elements, but name is only valid on form fields. You could give it an id if needed.
$('#formats div').click(function(e) {
var txt = $(e.target).text();
console.log(txt);
$.ajax({
url : "./enablereports/" + txt + ".html",
data: "html",
contentType:"application/x-javascript; charset:ISO-8859-1",
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
},
success : function (data) {
$("#rightDiv").html(data);
}
});
});
#formats div { text-decoration:underline; color:blue; cursor:pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<div id="enablestuff" class="yellowblock">
<h3 id="title" class="header">Enable Formats</h3>
</div>
<div id="formats" class="lightorangeblock">
<div>ADDSTAMP</div>
<div>SCLGLDNB</div>
<div>SCLGLVNB</div>
</div>
</div>
<div id="rightWrap">
<div id="rightDiv"></div>
</div>
I was able to get this working by adding ajaxShow(); into a $(document).ready(function ().
Dirty, but it works.
This is my html code
<div data-percent="" ></div>
This is my javascript
function retrieveProgressbar(){
$.ajax({
type:"post",
url:"retrieveprogressbar.php",
data:"progressbar",
success:function(data){
$(this).data("percent").html(data);
}
});
}
retrieveProgressbar();
I need the value retrieved by ajax to be displayed in the data-percent="". I am not sure how to do that. I have another javascript that needs to use this value to execute.
Need to use .attr() method.
<div data-percent="" id="datadiv"></div>
<script>
function retrieveProgressbar() {
$.ajax({
type: "post",
url: "retrieveprogressbar.php",
data: "progressbar",
success: function (data) {
//$("#datadiv").attr("data-percent", data);
// OR
$(this).attr("data-percent", data);
}
});
}
retrieveProgressbar();
</script>
HTML:
<div data-percent=""></div>
The proper way to assign data on jquery is
var new_data_value = "I will be the new value.";
$("div").data("percent",new_data_value);
The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
You can retrieve the data by:
var value = $( "div" ).data( "percent" );
.attr() on the other hand set/get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
It does not attach data of any type to DOM elements.
$("div").attr("data-percent",data_value);
Sources:
https://api.jquery.com/data/
http://api.jquery.com/attr/
Yep, you can use the .attr( function instead.
$(this).attr("data-percent", your_value);
What I want is simple but I don't know if it's possible.
I have a Kendo Mobile ListView as below:
e.view.element.find("#list-serviceorders").kendoMobileListView({
dataSource: ds,
pullToRefresh: true,
template: $("#list-serviceorders-template").html()
});
And I want to send to the template some values to access on it. My view with the template is this:
<div data-role="view" data-before-show="GAPCP.viewBeforeShow" id="serviceorders" data-layout="main-item-list">
<ul id="list-serviceorders"></ul>
</div>
<script id="list-serviceorders-template" type="text/x-kendo-template" data-teste="teste">
<a href="views/entries.html?id=#: CodOs #">OS: #: CodOs #<br />
#: parameter.Divi1 #: #: CodDivi1 #/#: parameter.Divi2 #: #: CodDivi2 #</a>
</script>
Where you can read parameter.Divi1 and parameter.Divi2 are the places where I want to display those values. They're are not in the Data Source like the others values.
I don't want to create global variable 'cause I don't want to mess with my code and I can't use a function for that purpose because those values come from the database and it will execute a query for each list item iteration.
Any suggestion of how do that?
What I'm proposing is adding this information to the model in the controller. You can do it in DataSource.schema.parse or in requestEnd, even in a dataBound event if the widget accepts it.
When the data is received you iterate through the model and fills the remaining data not received from the server.
Example: Using parse
var ds = new kendo.data.DataSource({
transport: {
read: {
url : ...
}
},
schema : {
model: {
CodOs : { type: "number" },
CodDivi1: { type: "string" },
CodDivi2: { type: "string" }
},
parse: function (data) {
$.each(data, function (idx, elem) {
// Extend original elem
elem.parameter = {
Divi1: elem.CodDivi1.toUpperCase(),
Divi2: elem.CodDivi2.toLowerCase()
}
});
return data;
}
}
});
Where I compute parameter inside the parse function and set parameter.Divi1 to CodDivi1 in upper-case and parameter.Divi2 to CodDivi2 in lowercase.
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(),
)};
I have the following html code:
<div id="result1" class="result">
... some html ...
... link
... some html ...
</div>
<div id="result2" class="result">
... some html ...
... link
... some html ...
</div>
<div id="result3" class="result">
</div>
<div id="result4" class="result">
</div>
The goal is to update the content of the next div when I click on the link. So for instance, when I click on a link in #result2, the content of #result3 will be updated.
Here is the javascript function:
<script>
function updateNext(elem, uri) {
$.ajax({
url: uri,
success: function(data) {
elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
}
</script>
However, when I use the link, elem is set as the window, not the link itself.
The content of the div is generated by a server which should not know the position of the div in which the code he is generating will be.
I also tried with a
<a href="javascript:" onclick="updateNext(...
with no other result...
any idea ? :-)
Thanks,
Arnaud.
this returns the window when used in href, but here it returns the actual link:
... link
Don't forget to use the jQuery $ in:
$(elem).closest('.result').nextAll().html('');
$(elem).closest('.result').next().html(data);
Why do you use inline scripts when you alrady are using jQuery?
I've setup a Fiddle for you which does what you want: http://jsfiddle.net/eLA3P/1/
The example code:
$('div.result a').click(function() {
$(this).closest('div.result').next().html('test');
return false;
});
First, you must remove those href="javascript:..." attributes. Please never use them again, they are evil.
Then, bind a click handler via jQuery, which you are alredy using:
// since you dynamically self-update the a elements, use "live()":
$("div.result a").live("click", function () {
var $myDiv = $(this).closest("div.result");
$.ajax({
url: "/build/some/url/with/" + $myDiv.attr("id"),
success: function(data) {
$myDiv.next("div.result").html(data);
}
});
return false;
});
Done.
Try to use jQuery to bind the event instead putting a javascript link in the href.
<div id="result1" class="result">
link
</div>
$('.resultLink').click(function(){
var elem = $(this);
$.ajax({
url: uri,
success: function(data) {
elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
});
You should do it like this:
http://jsfiddle.net/hJhC7/
The inline JavaScript is gone, and the href is being used to store the "uri", whatever that might be. I'm assuming it's different for each link.
The //remove this lines are just to make $.ajax work with jsFiddle.
$('.update').click(function(e) {
e.preventDefault();
var elem = $(this);
$.ajax({
type: 'post', //remove this
data: {html: Math.random() }, //remove this
url: $(this).attr('href'),
success: function(data) {
//not sure why you're doing this
//elem.closest('.result').nextAll().html('');
elem.closest('.result').next().html(data);
}
});
});
with this HTML:
<div id="result1" class="result">
link
</div>
<div id="result2" class="result">
link
</div>
<div id="result3" class="result">
link
</div>