alessandrob
alessandrob

Reputation: 1615

jQuery - Change name of an input field by using value of another input field filled at the same time

I'm working on a dynamic form where you can add or delete fields, Here you can find the fiddle The first button you find is Add Metric. From this the code generates:

Inside this field a user can add a tag with the button Add Tag, generated when you click add Metric. When you click Add Tag button, two fields are generated:

The Html code that I need to generate in order to serialize the entire form (this is not however the question point) will result like this:

<input type="text" name="metrics[0][name]" value="Text 0"> // Metric
<input type="text" id="TagId0" name=" "> //Tag Id
<input type="text" id="TagValue" name="metrics[0][tags][][0]">

Problem: I need that (when I fill the field with id="TagId0") the value I select will go immediately to the field name with id="TagValue". This field must result like this:

Consider I write on TagId0 the word "hello", field will become:

<input type="text" id="TagValue" name="metrics[0][tags][hello][0]">

How, if it's possible, it can be done? Thanks

Upvotes: 0

Views: 348

Answers (2)

wrxsti
wrxsti

Reputation: 3494

You can use the change method to detect a change in the fields value. Then use the attr method to change the name. Hope I understood correctly. Here is the modified JSFIDDLE.

$(document).on('change', '#InputsWrapper .inputID', function(){
    thisVal = $(this).val();
    thisName = $(this).siblings('.inputVal').attr('name');
    newName = thisName.replace('[tags][', '[tags][' + thisVal);
    $(this).siblings('.inputVal').attr('name', newName);
});

Don't forget to press enter after change the field value :)

Edit: I also added two classes to the fields you are appending. .inputID and .inputVal. I hope this helps!

Upvotes: 1

Shashank Kumar
Shashank Kumar

Reputation: 1220

you can write id of field something like TagId-0 and some common class like tagfield,so that u can split the value to get the index an then access it using the class

$(".tagfield").keypress(function() {
 var id=parseInt($(this).attr("id").split("-"));
      $(this).siblings().attr("name","metrics["+id+"][tags]["+$(this).val()+"][0]");
});

Upvotes: 1

Related Questions