ComputerLocus
ComputerLocus

Reputation: 3618

jQuery - Setting Hidden field to Textarea contents when Textarea name is Dynamic

I have a textarea in each row of my table. I need to set this textarea to the value of a hidden field associated with it.

The names of the textarea and hidden field look like so: Textarea name:

sc-(Account Name)c

Hidden fields name:

sc-(Account Name)h

An example would be:

Textarea:

sc-usernamec

Hidden field:

sc-usernameh

On submit or while they type the text, I need the hidden field to be updating with what is typed in the textarea. I'm fairly new to jQuery and Javascript, and I'm wondering how I can either a) go through each textarea field setting its content in the associated hidden field or b) set the hidden field to the textarea as they type.

I'm not sure which option I should use, nor how I would go about programming something of this nature.

Upvotes: 0

Views: 1292

Answers (2)

mplungjan
mplungjan

Reputation: 178126

If the textarea in question is a normal textarea then you can try

$(function() {
    $(":hidden[name^='sc']").each(function() { // all hidden starting with sc
      var id = this.id.substring(0,this.id.length-1)+"c";
      var hid = $(this);                           
      $("#"+id).on("keyup",function() {
          hid.val($(this).val());
        });
    });
});

Live Demo

All bets are of course off if the textarea is converted to an editor - then you need to read

jQuery and TinyMCE: textarea value doesn't submit

which means

$(function() {
  $("#myForm").on("submit",function() {
    $('#sc_texth').val(tinyMCE.get('sc_textc').getContent());
  });
});

or for more

$(function() {
  $("#myForm").on("submit",function() {
    $(":hidden[name^='sc']").each(function() { // hidden and starts with sc
      var textareaID = this.id.substring(0,this.id.length-1)+"c";
      $(this).val(tinyMCE.get(textareaID).getContent());
  });
});

Live Demo

Upvotes: 1

Manikandan S
Manikandan S

Reputation: 922

I think this may help you.

<p><textarea name="sc-username" id="sc-username" ></textarea></p>
<p><textarea name="sc-usernameh" id="sc-usernameh" style="display:none;"></textarea></p>

$(document).ready(function(){  
    $("textarea").on("keyup",function() {  
        var name = $("#"+$(this).attr('name')+"h");  
        if(name)  
          name.val($(this).val());  
    });
});

Upvotes: 0

Related Questions