简体   繁体   中英

Jquery append when option from dropdown list clicked

Why doesn't this work?

     <script>
     $(document).ready(function(){
     $('#custom_field option').click(function(){
        $('#custom_field_input').append('<tr><td></td></tr>');      
        $('#custom_field_input td:last').append($(this).find(":selected").text());
     });
     });
     </script>

I found out that there is a .change function for this and it works but does not relate to me as i need to have the text appended even if there is no change in the value of the select dropdown.

Meaning.

User clicks on option1, appends option1 text.

User clicks on option 1 again, another option 1 text gets appended.

Make the custon_field_input element on click of custom_field_opotion as empty with following code :

<script>
 $(document).ready(function(){
 $('#custom_field option').click(function(){
  $('#custom_field_input').html('');      
    $('#custom_field_input').append('<tr><td></td></tr>');      
    $('#custom_field_input td:last').append($(this).find(":selected").text());
 });
 });
 </script>
<script>
 $(document).ready(function(){
 $('#custom_field').change(function(){
    $('#custom_field_input').append('<tr><td></td></tr>');      
    $('#custom_field_input td:last').append($(this).val());
 });
 });
 </script>

this should work in your case as well

Try

 <script>
     $(document).ready(function(){
     $('#custom_field option').click(function(){
     $('#custom_field_input').html('');      
     $('#custom_field_input').append('<tr><td></td></tr>');      
     $('#custom_field_input td:last').append($(this).find(":selected").text());
 });
 });
</script>

You can use blur or focusout events instead of click.

$('#custom_field option').focusout(function(){
....
 });   

$('#custom_field option').blur(function(){
....
 });

Try This.

jQuery(function () {
    jQuery('#custom_field').click(function () {
        jQuery("#custom_field_input").val(jQuery("#custom_field_input").val() + jQuery("option:selected", this).text());
    });
});

Try this: Made 2 changes. Used live incase your selects are getting populated later dynamically. If not use simple .click(). Also instead of .find(":selected"), use .find("option:selected").

<script>
 $(document).ready(function(){
 $('#custom_field option').live('click',function(){
    $('#custom_field_input').append('<tr><td></td></tr>');      
    $('#custom_field_input td:last').append($(this).find("option:selected").text());
 });
 });
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM