簡體   English   中英

Javascript字數價格計算器

[英]Javascript word count price calculator

一切正常,除了選擇定價計划的問題。 我想要的是,只要用戶單擊指定的價格(即使文本已經存在於textarea中),它都應立即更新最終價格。 但是,第一次單擊時不會改變。

我應該點擊兩次。 有人知道怎么了嗎?

所以這里看起來像:

在此處輸入圖片說明

JavaScript代碼如下:

function __textCalculatorCounter(){

    var value = $('#calculateText').val();
    var spanWords = $('#calculatedWordsTotal'),
        spanChars = $('#calculatedCharsTotal'),
        spanPrice = $('#calculatedPriceTotal');


    if (value.length == 0) {
        spanWords.html(0);
        spanChars.html(0);
        return;
    }

    var selectedPricing = $("input[name=calculatePrice]:checked").val();
    var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
    var totalChars = value.length;
    var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));

    spanWords.html(wordCount);
    spanChars.html(totalChars);
    spanPrice.html(totalPrice.toFixed(2));
}

function _initTextCalculator(){
    var textblock = $('#calculateText');
    textblock.change(__textCalculatorCounter);
    textblock.keydown(__textCalculatorCounter);
    textblock.keypress(__textCalculatorCounter);
    textblock.keyup(__textCalculatorCounter);
    textblock.blur(__textCalculatorCounter);
    textblock.focus(__textCalculatorCounter);
    $('label', '#pricesGroup').click(__textCalculatorCounter);
}

====更新====

我不知道為什么,但是它在jsfiddle中可以正常工作...它是從html和javascript中提取的完全相同的代碼。

JSFIDDLE

因此,由於沒有人回答,我發布了我的答案,該問題得以解決。

問題出在Twitter的Bootstrap 3單選按鈕樣式中,當與javascript一起使用時,這實際上是常見問題。

我更改了單選按鈕的點擊處理程序:

function _initTextCalculator(){
    var textblock = $('#calculateText');
    textblock.change(_textCalculatorTrigger);
    textblock.keydown(_textCalculatorTrigger);
    textblock.keypress(_textCalculatorTrigger);
    textblock.keyup(_textCalculatorTrigger);
    textblock.blur(_textCalculatorTrigger);
    textblock.focus(_textCalculatorTrigger);

    // Fixing bootstrap 3 radio buttons
    $("#pricesGroup label").on('click', function(){
        // Once clicked, mark current radio as checked
        $('input:radio', this).prop("checked", true);
        // Then call a function to calculate the price
        _textCalculatorTrigger();
    });
}

正如已經注釋過的那樣,一旦其父label標簽被單擊,它將首先為單選按鈕分配一個“選中”屬性,然后調用一個函數來計算價格。

謝謝大家

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM