How To Get All Labels And Its Input Elements In Javascript
Solution 1:
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);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label>Some</label><Br/><inputtype="text"value="1" /><label>Some1</label><Br/><inputtype="text"value="11" /><label>Some2</label><Br/><inputtype="text"value="2" /><label>Some3</label><Br/><inputtype="text"value="4" /><label>Some4</label><Br/><inputtype="text"value="3" /><label>Some422</label><Br/><select><optionvalue="1"></option><select>
Solution 2:
You're using labels wrong so I'm going to assume what you really want is just some identifying attribute of the text field checkbox etc to associate with the value.
Here is my go https://jsfiddle.net/1akh5qg9/
JS
<formid="test-form"><label>Label1:</label><inputclass="get-value"name="input1"type="text" /><br><label>Label2:</label><inputclass="get-value"name="input2"type="text" /><br><label>Label3:</label><inputclass="get-value"type="checkbox"name="checkbox1">I have a bike
<br><br><buttonid="submit-button">Get Values</button></form>
HTML
let btn = document.getElementById('submit-button');
let form = document.forms['test-form'].getElementsByClassName('get-value');
let valueArr = [];
// attach onclick handler
btn.onclick = function(e) {
e.preventDefault();
getFormValues();
}
// getFormValuesfunctiongetFormValues() {
for (var x of form){
valueArr.push({label:x.name ,value:x.value})
}
console.log(valueArr);
}
Results
[
{label:"input1", value:"test1"},
{label:"input2", value:"test1"},
{label:"checkbox1", value:"on"}
]
Solution 3:
If you want to select all elements (labels, inputs) into a single array, try using a custom attribute and use a selector like this $('*[data-all-labels-inputs]');
Solution 4:
I would recommend doing something up-front in the HTML to mark the items you want to get.
You could put the label and input pairs in a DIV to indicate that they go together and then give the DIV a class that you could filter and loop on.
You could also use data-tag attributes to name the pairs. Say give all the labels and inputs the attribute data-LabelInp="NameA". Then you can select all labels with attribute data-LabelInp, get the value of the attribute and find the matching input with data-LabelInp === that value.
Post a Comment for "How To Get All Labels And Its Input Elements In Javascript"