2

I am converting a collection of text fields to an array using the following code (assume HTML input fields with values):

var bgimgsarray = $("input[class='image_name_input']").map{function(){return $(this).val();}).get();

Then I display it on the page using:

$("#vardisplay").html("var bgimgs = ["+bgimgsarray+"];");

That displays as:

var bgimgs=[image1.jpg,image2.jpg,image3.jpg];

However, I need it to display like this:

var bgimgs=['image1.jpg','image2.jpg','image3.jpg'];

Other than informing the user to put ' at the beginning and end of their input, how would I achieve this? I feel like it should be simple but its driving me crazy.

2 Answers 2

3

Change the way you are mapping the value.

From

return $(this).val();

To:

return "'"+$(this).val()+"'";

Ending code:

var bgimgsarray = $("input[class='image_name_input']").map{function(){return "'"+$(this).val()+"'";}).get();

You may want to make sure you don't add extra 's when the user types them. In that case, make it:

return "'"+$(this).val().replace(/^'|'$/g,'')+"'";
Sign up to request clarification or add additional context in comments.

1 Comment

Aaah of course, that completely slipped my mind. Thank you very much. And thank you for the little bit of regex, thats very helpful.
1

You should already add the quotes when you construct that array. Use the following line to construct you bgimgsarray variable:

var bgimgsarray = $("input[class='image_name_input']").map{function(){return "'" + $(this).val() + "'";}).get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.