1

I'm trying to be clever with some efficient Javascript but it's causing me headaches and lots of fruitless searching.

I have a set of inputs in a table, each with a given class:

...
<tr>
<td><input name="name" type="text" class="markertitle"/></td>
<td><input name="desc" type="text" class="markerdescription"/></td>
<td><input name="address" type="text" class="markeraddress"/></td>
<td><input name="url" type="text" class="markerurl"/></td>
</tr>
...

I want to take the value of those classes, use it to specify a given variable (which already exists), then assign the value of the input (using +=) to that variable.

This is what I've come up with, but no joy:

    var markertitle = {};
    var markerdescription = {};
    var markeraddress = {};
    var markerurl = {};
    $('#markermatrixadd input').each(function(){
        var field = $(this).attr('class');
        window[field] += $(this).val() + ',';

    });

It's dead simple I'm sure, but I think my brain's a bit fried :(

1
  • Watch out for elements with multiple classes or classes without a matching variable. Commented Jan 13, 2012 at 11:53

1 Answer 1

4

Your vars don't seem to be global. They must be declared outside any function. Besides that, you cannot add anything to an object ({}). Use either strings or arrays:

var markertitle = ""
var markerdescription = ""
etc

function() ....

    $('#markermatrixadd input').each(function(){
        var field = $(this).attr('class');
        window[field] += $(this).val() + ',';

    });

or

var markertitle = []
var markerdescription = []
etc

function() ....

    $('#markermatrixadd input').each(function(){
        var field = $(this).attr('class');
        window[field].push($(this).val())

    });

Better yet, get rid of window and use one single object to store all the data:

var data = {
    markertitle: "",
    markerdescription:  ""
}

function() ....

    $('#markermatrixadd input').each(function(){
        var field = $(this).attr('class');
        data[field] += $(this).val() + ',';

    });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I used your third method. Much appreciated! :)
Not at all! Also, pay attention to the @Stefan's comment above.

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.