You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery重新格式化已自动格式化的数字以存入数据库?

解决方法:从格式化后的金额中提取原始数值存入数据库

Hey there! I get that you're new to jQuery/JS and using the simple.money.format.js plugin to auto-format numbers as users type. When it comes to saving that value to your database, you just need to strip out the formatting characters (like commas, currency symbols, etc.) to get a clean numeric value. Here's how to do it:

方法1:利用插件内置的原始值存储(如果支持)

Many formatting plugins store the original unformatted value in a data attribute or jQuery's data object for easy access. First, check the plugin's docs (if you have them) to see if it does this. For example, some versions of simple.money.format.js might save the raw value to data-raw or the jQuery data store:

// Try this first to get the original value directly
var rawAmount = $('.money').data('raw'); 
// Or if it's stored in a data attribute
var rawAmount = $('.money').attr('data-raw');

方法2:手动清理格式化后的字符串

If the plugin doesn't store the raw value, you can easily strip out non-numeric characters (except for the decimal point) from the formatted text:

// Get the formatted value from your input/element
var formattedText = $('.money').val(); // Use .text() if it's a non-input element

// Remove all characters that aren't numbers or a decimal point
var rawAmount = formattedText.replace(/[^0-9.]/g, '');

// Optional: Convert to a number type if needed for your database
rawAmount = parseFloat(rawAmount);

结合保存按钮的点击事件

Putting it all together with your save button click handler:

$('button:contains("保存")').click(function(e) {
  e.preventDefault(); // Prevent default form submission if needed
  
  // Get the cleaned numeric value
  var formattedValue = $('.money').val();
  var rawAmount = formattedValue.replace(/[^0-9.]/g, '');
  
  // Optional: Handle edge case where there might be multiple decimals
  var decimalParts = rawAmount.split('.');
  if (decimalParts.length > 2) {
    rawAmount = decimalParts[0] + '.' + decimalParts.slice(1).join('');
  }
  
  // Now send rawAmount to your database (example using AJAX)
  $.ajax({
    url: '/your-save-url', // Replace with your actual endpoint
    method: 'POST',
    data: { amount: rawAmount },
    success: function(response) {
      alert('保存成功!');
    },
    error: function(xhr) {
      console.error('保存失败:', xhr.responseText);
    }
  });
});

A quick note: Make sure to validate the final rawAmount before saving (like checking it's a valid number) to avoid storing bad data in your database.

内容的提问来源于stack exchange,提问作者PJCodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:03:28