2017-03-31 15 views
-2

我有與含有值幾個輸入字段的網頁:提取值

<input type="text" id="input_1" value="Apple"> 
<input type="text" id="input_2" value="Pear"> 

我需要的Javascript/jQuery來提取這些值並將它們存儲在一個這樣的數組:

var myArray = ["Apple", "Pear"]; 

有沒有人知道一種方法來做到這一點?

謝謝!

+1

你的意思是'無功myArray的= $( 「#INPUT_1」)。VAL(),$( 「#INPUT_2」)。VAL()]'? - 爲什麼不查看jQuery手冊?這是真正的基本東西 – mplungjan

+0

...或'Array.from(document.querySelectorAll('input'))。map(x => x.value);' –

+0

太基本了!做一點閱讀! – funcoding

回答

1

您可以使用jQuery map()get()返回值的數組。

var myArray = $('input[type="text"]').map(function() { 
 
    return this.value; 
 
}).get(); 
 

 
console.log(myArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<input type="text" id="input_1" value="Apple"> 
 
<input type="text" id="input_2" value="Pear">

+0

一個非常好的和乾淨的解決方案。非常感謝Nenad Vracar :) – elton73

1

您可以通過輸入標籤必須循環:

var data = []; 
 
var inputs = document.getElementsByTagName('input'); 
 
for(var i=0; i< inputs.length; i++) 
 
{ 
 
    data.push(inputs[i].value); 
 
} 
 
console.log(data);
<input type="text" id="input_1" value="Apple"> 
 
<input type="text" id="input_2" value="Pear">

如果您使用JQuery

var data = []; 
 
    $('input').each(function(){ 
 
     data.push($(this).val()); 
 
    }); 
 
    console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="input_1" value="Apple"> 
 
    <input type="text" id="input_2" value="Pear">

優化JQuery的:

 var data = []; 
 
     $(":text").each(function(){ //only searches for input type="text" 
 
      data.push($(this).val()); 
 
     }); 
 
     console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="input_1" value="Apple"> 
 
<input type="text" id="input_2" value="Pear">

UPDATE

我會強烈建議您使用在所有輸入元件的共用類,然後依次通過他們像$('.the_class')爲它甚至更加優化。

+0

Works fine.Sweet! – elton73

+0

感謝您的更新,因爲可能存在其他輸入元素,我想從提取其值中排除。 – elton73

1

jQuery解決方案。

var arr = []; 
 
$('input').each(function(){ 
 
    arr.push($(this).val()); 
 
}); 
 
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="input_1" value="Apple"> 
 
<input type="text" id="input_2" value="Pear">

或純JS的解決方案。

var elems = document.querySelectorAll('input[type="text"]'), 
 
    res = Array.from(elems).map(v => v.value); 
 
    console.log(res);
<input type="text" id="input_1" value="Apple"> 
 
<input type="text" id="input_2" value="Pear">

+1

jQuery和vanilla jS的答案。太好了! – elton73

1

使用document.querySelectorAllArray#map

var result = [].map.call(document.querySelectorAll('input'), function (e) { 
 
    return e.value 
 
}) 
 

 
console.log(result)
<html> 
 
    <body> 
 
     <input type="text" id="input_1" value="Apple"> 
 
     <input type="text" id="input_2" value="Pear"> 
 
    </body> 
 
</html>