简体   繁体   中英

Change Text Field Once Drop Down Has Been Selected (Multiple forms on 1 page)

I'm looking to change the value of a <p> tag once an option from a drop down has been selected. I have that working but my issue is I am going to have lots of forms on one page and feel like I am repeating my code. Is there a way to do this with a function for example? To save me writing a new section of javascript everytime a form gets added to my page?

My javascript code:

    $('.orderProduct select#packageOption').change(function(){
        $('#packagePrice').html($(this).val());
    });

    $('.orderProduct2 select#packageOption').change(function(){
        $('#packagePrice2').html($(this).val());
    });

Thanks.

Add a data-element-id attribute to each select like:

<select data-element-id="packagePrice">...</select>
<select data-element-id="packagePrice2">...</select>

then you simply need this jQuery code:

$('select[data-element-id]').change(function(){
    var $this = $(this);
    var id = $this.data('element-id');    
    $('#' + id).html($this.val());
});

If you want to avoid the extra attribute you could use jQuery's DOM traversing functions, to locate which p you should update.

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