Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  21] [ 5]  / answers: 1 / hits: 27118  / 12 Years ago, tue, october 9, 2012, 12:00:00

i am having a very frustrating problem. I have this code
which filters out my results and inputs them into a select box



var syn = <?=json_encode($syn)?>;
function filterByCity() {
var e = document.getElementById(city_filter);
var city = e.options[e.selectedIndex].value;
var selectOptions = document.getElementById('syn_list');
selectOptions.options.length = 0;

for (i = 0; i < syn.length; i++) {
if (city == syn[i]['city'] || city == 'all') {
selectOptions.options[selectOptions.options.length] = new Option(syn[i]['name'], syn[i]['id'] + ' onclick=updateTxtContent('' + syn[i]['id'] + '')');
}
}
}


as you might see i am adding a onclick listener to every select option which look great in the source code of the page itself but if i copy it into an edit i notice this
my problem is that the updateTxtContent() function is not called.



<select size=10 name=syn_list id=syn_list class=span12 dir=rtl style=text-align:right;>
<option value=13&quot; onclick=&quot;updateTxtContent('13')>option a</option>
<option value=14&quot; onclick=&quot;updateTxtContent('14')>option b</option>




obviously there should be a better way to do this that i am not aware of.


More From » html

 Answers
18

I think you want to have your event handler on your select rather than on the option. See this fiddle for what I mean



<select size=10 name=syn_list id=syn_list class=span12 dir=rtl style=text-align:right; onchange=updateTxtContent();>
<option value=13>option a</option>
<option value=14>option b</option>
</select>

<script>
function updateTxtContent(){
alert($(#syn_list).val());
}
</script>



Or since it looks like you aren't using jQuery:



function updateTxtContent(){
var e = document.getElementById(syn_list);
var f = e.options[e.selectedIndex].value;
alert(f);
}

[#82652] Monday, October 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maya

Total Points: 418
Total Questions: 116
Total Answers: 112

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
maya questions
Sun, Jul 4, 21, 00:00, 3 Years ago
Tue, Dec 22, 20, 00:00, 4 Years ago
Fri, Nov 6, 20, 00:00, 4 Years ago
Wed, Jul 29, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;