Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get html array elements with 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 an display without refreshing the page, (i do display the value just 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>');}

only thing i see in <div id="val-authors"> is, "",

what am i missing?

thanks in advance..

like image 860
teutara Avatar asked Mar 15 '12 08:03

teutara


People also ask

How do I get HTML using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

How do I print an array element in HTML?

But when you have an array of objects, the innerHTML of the element will be set as [object Object] instead of the array elements. To print an array of objects properly, you need to format the array as a JSON string using JSON. stringify() method and attach the string to a <pre> tag in your HTML page.


1 Answers

Your selector:

$("input[id^="author"]")

is incorrect, because you're trying to use double quotes inside double quotes. One of the pairs needs to be single quotes.

If you were using a JS debugger this should be immediately visible.

FWIW, this is a cleaner way of retrieving the required array:

var authors = $('input[id^="author"]').map(function() {
  return this.value;
}).get();
like image 163
Alnitak Avatar answered Sep 20 '22 08:09

Alnitak