2016-12-22 80 views
0

林在我的智慧結束與這一個。如何創建一個動態jQuery字符串的複選框ID的

當我點擊一個複選框時,我想在下面的輸入中將複選框的ID添加到以逗號分隔的字符串中。我有這個工作,但是,我不能做的是刪除ID和它的逗號,如果它已經存在於輸入字段(檢查和取消選中)。

簡單的形式。

<form> 
<input class="iteminput" type="checkbox" value="1" id="1" name="<?php echo $title; ?>"> 
<input class="iteminput" type="checkbox" value="2" id="2" name="<?php echo $title; ?>"> 
<input class="iteminput" type="checkbox" value="3" id="3" name="<?php echo $title; ?>"> 

<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->  
<input type="text" id="excludelist" value="<?php echo $saved-string; ?>"> 
</form> 

jQuery(document).ready(function(){ 
    jQuery('.iteminput').on('click', function(){ 
     var id = jQuery(this).attr('ID'); 
     var string = jQuery('#excludelist').val(); 
     var newstring = string + id + ','; 
     jQuery('#excludelist').val(newstring); 
    }) 
}) 
+0

_「我不能做的是去除ID和逗號,如果它已經在輸入欄中存在」 _您可以包括'javascript'在問,你試圖消除串從'輸入''.value'?爲什麼要連接字符串,如果您可以在連接字符串之前檢查字符串是否已存在於.value中? – guest271314

+0

似乎最簡單的方法就是在複選框狀態發生變化時重建整個逗號選擇列表。 – Taplar

回答

1

你可以在輸入框的值,並使用split方法ID的字符串分割成一個數組。此時,您可以檢查您要查找的ID是否在該陣列中。例如:

const id = 3; 
const inputValue = $('input[type=text]').val(); 

// Split the IDs into an array by comma. 
const currentIds = inputValue.split(','); 

if (currentIds.indexOf(id) === -1) { 
    // ID has not yet been added to the input box. 
    // We can add it to the array here, and 
    // update it later. 
    currentIds.push(id); 
} else { 
    // ID is in the current list of IDs. We 
    // can remove it like this: 
    currentIds.splice(currentIds.indexOf(id), 1); 
} 

// Finally, we can reset the input string 
// with the new values we set above. 
$('input[type=text]').val(currentIds.join(',')); 

參見:

String.prototype.split()

Array.prototype.indexOf()

Array.prototype.push()

Array.prototype.splice()

Array.prototype.join()

+0

請問您是否可以擴展您的代碼並解釋如何在輸入字段中添加和刪除ID? –

+0

您可以根據需要添加/刪除數組中的ID,然後使用JavaScript的'Array.prototype.join()'方法重新創建字符串並將其設置爲值。我會更新我的答案給你一個更好的例子。 – samrap

+0

更新了一個更完整的例子 – samrap

1

爲什麼不重建它?

var $iteminputs = $('.iteminput'); 
 

 
$iteminputs.on('change', function(){ 
 
    var ids = $.map($iteminputs.filter(':checked'), function(element){ return element.id; }); 
 
    $('#excludelist').val(ids.join(',')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class="iteminput" type="checkbox" value="1" id="1" name="title1"> 
 
<input class="iteminput" type="checkbox" value="2" id="2" name="title2" checked> 
 
<input class="iteminput" type="checkbox" value="3" id="3" name="title3" checked> 
 

 
<!-- Note that this field may or may not have an existing string of ID's (1,2,3) from previous saves -->  
 
<input type="text" id="excludelist" value="2,3">

相關問題