jQuery edit in place-每次编辑内容时更新/预填充字段



我正在使用jQuery Jedit(神奇的脚本btw)来创建一个就地编辑表单。因此,我在表单的顶部加载脚本。然后,表单由几个隐藏字段组成,这些字段用相关<p>标签。

在大家的帮助下,这是一个如何预填充字段的示例:

来自就地编辑页面的文本:

<p class="autogrow" style="width: 300px" id="title">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>

做生意的Javascript脚本:

<script type="text/javascript" charset="utf-8">
$(function() {
  $("#input_3_2").val($("#title").text());
});
</script> 

我遇到的问题是,目前,当页面加载时,ID为"input_3_2"的字段被ID为"title"的段落中的文本预先填充。

每次更改段落时,是否可以重新填写/或重新填充字段?

使用回调

$("#title").editable('http://www.example.com/save.php', { 
    type     : 'textarea',
    submit   : 'OK',
    callback : function(value, settings) {
        $("#input_3_2").val( value );     
    }
});

您需要遍历每个文本字段的DOM及其相关的p标记。所以我说,遍历取决于您使用的HTML结构。在这里,我认为您可以将文本字段放在它的相关p标记之前。你可以用类似的东西遍历DOM

   $("input:text").each(function(){
           $(this).val($(this).next('p').text());
   });

如果p具有属性contenteditable="true",则可以订阅它的keyup事件。

例如,如果这是您的html

<p id="TargetP" contenteditable="true">
    Some text
</p>
<input type="hidden" id="TargetHidden"/>
<!-- This anchor is just for the purpose of the demonstration -->
<a href="javascript:;" id="ShowContent">Show hidden's value</a>

​这个脚本将完成的工作

$(function() {
    // declare the function that will take value from p 
    // and put it into the hidden
    function updateHidden() {
        $("#TargetHidden").val($("#TargetP").text());
    }
    // Call it for the first time to update the hidden
    updateHidden();
    // assign it each time the key is released when the p is being
    // edited
    $("#TargetP").keyup(updateHidden);
    // just a dummy action to show the content of the hidden at the
    // given time
    $("#ShowContent").click(function() {
        alert($("#TargetHidden").val());
    });
});​

这是工作演示。


然而,如果formonsubmit事件当然是同步的,我更喜欢它。

<!-- onsubmit="return false" is placed to prevent the form from being
     submitted remove it in production. -->
<form id="TargetForm" onsubmit="return false;">
    <p id="TargetP" contenteditable="true">
        Some text
    </p>
    <input type="hidden" id="TargetHidden"/>
    <input type="submit" value="Submit me" />
    <!-- Demo's helper link -->
    <a href="javascript:;" id="ShowContent">Show content</a>
</form>​

和脚本

// declare the function that will take value from p 
// and put it into the hidden
function updateHidden() {
    $("#TargetHidden").val($("#TargetP").text());
}
$(function() {
    // Call it for the first time to update the hidden
    updateHidden();
    // subscribe to the submit event of your form
    $("#TargetForm").submit(function() {
        updateHidden();
    });
    // dummy function for demo purposes
    $("#ShowContent").click(function() {
        alert($("#TargetHidden").val());
    });
});​

和工作演示

附言如果您有任何其他情况。评论出来,我会更新。

最新更新