我需要允許用戶點擊一系列的div。他們基本上選擇x個項目(每個項目都在一個div中)添加到一個組中。每個項目只能添加一次。但他們也應該能夠取消選擇項目。需要切換選定的div,並增加一個計數器
每次選擇一個項目時,它的id都會添加到表單域,所以我可以捕獲所有選定項目ID的逗號分隔列表。
只能選擇x個項目。所以我需要保持選定項目的運行計數並停止選擇其他項目的能力。當然,如果選定的項目未被選中,計數將減少。
我現在擁有的東西,正確的項目ID添加到表單字段,並正確切換div樣式打開和關閉每次單擊。但是,它只是將ID添加到表單字段中。 「x」號碼沒有限制,並且在未選中某個項目時不刪除ID。
任何幫助將是真棒醬。
這裏的HTML:
<h3 style="border-top:none;padding-top:0;">Choose <div id="boxQ">3</div> Items for Your Box</h3>
{% set featuredCollection = 'clctn-box-items'|collection %}
{% for product in featuredCollection.products %}
<div class="row">
<div class="twelve columns">
<div class="box-items" id="tag{{ product.id }}" value="{{ product.id }}">
{{ product.name }} <img class="box-item-thumb" align="right" src="{{ product.images.first.thumbnail('auto', 65)|default('http://placehold.it/100x65') }}"/>
</div>
</div>
</div>
{% endfor %}
<input type="text" id="boxItemIDs" name="box_item_ids" value="">
這裏的CSS:
.box-items {
padding: 5px;
margin: 5px 5px 5px 5px;
border-left: 4px solid #ff7b01;
min-height:75px;
width:100%;
display:inline-block;
background-color:#efefef;
cursor: pointer;
}
.itemClicked {background-color:grey;}
這裏是jQuery的:
//
// Set Selected Item Count - numer of items allowed for this box
//
var itemCount;
$(function() {
var urlString = window.location.href;
var thesplit = urlString.substring(urlString.lastIndexOf("/")+1).split('-');
itemCount = thesplit[0];
});
//
// Handle Box Item Clicks
//
var count = 0;
$(document).ready(function() {
document.getElementById("boxQ").innerHTML = itemCount;
$('div[id^="tag"]').on('click', function() {
var $thisDiv = $(this);
count++;
$thisDiv.toggleClass("itemClicked");
var ids = $(this).attr('value');
var resultObj = $("#boxItemIDs");
var stringToAppend = resultObj.val().length > 0 ? resultObj.val() + "," : "";
resultObj .val(stringToAppend + ids);
});
});
下面是我爲它創建了一個小提琴:https://jsfiddle.net/3z1uoL8f/它不雖然工作。
你可以創建一個小提琴嗎?並請給我們最終的客戶端HTML。 – andi
我沒有看到使用'count'的代碼中定義的任何條件? – renakre
我會爲此做一個小提琴。我上次嘗試後無法運行。我會再嘗試。而伯爵還沒有整合...而是,我以前刪除了我曾嘗試過的B/C它不工作。 –