[英]how to check the check-box if it's value is exist in a text-area
我有一些復選框和一個文本區域,並收集一個文本區域中的所有復選框值,然后將其插入數據庫中,當我從數據庫中選擇數據時,我只有文本區域的數據,而沒有復選框。 我想要的東西是:我查看之前必須選中的復選框。 現在如何檢查復選框的值是否存在於文本區域中,然后選中該框? 我的代碼在這里?
<div style="margin-top:50px;">
<div style="margin-top:-30px;">
<h4>Header Options</h4><br>
<table style="width:70%;float:left">
<tbody>
<tr>
<td><input type="checkbox" id="h_option1" name="h_option1" value="Company Name"> Company Name </td>
<td><input type="checkbox" id="h_option2" name="h_option2" value="Company Address"> Company Address</td>
<td><input type="checkbox" id="h_option3" name="h_option3" value="Month"> Month</td>
<td> <input type="checkbox" id="h_option4" name="h_option4" value="Name"> Name </td>
</tr>
<tr>
<td> <input type="checkbox" id="h_option5" name="h_option5" value="Employee Ref No"> Employee Ref No </td>
<td><input type="checkbox" id="h_option6" name="h_option6" value="Designation"> Designation </td>
<td><input type="checkbox" id="h_option7" name="h_option7" value="Date of joining"> Date of joining </td>
</tr>
</tbody>
</table>
<div>
<span>
<textarea readonly="" type="text" id="header_options" name="header_options" rows="5" cols="25">Company Name,Company Address,Month,Employee Ref No,</textarea>
</span>
</div>
</div>
<br>
<br>
<div align="center">
<input type="button" value="Configure" class="detailsbutton" onclick="get_check_value();">
</div>
<br>
</div>
我期望的結果是: 但這給了我以下結果:
注意:我用文本區域內的逗號分隔復選框的每個值。
var options = document.getElementById('header_options').value;
options = options.split(',');
for(var i = 0; i < options.length; i++){
//Set "checked" for element where the value is the current value in options array
if(options[i]) document.querySelectorAll('input[value="'+options[i]+'"][type="checkbox"]')[0].checked = true;
}
首先,您必須創建一個文本區域中存在的所有復選框的數組,然后必須使用復選框的id檢查相應數組中存在哪些復選框的值。 然后只需根據isExist函數的結果設置選中和未選中
盡管您可以在服務器端代碼(PHP,JSP或使用的任何技術)上做得更好,但是,如果您真的想在客戶端上做它,那么這是普通JavaScript的一種方式(幾乎可以在所有現代版本中使用)瀏覽器版本)。
創建一個函數以選中復選框,
<script type="text/javascript">
function selectChkbox() {
var strAllValues = document.getElementById('header_options').value; // Contains all values
var chkboxArr = document.getElementsByTagName('input');
for(var i=0; i<chkboxArr.length; i++) {
if(chkboxArr[i].type == 'checkbox') {
if(strAllValues.indexOf(chkboxArr[i]) != -1) { // check if checkbox value is present in all values
chkboxArr[i].checked = true;
}
}
}
}
</script>
頁面加載時調用此函數。 像這樣:
<body onload="selectChkbox();">
希望能有所幫助,謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.