如何使用 ajax/javascript 在表单中附加文本?
我有一个表格。我们称之为 myform。
里面有复选框,例如这两个:
<input type='checkbox' name='power_convention[]' value='SOME VALUE #1' />
<input type='checkbox' name='power_evidence[]' value='SOME VALUE #2' />
在表单的末尾,有一个文本区域。
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
如果选中 power_convention,我希望它立即将该复选框的值附加到具有以下结构的 comments
复选框中:
<h3>SOME VALUE #1</h3><br />
同样,如果单击 power_evidence,我希望它执行相同的操作,但显然无论发生什么之后。
我该怎么做呢?
谢谢!
I have a form. Let's called it myform.
Inside there are checkboxes, such as these two:
<input type='checkbox' name='power_convention[]' value='SOME VALUE #1' />
<input type='checkbox' name='power_evidence[]' value='SOME VALUE #2' />
At the end of the form, there's a textarea.
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
If power_convention is checked, I want it to immediately append the value of that checkbox into the comments
checkbox with the following structure:
<h3>SOME VALUE #1</h3><br />
Similarly, if power_evidence is clicked, I want it to do the same thing, but obviously after whatever came before it.
How would I go about doing this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
jQuery 解决方案:
DEMO
仅当
val< 时才有效/code> 不包含任何特殊的正则表达式字符。在这种情况下,您必须转义它们。
更新:实际上,这里不需要正则表达式,
v.replace(val, '')
就可以了(感谢@Pinkie);正则表达式的替代方法是重新创建文本区域的内容:
DEMO 2
A jQuery solution:
DEMO
This only works if
val
does not contain any special regular expressions characters. In this case you would have to escape them.Update: Actually, you don't need a regular expression here,
v.replace(val, '')
will be just fine (thanks @Pinkie);An alternative to regular expressions would be to recreate the content of the textarea:
DEMO 2
jQuery
如果您希望它们都插入到同一个
textarea
中(并且它们是页面上唯一以 power_ 开头的字段),那么您可以更改选择器以使用jQuery 的 属性开头 选择器:
jsfiddle 上的演示。
jQuery
If you want them both to insert into the same
textarea
(and they're the only fields on the page that begin with power_) then you can change the selector to usejQuery's Attribute Starts With selector:
Demo on jsfiddle.
首先,您需要向复选框添加一个 onClick 事件处理程序:
然后,在 head 部分的 script 标记中,输入
First, you will need to add an onClick event handler to your checkbox:
Then, up in the head section, in a script tag, put
这是一个 jsfiddle
Here's a jsfiddle