传递javascript字数变量值作为隐藏字段值

Pass javascript Word Count variable value as hidden field value

本文关键字:隐藏 字段 变量值 javascript 传递      更新时间:2023-09-26

我有这个简单的页面:http://jsfiddle.net/20140228/2cjw9h9n/1/

使用下面的WordCount代码作为起始点:http://jsfiddle.net/deepumohanp/jZeKu/

但是更基本,只包含单词计数部分的代码。

我需要传递wordCount Javascript变量的值给"varCount"隐藏表单字段变量。

我看了这一页:传递一个javascript变量值到输入类型hidden value

但是我不知道如何实现从页面的建议到我的页面,因为我的Javascript理解是相当基本的!

我想它必须包括这样的东西:

document.getElementById('varCount').value = ???;

我该如何做到这一点?

如果你正在使用jquery

$('#varCount').val('your-value');

val可以同时对特定的DOM元素进行读或写操作

val() -当不带参数调用时读取DOM元素

的值

val('value') -当带参数调用时,将值写入DOM元素

我稍微修改了一下你的代码。

<script>
setWordCount = function(wordCount){ 
    $('#wordCount').html(wordCount);
    // jQuery solution (this is what you actually need)
    $('#varCount').val(wordCount);
    // Commented below is plain JS solution (just in case you're curious)
    // document.getElementById('varCount').value = wordCount;
};
counter = function() {
    var value = $('#text').val();
    if (value.length == 0) {
        setWordCount(0);
    } else {
       var wordCount = value.trim().replace(/'s+/gi, ' ').split(' ').length;
       setWordCount(wordCount);
    }
};
jQuery(function($) {
    $('#count').click(counter);
    // No need to have keypress, keydown, the keyup event will handle it anyway.
    $('#text').change(counter).keyup(counter).blur(counter).focus(counter);
});
</script>

传递你的wordCount变量的值到你的隐藏字段,你可以使用这种方式:

$('#varCount').val(wordCount);

您需要将其写入counter函数。

(在演示中,我已经将隐藏字段更改为文本字段,只是为了显示更改)

试试这个:

<script>
var abc;
abc = document.getElementById('wordCount').value;
<script>

变量abc将获得您在文本区域中输入的单词总数的值