0

I've got a jQuery function that triggers when the selected option from a select element changes, its a function that is applied to the select element when it have a specific class:

<script type="text/javascript">
$(document).ready(function() 
{       
    $('.acompanante').on('change', function(event) 
    {   
       //my code
    }
}
</script>

And this is my select element code:

<select class="acompanante" name="acompanante_anterior" id="<?php echo "$i" ?>">
  <option value="0" ><?php echo $txt_nuevo_acompanante;?></option>
  ....
</select>

How do I call the jQuery .change() event of the select element from PHP?

Ben Everard
  • 13,652
  • 14
  • 67
  • 96
Albert Prats
  • 786
  • 4
  • 15
  • 32
  • What do you mean from php? Do you mean on page load? – TJHeuvel Jun 07 '12 at 08:53
  • i want to call the function after i create the dropdownlist. when it changes the jquery function fills a form with all the customer info. I want to load the customer's info in the form if a customer is preselected. – Albert Prats Jun 07 '12 at 08:55
  • Thats on page load. `created` really doesnt mean as much. – TJHeuvel Jun 07 '12 at 08:57

3 Answers3

3

You can't call it from PHP and you don't need it. jQuery doesn't see the PHP, but only the rendered HTML.

So you can just bind it as normal, in this case use the class.

$('.acompanante').change(function(){
    this  // the dropdown which changed
});

Within that, you can use $(this) to see which dropdown it is.

Want to call javascript from PHP, let PHP render the JavaScript to do so:

<script>
    <?
       echo 'javascriptFunction();';
    ?>
</script>
Rene Pot
  • 24,681
  • 7
  • 68
  • 92
  • 2
    +1 for the 'You can't call it from PHP and you don't need it jQuery doesn't see the PHP'... There should be a FAQ/tutorial somewhere explaining the difference of scripts running on the server and on a local machine (in a browser)! – Veger Jun 07 '12 at 08:59
  • @vager there is now! http://meta.stackoverflow.com/questions/269305/looking-for-a-canonical-answer-to-web-development-language-relationships-and-flo?cb=1 – Sam Denton Aug 22 '14 at 15:17
1

You want to execute your function on page load.

<script type="text/javascript">
$(document).ready(function() 
{       
    $('.acompanante').on('change', fillDropdown);
    fillDropdown.call($('.acompanante'));
});

function fillDropdown(event)
{

}
</script>

Some trickery is involved to make this be the jquery object, which is the default behaviour for jQuery. That is what the fn.Call does.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
0

With change():

$('.acompanante').change(function() {
    alert('change() called.');
});
Sanjay
  • 1,570
  • 1
  • 13
  • 30