简体   繁体   中英

How to change placeholder and name from select option dynamically using jQuery

if i need to edit my question please state so before down voting.

I'm creating a form that when an option selected. a form will appear depends on the option selected. How do i dynamically change placeholder and name. Also if the option is selected multiple times the placeholder and name will increment like

placeholder="holder1" name="name1"

placeholder="holder2" name="name2"

here's my code:

Twig file

<select class="form-control" id="collaterals" name="loan_type_id" required>
    <option disabled value="0" selected}>-- Select Collateral --</option>
    <option value="" id="veh_coll">Vehicle</option>
    <option value="" id="hal_coll">House and Lot</option>
    <option value="" id="lot_coll">Lot</option>
</select>

Jquery

jQuery(document).on('click',"#removeThis",function(e){
    jQuery(this).closest('tr').remove();
    e.preventDefault();
});

jQuery("#addType").click(function() {
    var selectedType = jQuery('#collaterals :selected').text();
    jQuery("#nfo").clone().appendTo('tbody');
    jQuery("#addTypeText").val(selectedType);
    jQuery("#nfo").removeClass("hidden-xs-up");
});

当我按下添加按钮时,效果很好

在此处输入图片说明

I need the placeholder and the name to be dynamic depends on the option i selected and also making the name increment for example name="vehicle1" if add another option it will be name="vehicle2"

I am self-taught so someone please show me a better way if possible.

Create a counter with global scope:

i = 0 

(inside a function)

Window[i] = 0 

Increment when they choose an option:

Window[i] ++

When you want to set the name and placeholder:

$(input).attr("placeholder", newValue + window[i])
$(input).attr("name", newValue + window[i])

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