7

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..

3 Answers 3

8

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();
Sign up to request clarification or add additional context in comments.

Comments

3

Your "html array" is not an array at all, even assuming there are a number of other similar inputs (though when the form is submitted your chosen server-side language likely lets you access the values of inputs with the same name as an 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 have to do escape them:

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

Or quote the string with singles:

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

It may be more efficient to avoid the attribute starts-with selector with the id attribute and select by the name attribute, noting that for jQuery the square brackets in the atttribute name need to be escaped with backslashes, and for JS string literals backslashes also need to be escaped:

$('input[name="authors\\[\\]"]')

Also to get the value of an input with jQuery use .val() rather than .text(), but it is more efficient to just use this.value:

var authors = [];
$('input[id^="author"]').each(function(){ authors.push(this.value); }); 

I'd also recommend declaring arrays with = [] rather than = new Array().

2 Comments

thank you @nnnnnn, i did not mention here but i have another javascript that adds into authors[], so i have multiple author in fact. i tried your advice and replacev .text() to .val(), and baam! thank you..
Cool. Happy to help. (I understood that you had multiple authors[] elements, but my point about the array is that html doesn't have arrays.)
1

Change:

$("input[id^="author"]").change(update);

To:

$("input[id^='author']").change(update);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.