I need to print inside a span tag ("estimation2") the result of a calculation (for now, just a simple sum of the two input boxes "SHm2" and "STm2"). I'm using an AJAX call to perform that task. It seems to work perfectly until the alert, which shows the correct result, but for some reasons I can't write that result in my html form. I've been looking around and tried several things, yet none of them worked. For instance I've tried using the write method but it didn't work or stuff like $("#estimation2").html(estimation); or
document.getElementById("estimation2").innerHTML = estimation;
The only way I managed to get it written was by using window.onload, but this generates the calculation when the page loads, and I don't want that. I only want the AJAX code to be triggered when I click on my button.
Also, just for info, the calculation is made in my django view, even though I don't think it's relevant here as it looks to work properly. I'm really lost here, could you please help?
Here is my html code and the AJAX script:
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
<script type="text/javascript">
function calculate () {
var SHm2 = $('#SHm2').val();
var STm2 = $('#STm2').val();
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
'SHm2':SHm2,
'STm2':STm2,
estimation: 'estimation',
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
</script>
so what you wanna do is run the JS after the HTML document has loaded, and as mentioned in the comment section you need to add type="button" to estimation button
HTML
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" type="button" onclick="calculate()" >Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
JS
$(document).ready(function() {
function calculate() {
var SHm2 = $("#SHm2").val();
var STm2 = $("#STm2").val();
$.ajax({
url: "/myApp/templates/homepage/",
type: "POST",
data: {
SHm2: SHm2,
STm2: STm2,
estimation: "estimation"
},
success: function(estimation) {
console.log(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
});
Related
I have a form that I'm trying to submit and process with javascript using the code outlined below:
Form:
<form id="my_form_id" method="POST" action="my_processor_script.php">
<input type="text" id="form_id_1" name="form_field_1">
<input type="text" id="form_id_2" name="form_field_2">
<input type="text" id="form_id_3" name="form_field_3">
<input class="cbp-mc-submit" type="submit" name="save_settings_button" id="save_settings" value="Save Settings" />
</form>
Script:
<script>
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
alert("Form Processed");
},'json');
return false;
});
});
</script>
Processor:
<?php if (isset($post_data['save_settings_button']))
{
$form_field_1 = $_POST['form_field_1'];}
$form_field_2 = $_POST['form_field_2'];}
$form_field_3 = $_POST['form_field_3'];}
}
?>
Once I have the variables I then store them in a database.
The form works great if I just post from the form to the processor script without using the javascript however when I use the javascript nothing happens. I'm obviously doing something very wrong but can work this out at all as I cant see what is being received by the processor. Has anyone got any ideas on how i can get this to work?
It would also be great if I can return the data so that I can see what is being passed to the script as this would help me to debug any issues?
So I have my form pretty much done and I need to calculate the total values of input fields after AJAX fills them based on user selects. I have tried and tried and tried to find a solution but nothing is working... ugh.
Here's the html for the input fields that need to be calculated and the field that the sum needs to be returned to:
<input type="text" class="form-control prices" id="lt1total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control prices" id="lt2total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control prices" id="lt3total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control disabled" id="lttotal" placeholder="Amount" value="" readonly>
Here is the AJAX request (there is one for each they all work correctly):
$.ajax({
method: 'GET',
url: 'example.url',
data: {
lt1datetype: lt1datetype,
lt1tt: lt1tt,
}
}).done(function(result) {
console.log('', result);
$('#lt1total').val(result);
});
And this is the only jquery function that I have gotten to even put a value for #lttotal :
$(document).ready(function() {
var sum = 0;
$(".prices").each(function(){
sum += Number($(this).val());
});
$("#lttotal").val(sum);
});
It only outputs 0 for the amount. The values that AJAX is getting are like this 123.00 or 1234.00 I'm stuck and aggravated. Any help or direction would be greatly appreciated.
Use $.when to run the calculations code after all the requests have been completed.
var request1 = $.ajax({
method: 'GET',
url: 'example.url',
data: {...}
}).done(function(result) {
console.log('', result);
$('#lt1total').val(result);
});
var request2 = $.ajax({
method: 'GET',
url: 'example.url',
data: {...}
}
}).done(function(result) {
console.log('', result);
$('#lt2total').val(result);
});
$.when(request1, request2....., requestn).done(function(){
// set totals here instead of on page load
})
How to call function xxx when input type text id="username" change value ?
first, when you fill data into
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
Then data in
<input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
will change value.
OK, when input name="thingy" change i want to call function xxx , i try this code but not work.
How can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function updateInput(ish){
document.getElementById("username").value = ish;
}
</script>
<form id="main_fid">
input1 : <input type="text" name="thingy" onkeypress="updateInput(this.value)" onkeyup="updateInput(this.value)" />
<span id="mySpan"></span>
<input type="submit" value="OK"/>
</form>
<script>
function xxx() {
$.ajax
(
{
url: 'other.php',
type: 'POST',
data: $('#username_send_value_fid').serialize(),
cache: false,
success: function (data) {
$('#mySpan').show();
$('#mySpan').html(data);
}
}
)
}
</script>
<br>
<form id="username_send_value_fid">
input2 : <input type="text" name="username" id="username" onchange="xxx()" readonly/>
</form>
I think calling xxx() on "onchange" event or inside updateInput(ish) will give the same effect.
Try
function updateInput(ish){
document.getElementById("username").value = ish;
xxx();
}
$("#username").on( "change", handler )
or in short form
$("#username").change( handler )
And get rid of the inline onchange attribute. You will also need to wrap the code in a ready function:
$(document).ready(function(){
$("#username").change( handler )
});
http://api.jquery.com/change/
Added after reading the question a bit more carefully:
If you want to link your input name="thingy" to username you can do something like this:
$('input[name="thingy"]').change(function(){
$("#username").val( $(this).val() ).trigger('change');
});
This will update the value of username and then trigger a change event as if the user had typed in the input.
However if what you are trying to accomplish is something like validating the uniqueness of an input the is no reason to jump though so many hoops - just call your ajax handler straight from the username change event.
I have this form:
<form>
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
</form>
And what I'm doing with JQuery is to check if the username that was written is avalible. This is the JQuery code:
$('#checkuser').click(function (){
$(this).change(function () {
$.ajax( {
url: '/check',
type: 'POST',
cache: false,
data: { checkuser: $(this).val() },
dataType: "json",
complete: function() {
},
success: function(data) {
var check = JSON.stringify(data.aval);
if (check == "false") {
$('<p>Not available.</p>').insertAfter('#checkuser');
}
else {
$('<p> Available!</p>').insertAfter('#checkuser');
}
},
error: function() {
console.log('process error');
}
});
});
});
The problem is: if the user is not available, the user has to rewrite the username and when jQuery recheck if is available, instead of rewrite the content of <p>, JQuery create another <p>next to the old <p>, ergo, this is the result: Not available.Available!, instead write only one of them. How can I resolve this?
To solve this I would add a blank <p></p> tag after the input and update this tag when needed.
<form>
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
<p></p>
</form>
$('form p').text('Available!');
insertAfter will append new html context to the div. instead create another div after the checkuser div and replace the html inside:
<input id="checkuser" type="text" name="user" placeholder="Your username"/>
<div id="msg"></div>
and then just:
$('#msg').text('your text if available or not here');
The insertAfter() method is working as designed: it finds the element (#checkuser in this case) and appends a new paragraph after it.
You probably need to create a DIV or SPAN element after your INPUT tag like this:
<span id="checkuser-validation"></span>
Then adapt your JavaScript code to look like this:
if (check == "false") {
$('#checkuser-validation').Empty();
$('#checkuser-validation').Html('Not Available');
}
... and so on. Hope that helps :)
This piece of code does not execute the code block inside the callback function for result():
var cityURL = '/myURL/path';
$('#city').autocomplete(cityURL, {
cachelength:0
}).result(function(event, data){
if(data){
$('#city_id').val(data[1]);
$('#state_id').val(data[3]);
$('#state').val(data[2]);
}
});
the value of input#city_id and input#state_id does not change, but the value for #state does change. Both are hidden input right next to their field:
<input type="text" id="city" name="city"/>
<input type="hidden" id="city_id" name="city_id" />
<input type="text" id="state" name="state"/>
<input type="hidden" id="state_id" name="state_id" />
however, if I put an alert, the values change:
$('#city').autocomplete(cityURL, {
cachelength:0
}).result(function(event, data){
if(data){
alert(data[1]);
$('input#city_id').attr('value',data[1]);
$('input#state_id').val(data[3]);
$('input#state').val(data[2]);
}
});
why is this?
EDIT: Scratch that, the values do not change even with an alert:
As I suspected in my comment, it's just Firebug that's not updating properly. You shouldn't trust the input value attributes it shows as they're often out of date.
A reliable way to check input values is to just use JS and enter something like $("#foo").val(); in the console.