[英]jQuery - add and remove items in input tag, by click on the specific item
I have a list of color items, like this : Black, Red, Green, Blue, Orange , separated from each other by <div>
tags. 我有一个颜色项列表,例如: 黑色,红色,绿色,蓝色,橙色 ,由<div>
标签彼此分隔。 I don't want to use a checkbox. 我不想使用复选框。
I wrote some jQuery code, but it is doesn't work well. 我写了一些jQuery代码,但效果不佳。 I have some trouble with jQuery array methods, like the each
method, push
and splice
methods. 我在使用jQuery数组方法时遇到了麻烦,例如each
方法, push
和splice
方法。
When I click on the specific color name, for example Green , it should be added in the input
tag, separated by comma from the next color name. 当我单击特定的颜色名称(例如Green)时 ,应将其添加到input
标签中,并用逗号与下一个颜色名称分隔。 And when I click a second time on the same color, it should be removed. 当我第二次单击相同的颜色时,应将其删除。
Also, if I click on each of the color names the first time, they should be added in the input
tag, separated by comma. 另外,如果我第一次单击每种颜色名称,则应将它们添加到input
标记中,并用逗号分隔。
Below is a my code in PHP, jQuery and HTML 下面是我在PHP,jQuery和HTML中的代码
I fetch color values from MySql by PHP: 我通过PHP从MySql获取颜色值:
<?php
$color = explode(',', $row['product_color']);
foreach($color as $color_value){
echo'<div class="colorValue">';
echo'<div class="colorItem">'.$color_value.'</div>';
echo'</div>';
}
?>
This is jQuery code : 这是jQuery代码:
$(document).ready(function(){
$('.colorValue').on('click',function(){
var colorText = $(this).text();
if($(this).attr('color-state') == 1){
$(this).attr('color-state', 0)
$(this).css('border', '2px solid #e0e5ea')
$('#colorResult').val('');
} else {
$(this).attr('color-state', 1)
$(this).css('border', '2px solid #09c')
myFunc(colorText);
}
});
var myList=[];
var ColorValue;
function myFunc(ColorValue){
myList.push(ColorValue);
var output = "";
for(var i in myList){
output +=myList[i] + ',';
//output=output.substring(0,output.length-1);
}
$('#colorResult').val(output);
}
});
Here is the HTML input
tag code, where colors should be added or removed after clicking: 这是HTML input
标签代码,单击后应在其中添加或删除颜色:
<input type="text" name="colorResult" placeholder="Color" id="colorResult"/>
i created a new code for you doing the same thing but in a different way 我为您创建了一个新代码,以相同的方式但以不同的方式
$(document).ready(function(){
$('.colorValue').on('click',function(){
var colorText = $(this).text().trim();
var selectedColors = $('#colorResult').val() !== "" ? $('#colorResult').val().split(',') : [];
var elementIndex = selectedColors.indexOf(colorText);
if(elementIndex == -1)
{
selectedColors.push(colorText);
$('#colorResult').val(selectedColors.join(','));
}
else{
selectedColors.splice(elementIndex, 1);
$('#colorResult').val(selectedColors.join(','));
}
});
});
i created a working JSFiddle you can check it 我创建了一个工作的JSFiddle,您可以检查一下
hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.