Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Getting variable name from HTML

Tags:

javascript

I am attempting to create a reusable javascript / jQuery function where only the HTML will be editable. Basically, the jQuery script will look for a certain class on a form select element, and it will populate the select box. It's going to use an xml document, that will be fed into JavaScript variables.

<form>
    <select name="topliclist" class="mhs-events" data-event-xml="/xml/events.xml" data-event-text="$fullDate, at ,$startTime, - ,$location"></select>
</form>

In this example, 'fullDate', 'startTime' and 'location' are variables in the JavaScript:

//js
var fullDate = 'Monday, October 7';
var startTime = '6:30 PM';
var location = 'Office Building 1';

(don't worry about feeding the variable from xml, I can do that.)

The 'string' variable will equal the data-event-text:

//js
var string = '$fullDate, at ,$startTime, - ,$location';
$.each(string.split(","), function(index, item) {

            //remove $, only put this to specify that it is a variable
            if(item.indexOf('$') == 0) {
                item = $(item.substring(1));
                item = item.toString();
            }

            newString += item
        });

        $(this).append('<option>' + newString + '</option>');

Instead of 'Monday, October 7 at 6:30 PM - Office Building 1', it populates '[object Object] at [object Object] - [object Object];

What is the best way to get the variable name from the data-event-text attribute and actually use it to get the variable value in JavaScript?

like image 460
nitsuj Avatar asked Jun 15 '26 16:06

nitsuj


1 Answers

Change

item = $(item.substring(1)); // this converts your string to object
item = item.toString();

to

item = item.substring(1);
item = eval(item).toString();

And you dont need to add every item into newString which will return all items as one option.

Try:

$.each(string.split(","), function(index, item) {
            //remove $, only put this to specify that it is a variable
            if(item.indexOf('$') == 0) {
                item = item.substring(1);
                item = eval(item).toString();
            }
           newString += item;
});
$('.mhs-events').append('<option>' + newString + '</option>');

DEMO FIDDLE

like image 115
Kiran Avatar answered Jun 17 '26 04:06

Kiran