HK1988 HK1988 - 1 year ago 114
PHP Question

Run Function on default HTML Select with PHP And Javascript

I try to Run Default Function on HTML Select, but Default Function doesn't works for Default Selected Value, But it Works On User Select

$status_selected = 'A002';
<!-- HTML Select 1 -->
<select id="state" class="l" name="state" onchange="Func()">
<option value="A001" <?php if($status_selected == "A001") echo "selected"; ?> data_item=" , StateA003 One, A003 State Two, A003 State Three">A001</option>
<option value="A002" <?php if($status_selected == "A002") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A002</option>
<option value="A003" <?php if($status_selected == "A003") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A003</option>
<!-- HTML Select 2 -->
<label for="city">Item : </label><select id="city" name="item" class="l" onchange="onSelected()">

function Func() {
var city = document.getElementById('item');
var state = document.getElementById('state');
var val=state.options[state.selectedIndex].getAttribute('data_item');
var arr=val.split(',');
item.options.length = 0;
for(i = 0; i < arr.length; i++) {
if(arr[i] != "") {
item.options[item.options.length] = new Option(arr[i],arr[i]);

function onSelected() {
var item = document.getElementById('item').value;
var state = document.getElementById('state').value;
console.log('Parent : ' + state+ ', Item : ' + item);

it load
HTML Select One
And then Select Item in
HTML Select Two
, But
HTML Select Two
Works Only By
Manual User Select
And Not Works For Default Programatically Value

Whole Of Codes Above Are On PHP File.

How i can fix it ?

Answer Source

Put Out Of PHP Tag:

<script src=""></script>

On Script Tag Put :

$(function() {
    $("#state").on("change", Func()); 

After :

item.options[item.options.length] = new Option(arr[i],arr[i]);

put the code :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download