Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to change input to text area with attribute and atrribute values intact

I have the following:

<input type="text" id="tag_856_subfield_u_270150_676903" name="tag_856_subfield_u_270150_676903" value="http://www.test.com/2073-4441/8/1/23/pdf" class="input_marceditor noEnterSubmit" tabindex="1" size="67" maxlength="9999">

And I wanted to change the text input type into textarea by using the following jquery:

$('input[name^="tag_856_subfield_u"]').each(function () {
    var style = $(this).attr('style'),
    textbox = $(document.createElement('textarea')).attr('style', style);
    $(this).replaceWith(textbox);
});

With the jquery above, I get to have a textarea but the data that is already in the text box is/are removed and inspecting the elements in Google Chrome, I only get the following:

<textarea></textarea>

Is there a way in jquery to do what I wanted to do as what can be seen below, such that I get the following below in my particular use case? The input id and input name is dynamic, hence I used input[name^="tag_245_subfield_b"]. I actually followed this stackoverflow question to achieve my use case: how to change an input element to textarea using jquery.

<textarea cols="70" rows="4" id="tag_856_subfield_u_270150_676903" name="tag_856_subfield_u_270150_676903" class="input_marceditor" tabindex="1">http://www.mdpi.com/2073-4441/8/1/23/pdf</textarea>

Thanks in advance and cheers!

like image 952
schnydszch Avatar asked Oct 27 '25 06:10

schnydszch


1 Answers

Set the value using val(this.value). If you want to copy the other attributes as well, then use the following.

console.log($('input[name^="tag_245_subfield_"]'))
$('input[name^="tag_245_subfield_"]').each(function() {
  var textbox = $(document.createElement('textarea')).val(this.value);
  console.log(this.attributes);
  $.each(this.attributes, function() {
    if (this.specified) {
      textbox.prop(this.name, this.value)
    }
  });
  $(this).replaceWith(textbox);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="tag_245_subfield_u_270150_676903" name="tag_245_subfield_u_270150_676903" value="http://www.test.com/2073-4441/8/1/23/pdf" class="input_marceditor noEnterSubmit" tabindex="1" size="67" maxlength="9999" style="color:red;">

PS : Even though this works there is a chance that all the attributes are not compatible with destination tag type. You'll need to make some conditions and adjustments accordingly.

like image 131
rrk Avatar answered Oct 28 '25 19:10

rrk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!