简体   繁体   English

如何使用javascript将选定的div标签ID值传递给以逗号分隔的单个文本框

[英]How to pass selected div tag id values to single textbox separated by comma using javascript

Javascript: 使用Javascript:

function sample(c_id) 
{
    document.getElementById("result").value="";

  var x = document.getElementById("result").value=c_id; 

}

HTML: HTML:

<div id="1" onclick="sample(this.id)">one</div>
<div id="2" onclick="sample(this.id)">Two</div>
<input type="text" value="" id="result">

Please Help Me... 请帮我...

You'll need to keep an array of values that have already been added to the input. 您需要保留一个已经添加到输入中的值数组。 When you toggle each number, you can have it removed from the array with splice() or added to the array with push() . 切换每个数字时,可以使用splice()将其从数组中删除,也可以使用push()将其添加到数组中。 Then all you need to do is join the values with a comma, and apply it to the value of your input : 然后,您要做的就是用逗号将值连接起来,并将其应用于input的值:

var taken = [];
function sample(c_id)  {
    var inp = document.getElementById("result");
    var ind = taken.indexOf(c_id);
    if(ind > -1){
        taken.splice(ind,1);
        taken = taken;
    } else {
        taken.push(c_id);
    }
    inp.value = taken.join(',');
}

JSFiddle 的jsfiddle

Note: It is invalid to start your id s with a number. 注意:以数字开头的id是无效的。 They should start with a letter. 他们应该以字母开头。

not sure what you are trying to do there. 不知道您要在那里做什么。

You don't need to pass the id to the function, that can be got with .id on a html element. 您无需将id传递给函数,可以通过html元素上的.id获得。 ie. 即。 document.getElementById('someElement').id;

Try to get your javascript in an external document too, as is you are going to place your code inline then you may as well hard code the id anyway. 尝试将javascript也添加到外部文档中,因为您将内联代码,因此您最好还是对ID进行硬编码。 (not suggesting that obviously) (显然没有暗示)

If I'm not wrong I think you want something like this: 如果我没记错,我想你想要这样的东西:

$("div").click(function(){
     $("#result").val($("#result").val() + ", " + $(this).attr("id"))
})

or if you want something similar to your code just do this: 或者如果您想要类似于您的代码的代码,请执行以下操作:

$("div").click(sample($(this).attr("id")));

function sample(c_id) 
{
    document.getElementById("result").val(document.getElementById("result").val() + ", " + c_id);

    var x = document.getElementById("result").val(); 

}
function sample(c_id) {
  var result = document.getElementById('result'),
      resultVal = result.value;
  result.value = resultVal == '' || resultVal == undefined ? c_id : resultVal', '+c_id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM