Help edit jQuery script

$(function(){ $('#order').bind('change',function(){ $('#order_price').html($('#order option:selected').attr('title')); }); }); 

This script adds to the block with the #order_price value from the title attribute of the option tag. But the problem lies in the fact that the script is triggered on the condition that the options are switched, and therefore, if the selected attribute is set for option, then nothing is displayed in the block. How to make it appear immediately?

    2 answers 2

    Just write a function and call it when the DOM model is ready:

     $(function(){ function start(){ $('#order_price').html($('#order option:selected').attr('title')); } start(); }); 

    Something like this...

    • 2
      I would add a bit: function setPrice () {$ ('# order_price'). Html ($ ('# order: selected'). Attr ('title')); } setPrice (); $ ('# order'). on ('change', setPrice); - Deonis
    • one
      Maybe I'm wrong, but I understand the declaration and use of the function in your code as well as: var a; a = 1; instead: var a = 1; Ie the code you write works the same way as more simple: $ (function () {$ ('# order_price'). Html ($ ('# order option: selected'). Attr ('title'));}); If I am mistaken - please explain the relevance of creating a function here. - Crasher
    • Yes, you can use the option that you offer. Whatever you like ... - spoilt
    • @ eprivalov1, what is the habit here? These are just unnecessary actions, no more. - Crasher
    • one
      If the program consists of 10 lines of code, then of course your method is preferable, and if out of 10,000 lines of code, then all that is best can be broken down into functions. It is more convenient to search, edit, work ... You can make a library of functions and put it into a separate file. This is a personal preference for everyone so to speak .. - spoilt

    Maybe you just need to call a function when loading DOM?

     $(function(){ $('#order').bind('change',function(){ $('#order_price').html($('#order option:selected').attr('title')); }); $('#order').change(); }); 

    It is only desirable to optimize the code, namely:

    1. Replace .bind('change',function(){...}) with .change(function(){...} ;

    2. Remove the second call $('#order') ;

    3. Replace the search $('#order option:selected') with a search among child elements.

    Result:

     $(function(){ $('#order').change(function(){ $('#order_price').html($(this).children(':selected').attr('title')); }).change(); });