Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

jquery - How to get all labels and its input elements in javascript

I would like to get all labels and its input elements using Javascript. I have also radio, checkboxes and textarea elements. Then I want to put it in an array of objects.

This is what I have done,

var html = data;
var array = [];
for(var i=0;i<$("input").length;i++){
    array[i] = {label:"",val:$("input").eq(i).val()};
}
console.log(array);

By the way, doesn't have for attributes and also their next sibling is not always the input/radio/checkbox/textarea element. Sometimes,the structures are,

<label>Something:</label><Br/ ><input type="text" />

How can I do what I want in this situation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use map() method to generate the array and use prevAll() method with jQuery :first pseudo-class selector to get the label(you can't use prev() method since there is a br tag in between).

var array = $("input").map(function(){
  return { 
    label : $(this).prevAll('label:first').text(),
    val:$(this).val()
  };
}).get();

console.log(array);

FYI : If the input is wrapped by label in some case then you can use closest() method to get the wrapped element. Although you can use :input to select all form elements.

var array = $(":input").map(function() {
  return {
    label: $(this).prevAll('label:first').text(),
    val: $(this).val()
  };
}).get();

console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Some</label>
<Br/>
<input type="text" value="1" />
<label>Some1</label>
<Br/>
<input type="text" value="11" />
<label>Some2</label>
<Br/>
<input type="text" value="2" />
<label>Some3</label>
<Br/>
<input type="text" value="4" />
<label>Some4</label>
<Br/>
<input type="text" value="3" />

<label>Some422</label>
<Br/>
<select><option value="1"></option><select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...