简体   繁体   English

一旦选择了下拉菜单,请更改文本字段(在1页上有多种表格)

[英]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. 一旦从下拉列表中选择了一个选项,我就希望更改<p>标记的值。 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? 为了节省我每次将表单添加到页面时编写新的javascript部分的时间?

My javascript code: 我的JavaScript代码:

    $('.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属性,例如:

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

then you simply need this jQuery code: 那么您只需要以下jQuery代码:

$('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. 如果要避免使用多余的属性,可以使用jQuery的DOM遍历函数来确定应更新的p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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