[英]Google search bar - add custom search text thru input checkbox
我試圖在單擊復選框時將自定義搜索文本添加到Google搜索欄,並在刪除該文本時將其刪除。 我已經弄清楚了如何在文本區域中添加/刪除文本,以及如何在搜索欄中放置自定義文本,但是在弄清楚如何用自定義文本替換搜索欄中的自定義文本時遇到了一些困難。單擊這些復選框。
的HTML
<body>
<div id="content">
<div id="search">
<gcse:search></gcse:search>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 1" id="checkbox1" name="checkbox" />
<label for="checkbox1" ></label>
</div>
<span>Value 1</span>
</div>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 2" id="checkbox2" name="checkbox" />
<label for="checkbox2" ></label>
</div>
<span>Value 1</span>
</div>
<div class="check_content">
<div class="checkbox">
<input type="checkbox" value="Value 3" id="checkbox3" name="checkbox" />
<label for="checkbox3" ></label>
</div>
<span>Value 1</span>
</div>
</div>
<textarea id="text"></textarea>
</div>
<strong>Google Search Bar with Custom Text</strong>
<script>
(function() {
var cx = '014565979167738564771:fixr4qj_zfs';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
window.onload = function(){
document.getElementById('gsc-i-id1').placeholder = 'This is custom text';
};
</script>
它將被放置在結束標簽的正上方。
將復選框中的文本追加到textarea的函數
$("input[name=checkbox]").change(function() {
updateAllChecked();
});
function updateAllChecked() {
$('#text').text('');
$("input[name=checkbox]").each(function() {
if (this.checked) {
let old_text = $('#text').text() ? $('#text').text() + ', ' : '';
$('#text').text(old_text + $(this).val());
}
})
}
還包括JS小提琴-https: //jsfiddle.net/2pdkv6ph/1/
您的代碼有幾個問題。 首先, $(this).val()
不是復選框$(this).val()
的跨度文本。 您需要遍歷DOM才能找到它。
$(this).parent('div').parent('div').find('span').text();
其次,清除文本框,然后嘗試評估文本框中的文本的順序是向后的(您不能清除它,然后檢查它以查看“舊”文本是什么,因為您剛剛清除了它) 。
一種更簡單的方法是使用數組,然后選中復選框,將跨度的文本推入數組。 循環后,將數組轉換為逗號分隔的字符串,然后將該值分配給文本框。
function updateAllChecked() {
var myArray = [];
$("input[name=checkbox]").each(function() {
if (this.checked) {
var spanText= $(this).parent('div').parent('div').find('span').text();
myArray.push(spanText);
}
});
$('#text').text(myArray.join(", "));
//then assign to the Google text box?
document.getElementById('gsc-i-id1').value = myArray.join(", ");
}
注意:我不完全清楚您輸入id =“ text”相對於Google搜索輸入的目的。 因此,我已經展示了如何將跨度文本分配給兩者。
這是一個Fiddle演示: https : //jsfiddle.net/zephyr_hex/g97rzy2e/2/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.