簡體   English   中英

基於錨值的動態表格輸入

[英]Dynamic Form Input Based on Anchor Value

我有以下代碼片段打開了一個模態表格:

<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...

不知何故,我需要以下面的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>

我已經在使用Javascript進行驗證,並使用AJAX進行PHP腳本處理。

編輯:這是已經用於填充上面隱藏的輸入的Javascript,它運行良好:

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

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

我建議使用純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小提琴演示

但鑒於您似乎已經在使用jQuery:

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

JS小提琴演示

暫無
暫無

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

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