2016-08-04 30 views
0

在下面,當用戶更改資產標籤時,我想要他們輸入的內容添加到左側字段的末尾(主機名)當且僅當主機名當前具有以' - '結尾的值。jQuery - 從另一個文本輸入(我不知道ID)更新一個文本輸入

而且,我不知道確切的ID或名稱或者它們兩個輸入,因爲他們在PHP會產生這樣的:

<input type="text" name="hostname-<?=$t;?>" class="form-control" id="hostname-<?=$t;?>"> 

<input type="text" name="asset-tag-<?=$t;?>" class="form-control" id="asset-tag-<?=$t;?>"> 

enter image description here

我怎樣才能做到這一點?

編輯 - 我最終實現了我這個代碼希望(資產標籤和主機名總是分享最後一個數字:

$("[name^='asset-tag']").on("change", function() { 
     var host = $(this).attr('name'); 
     var hostname = $('#hostname-' + host.substr(host.lastIndexOf("-") + 1)); 
     var host = hostname.val(); 
     if (host.slice(-1) == "-") { 
     hostname.val(host = host + $(this).val()); 
    } 
    }); 
+0

關於資產框的更改通過var text = $(row).prev('input')。text()然後if(文本最後一個字符是「 - 」),.append(text)檢索輸入框的值。到輸入框。 –

回答

2

基本上你需要:

$("[name^='asset-tag']").on("change", function() { 
    var $host = $(this).prev("[name^='hostname']"); 
    if ($host.val().substr($host.val().length-1) == "-") { 
     $host.val($host.val()+$(this).val()); 
    } 
}); 

在哪裏[name^=表示「名稱屬性以」開始「

注意:這裏假設主機是最接近的元素一個以hostname開頭的名字。

+0

獲取最後一個字符的一種更簡單的方法是使用'.slice(-1)' – 4castle

+0

感謝您的回覆,但是當我更新asset-tag時,此代碼會產生此錯誤:'Uncaught TypeError:Can not read property 'substr'undefined' – daninthemix

+0

雖然我無法完全使用你的代碼,但是你讓我走上了正確的道路,所以我接受了你的答案。將最終代碼添加到我的OP中。 – daninthemix

相關問題