Get html array elements using jquery
I have an HTML array,
<input class="input_box" name="authors[]" id="author1"/>
what I want to do is get the value of this array on the display without refreshing the page (I show the value next to the input field in an independent div
)
$(document).ready(function(){ $("input[id^="author"]").change(update); }); function update(){ var authors=new Array(); $("input[id^="author"]").each(function(){authors.push($(this).text()) }); var author= '"' + authors.join('", "') + '"'; $('#val-authors').html('authors:<span class="red"> "'+author+'"</span>');}
The only thing I see in <div id="val-authors">
, "",
What am I missing?
thanks in advance.
Your selector:
$("input[id^="author"]")
incorrect because you are trying to use double quotes inside double quotes. One of the pairs must be a single quote.
If you used the JS debugger, this should be immediately visible.
FWIW, this is a cleaner way to get the required array:
var authors = $('input[id^="author"]').map(function() { return this.value; }).get();
Your โhtml arrayโ is not an array at all, even assuming that there are a number of other similar inputs (although when the form is submitted, the server-side language of your choice will probably allow you to access the values โโof the inputs with the same name as the array ) Anyway...
The main problem is that your JS has a syntax error:
$("input[id^="author"]")
If you want to include double quotes inside a double-quoted string literal, you need to execute them:
$("input[id^=\"author\"]")
Or specify a line with singles:
$('input[id^="author"]')
It may be more efficient to avoid running the attribute - by using the selector with the id attribute and selecting the name attribute, noting that for jQuery the square brackets in the atttribute name should be escaped with backslashes, and for JS string literals, the backslash should also be escaped :
$('input[name="authors\\[\\]"]')
Also, to get the input value with jQuery, use .val()
, not .text()
, but it is more efficient to use this.value
:
var authors = []; $('input[id^="author"]').each(function(){ authors.push(this.value); });
I would also recommend declaring arrays with = []
rather than = new Array()
.