I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();
This code is calculating sum of rendered rows not the new created rows
$(document).ready(function(){
$('.datepicker').datepicker();
var $inst = $('.inst_amount');
$inst_form = $('.inst_form');
$total_amount = $('#total_amount');
$total_price = $('#total_price');
total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
$(document).on('blur','.inst_amount', function(){
var total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
console.log(total);
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
});
});
move var $inst = $('.inst_amount'); to where you use it:
var total = 0,$inst = $('.inst_amount'); - actually don't even. See my code
Use commas to separate vars
DRY - Don't Repeat Yourself
give the class correctly and add the field to a container.
function sumIt() {
var total = 0, val;
$('.inst_amount').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('#total_price').html(Math.round(total));
$('#total_amount').val(Math.round(total));
}
$(function() {
// $('.datepicker').datepicker(); // not needed for this test
$("#add").on("click", function() {
$("#container input").last()
.before($("<input />").prop("class","inst_amount").val(0))
.before("<br/>");
sumIt();
});
$(document).on('input', '.inst_amount', sumIt);
sumIt() // run when loading
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
<input type="text" class="inst_amount" value="4" /><br/>
<input type="text" class="inst_amount" value="" /><br/>
<input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span>
This code will only calculate total of all the rows which were available when page was loaded. You need to call the same code to make the total again when you are adding a new row. Basically on click of add row you need to re-calculate.
Put these code outside the $(document).ready
$(document).on('blur','.inst_amount', function(){
var total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
console.log(total);
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
});
because at a time of $(document).ready , new row is not added
Related
I'm using phpGrid library based on jqgrid and I have this function:
onSelectRow: function(id){
var grid = $(this);
if(id && id!==lastSel){
grid.restoreRow(lastSel);
lastSel = id;
var rd = jQuery("#php_temp_det_vo").jqGrid("getCell", id, "status");
if(rd == 1){
alert("Data cannot be changed");
$("#'. $this->jq_gridName .'").trigger("reloadGrid");
}
else{
$(function(){ $("#begin_km").val("123"); });
}
}
grid.editRow(id, true,oneditfunc,"","","",aftersavefunc);
}
I need to dynamically give default value to one column called begin_km depends on some function that I will generate later. I wanted to try $(function(){ $("#begin_km").val("123"); }); first without that function I mentioned, but it doesn't work whereas it works on a simple html page:
the ajax
$(function(){ $("#aaa").val("123"); });
the html
<input type="text" id="aaa" />
What is the problem and how can I fix it?
EDITED:
Here's a slice of my jqgrid column model *refering to begin_id as column ID
<script type="text/javascript">
...
colModel:[{"name":"id","id":"id","index":"id","hidden":true},
{"name":"begin_km","id":"begin_km","index":"begin_km","hidden":false,"align":"right"},
...
</script>
You can set the cell values using setCell
onSelectRow: function(id){
var grid = $(this);
if(id && id!==lastSel){
grid.restoreRow(lastSel);
lastSel = id;
var rd = jQuery("#php_temp_det_vo").jqGrid("getCell", id, "status");
if(rd == 1){
alert("Data cannot be changed");
$("#'. $this->jq_gridName .'").trigger("reloadGrid");
}
else{
grid.jqGrid('setCell', id, 'begin_km', "123");
}
}
grid.editRow(id, true,oneditfunc,"","","",aftersavefunc);
}
I am having an issue where I am trying to pass a submit buttons values along with the form to ajax but for some reason the only value that passes no matter which button I push is the first button. There is more to the form but I am just showing the buttons.
<form>
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Delete" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Save" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Finalize" />
</form>
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var invoice_temp_id = $('#invoice_temp_id').attr('value');
var man_part_number = $('#man_part_number').attr('value');
var customer = $('#customer').attr('value');
var date = $('#date').attr('value');
var shipdate = $('#shipdate').attr('value');
var shipvia = $('#shipvia').attr('value');
var ponumber = $('#ponumber').attr('value');
var rep = $('#rep').attr('value');
var invoicenotes = $('#invoicenotes').attr('value');
var serial_number = $('#serial_number').attr('value');
var skid = $('#skid').attr('value');
var finalize_invoice = $('#finalize_invoice').attr('value');
$.ajax({
type: "POST",
url: "includes/createfinalinvoice.php?",
data: "invoice_temp_id="+ invoice_temp_id+
"&man_part_number="+ man_part_number+
"&customer="+ customer+
"&date="+ date+
"&shipdate="+ shipdate+
"&shipvia="+ shipvia+
"&ponumber="+ ponumber+
"&rep="+ rep+
"&invoicenotes="+ invoicenotes+
"&serial_number="+ serial_number+
"&skid="+ skid+
"&finalize_invoice="+ finalize_invoice+
$( this ).serialize(),
success: function(data){
if (data == 1) {
var thiserror = 'You may not have any blank fields, please make sure there is a serial number in each field';
alert(thiserror);
}
if (data == 2) {
var thiserror = 'Your serial number(s) do not match with the Manufacture Part Numbers, please double check your list';
alert(thiserror);
}
if (data == 3) {
var thiserror = 'Some of your serial numbers are not located in the database, please make sure you entered the correct serial number';
alert(thiserror);
}
if (data == 4) {
var thiserror = 'This item has already been sold to another customer. Please report this to administration';
alert(thiserror);
}
if (data == 5) {
var thiserror = 'Everything went OK, you may continue and view the processed invoice';
alert(thiserror);
}
if (data == 6) {
var thiserror = 'There are no default prices setup for this customer matching the Manufacture Part Numbers. Please check and make sure they all exist before processing this list';
alert(thiserror);
}
if (data == 7) {
window.location = ('/admin/?mmcustomers=1&viewinvoice=1');
}
}
});
return false;
});
});
You have three submit buttons with identical ids of finalize_invoice. ids must be unique however. This is the reason, jquery selects the first button only, no matter which one was clicked. If you want to send the request with the clicked button, bind a function to the button's click event
$('form#submit input[type="submit"]').click(function() {
...
var finalize_invoice = $(this).attr('value');
$.ajax(...);
...
return false;
}
As #thaJeztah suggested, suppressing the submit event on form
$('form#submit').submit(function() {
return false;
});
<form>
<input type="button" name"del_button" id="del_btn" value="Delete" />
<input type="button" name"save_button" id="save_btn" value="Save" />
<input type="button" name"finalize_button" id="finalize_btn" value="Finalize" />
</form>
<script>
$(document).ready(function(){
var clicked_btn = '';
$('form').submit(function(){ return false; });
$('form input[type=button]').click(function(){
clicked_btn = $(this).attr('id');
yourSubmitFunction(clicked_btn);
return false;
});
}
</script>
I am currently working with a wmd editor and jQuery-UI tabs. I have created an ajax/js function that will submit (when next button is clicked) the wmd-preview value and then php echo the result in tab 2. The problem is that I am not getting any results displayed. I am not looking for the textarea value but the div #wmd-preview value. How can I display the value of the div wmd-preview through my ajax/function?
JS
<script>
$(function () {
var $tabs = $('#tabs').tabs({
disabled: [0, 1],
select: function () {
$.ajax({
type: "POST",
url: "post_tabs.php",
data: {
"wmd": $("#wmd-preview").val(),
},
success: function (result) {
$("#tab-2").html(result);
}
});
}
});
$(".ui-tabs-panel").each(function (i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab').click(function () {
var currentTab = $('#tabs').tabs('option', 'selected');
if (
(
currentTab == 0 && /*(B)*/
$.trim($('#wmd-input').val()).length > 0
)
) {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
} else {
switch (currentTab) {
case 0:
alert('Please fill out all the required fields.', 'Alert Dialog');
break;
}
}
console.log("preventing default");
return false;
});
$('.prev-tab').click(function () {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
return false;
});
});
</script>
PHP
<?
if (isset($_POST['wmd'])){
$wmd = $_POST['wmd'];
echo ('<div id="text_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$wmd.'</span></div>');
}
?>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input" cols="92" rows="15" tabindex="6"></textarea>
<div id="wmd-preview"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>
PHP code should start with <?php , yours start with <? which is incorrect.
When you see PHP code presented as text - it should tell you it is not running, this is why you keep getting output like '.$wmd.''); } ?> instead of real PHP echo output.
The other comment still stands as well - you should either use $("#wmd-preview").html() or $("#wmd-input").val() but you cannot use val on divs, it does not work.
In this scenario $("#wmd-input").val() is the better choice just because this is the reason input fields exist - to get input.
Let me know if there are more questions I can help with.
I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.
One page I have articles with prices. I would like to do administration. When I am administrator and I would click on price input field text would show.
My code for this:
$('#priceBig').click(function() {
var originalelement = this;
var dishID = this.id;
var currentText = $.trim($(this).text())
$(this).hide().before('<input class="input" id="'+dishID+'" style="padding:3px; text-align:left; font-size:17px; width:50px;" type="text" value="'+currentText+'"/>');
$('.input').live('change', function() {
var picaID = this.id;
var price = $(this).val();
var thisparam = this;
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : picaID, price:price},
function(data) {
$(thisparam).remove();
$(originalelement).text(price).fadeIn(1000);
},'text');
});
});
But this doesn't work because jQuery store all originalelement objects and every change of price change all originalelements which were clicked before...
I hope I was clear what I want to do.
I would like to click on price, change and one I go on other price
I believe my old answer won't work.
New tactics - save the old ID in an attribute on the new input you create, and use it in the success handler.
$('#priceBig').click(function() {
var currentText = $.trim($(this).text())
var input = $('<input />')
.addClass('input')
.attr('type', 'text')
.attr('orig-id', $(this).attr('id'))
.val(currentText)
.bind('change', function () {
var t = $(this);
var price = t.val();
var origID = t.attr('orig-id');
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : origID, price:price},
function(data) {
t.remove();
$('#' + origID).text(price).fadeIn(1000);
},'text');
});
$(this).hide().before(input);
});
EDIT: fixed typo in var origID = t.attr('orid-id');
EDIT: change picaID to origID in the $.post parameters