简体   繁体   English

基于锚值的动态表格输入

[英]Dynamic Form Input Based on Anchor Value

I have the following snippets that open a single Modal Form: 我有以下代码片段打开了一个模态表格:

<a class="modalbox" id="foo" href="#inline">Request a Quote</a>
<a class="modalbox" id="bar" href="#inline">Request a Quote</a>
...and so on...

Somehow, I need to render the value of ID in the input "sub" in the following HTML form as well as concatenate the ID with some predetermined text, which is "I am interested in..." 不知何故,我需要以下面的HTML形式在输入“ sub”中呈现ID的值,以及将ID与一些​​预定的文本(“我感兴趣...”)连接起来。

<form id="contact" name="contact" action="#" method="post">
    <input type="hidden" id="product" name="product" value="">
    <label for="sub">Subject:</label>
    <input type="sub" id="sub" name="sub" class="txt" value="I am interested in '$id'">
    <button id="send">Submit</button>

I'm already using Javascript for verification and AJAX for processing to PHP script. 我已经在使用Javascript进行验证,并使用AJAX进行PHP脚本处理。

Edit: This is the Javascript already being used to populate the hidden input above, which is working perfectly: 编辑:这是已经用于填充上面隐藏的输入的Javascript,它运行良好:

$('a').click(function(e) {

 $('#product').val($(this).attr('id'));

I'd suggest, with plain JavaScript, something like: 我建议使用纯JavaScript,例如:

function addTextToInput(from, to, prefix, e) {
    e = e || window.event;
    if (!from || !to) {
        return false;
    }
    else {
        from = from.nodeType == 1 ? from : document.getElementById(from);
        to = to.nodeType == 1 ? to : document.getElementById(to);
        var text = from.id;
        to.value = prefix ? prefix + ' ' + text : text;
    }
}

var as = document.querySelectorAll('a.modalbox');
for (var i = 0, len = as.length; i<len; i++) {
    as[i].onclick = function(e) {
        addTextToInput(this, 'sub', 'I am interested in', e);
    };
}​

JS Fiddle demo . JS小提琴演示

But given that you already seem to be using jQuery: 但鉴于您似乎已经在使用jQuery:

$('a.modalbox').click(function(e){
    e.preventDefault();
    $('#sub').val('I am interested in ' + this.id);
});

JS Fiddle demo . JS小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM