如何将数组值推送到输入框?

时间:2016-06-30 15:20:23

标签: javascript arrays json

嗨谁可以将值推送到输入框而不是警告框?请保持唯一性并输出整个列表。

Names:<input id='names'/>

var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];

var uniqueNames = [];
for(i = 0; i< data.length; i++){    
    if(uniqueNames.indexOf(data[i].website) === -1){
        uniqueNames.push(data[i].website);        
    }        
}

for(i = 0; i< uniqueNames.length; i++){    
   alert(uniqueNames[i]);    
}

请帮助,因为没有人在线完成!!

1 个答案:

答案 0 :(得分:0)

这是一个部分答案,因为它没有附加到文本框但我设法将其附加到列表中:虽然我的HTML和JS和JSON是部分(MVC5)并且不知道如果从长远来看这是好的做法。但我很高兴我有一半的答案,作为开发人员,我们将一直学到越来越多,因为它是所有的发展!并希望这会帮助某人;-)答案:

HTML: 
Names:<p id="uniqueWebsites"></p>

JS:
var uniqueNamesRes = "";

var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];

var uniqueNames = [];
for(i = 0; i< data.length; i++){    
    if(uniqueNames.indexOf(data[i].website) === -1){
        uniqueNames.push(data[i].website);        
    }        
}

for(i = 0; i< uniqueNames.length; i++){    
  uniqueNamesRes += uniqueNames[i] + "<br>";
}

document.getElementById("uniqueWebsites").innerHTML = uniqueNamesRes;