Reputation: 1025
I'm trying to get the input type value's from input fields that have been generated by a webshop framework. I can't change the html. When I added fields it creates this:
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
I found some code that gets the value based on the input id, except that the id's filter_... can change, and are different for every shop.
any sugestions? here's what i've gathered so far.
<script type="text/javascript">
var filter;
function onload() {
filter = document.getElementById('filter');
}
function show() {
alert(filter.value);
}
Upvotes: 1
Views: 8112
Reputation: 8276
You can get inputs by tag name, then iterate over it.
var inputs, index, len;
inputs = document.getElementsByTagName('input');
len = inputs.length;
for (index = 0; index < len; ++index) {
alert(inputs[index].value)
}
Upvotes: 1
Reputation: 476
Heres the Jquery solution
$('input [id^="filter_"]').each(function(){
alert( $(this).val() );
});
Upvotes: 1
Reputation: 19007
By using document.querySelectorAll
, in which you can use any CSS selector with, including an "attribute starts with"
selector like input[id^="filter_"]
must get your job done.
Here is a demo
var inputs = document.querySelectorAll('input[id^="filter_"]');
debugger;
for (i = 0; i < inputs.length; i++) {
alert(inputs[i].value)
}
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
Upvotes: 3
Reputation: 10975
You were on the right track with .getElementById
, but you want instead, .getElementsByName
.
var els = document.getElementsByName("filter[]");
for (var i = 0; i < els.length; i++)
alert(els[i].value);
<input id="filter_15" type="checkbox" name="filter[]" value="15">
<input id="filter_16" type="checkbox" name="filter[]" value="16">
<input id="filter_17" type="checkbox" name="filter[]" value="17">
Upvotes: 7