Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...