I'm trying to hack together a couple of different jquery functions to help me complete a project I'm working on.
The first portion seems to work (Populating the two input text boxes, but I am unable to populate the second select drop down with the array I have provided. I am sure it is something simple but being new to jquery I cant quite figure it out.
Edit
I need to split the value of the options (Separated by the "_") of the first Select dropdown and send those to both of the text boxes displayed. This is important for my page's functionality.
Here is my html
<form action="/revenue_lines/lock" id="lockLockForm" method="post" accept-charset="utf-8">
<input type="text" id="RevenueLineDate1">
<input type="text" id="RevenueLineDate2">
<select id="selector">
<option value="Data1_<Data1>">Sample1</option>
<option value="Data2_<Data2>">Sample2</option>
</select>
<select id="item"></select>
And here is my jquery
$('#selector').on('change', function () {
var val = this.value;
var parts = val.split("_");
$('#RevenueLineDate1').val(parts[0]);
$('#RevenueLineDate2').val(parts[1]);
});
Sample1 = new Array('Top Story', 'Cases', 'News');
Sample2 = new Array('Top Story', 'Cases', 'News');
populateSelect();
$(function () {
$('#selector').change(function () {
populateSelect();
});
});
function populateSelect() {
selector = $('#selector').val();
$('#item').html('');
eval(selector).forEach(function (t) {
$('#item').append('<option>' + t + '</option>');
});
}
Here is a link to the jsfiddle I'm working off of.
Many thanks in advance!
-
1jsfiddle.net/deuq3/15A.O.– A.O.2014年01月09日 01:44:39 +00:00Commented Jan 9, 2014 at 1:44
-
This is close but I still need to split the values of the Options (separated by the "_") so I can populate both text boxes. Sorry for not being clear I will edit my question.cmill02s– cmill02s2014年01月09日 01:48:47 +00:00Commented Jan 9, 2014 at 1:48
1 Answer 1
You were almost there!
Try this HTML instead:
<select id="selector">
<option value="Sample1">Sample1</option>
<option value="Sample2">Sample2</option>
</select>
Your .val() is getting the value attribute of the selected <option>, not the text.
Edit:
I see from your edit that the original values are important for you. In that case, replace your .val() in populateSelect with .text() and you'll get the behavior I think you want.
function populateSelect() {
selector = $('#selector').text();
$('#item').html('');
eval(selector).forEach(function (t) {
$('#item').append('<option>' + t + '</option>');
});
}
As a note, I wouldn't usually consider using the visible text that way a good practice - it prevents you from doing things like localizing the text. One alternative would be to instead key off of the first portion of the value (Data1, Data2) using split() and use those as your array names. Then you're free to change the displayed text without breaking your functionality.