Pravin Tukadiya Pravin Tukadiya - 7 months ago 6
Javascript Question

Replace every input in form with its value property

I am try to export html as pdf but I am not be able to export the form inputs fields so I need to replace form tag with its value.

I have one form that contain multiple labels and form inputs like text,checkbox,radio button,select etc.

I want to replace that input tag with its value property but I don't know How to do it..

ie.

<div id="Content">
Name : <input type="text" value="abc"/>
Hobby : <input type="checkbox" value="abc" checked/>
<input type="checkbox" value="abc"/>
City :<select class="form-control" id="EmployeeId" name="EmployeeId">
<option value="">--Select One--</option>
<option value="2454">Abc</option>
<option value="2454">Def</option>
<option value="2454" selected>Gif</option>
</select>
</div>


if I have above html of this div than I want output like this

Name : abc
Hobby : abc
City : Gif

Answer

Use .replaceWith, Replace each element in the set of matched elements with the provided new content

:input Selects all input, textarea, select and button elements.

To show output in another element, clone the target element and do the manipulations on cloned(clone()) element.

$('#preview').on('click', function() {
  var temp = $("#Content").clone(true);
  $("#target").append(temp);
  temp.find(":input").each(function() {
    $(this).replaceWith(this.value);
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="Content">
  Name :
  <input type="text" value="abc" />
  <br>Hobby :
  <input type="checkbox" value="abc" checked/>
  <input type="checkbox" value="abc" />
  <br>City :
  <select class="form-control" id="EmployeeId" name="EmployeeId">
    <option value="">--Select One--</option>
    <option value="2454">Abc</option>
    <option value="2454">Def</option>
    <option value="2454" selected>Gif</option>
  </select>
</div>
<br>
<button id='preview'>Show Preview</button>
<h5>Target Elem</h5>
<div id='target'></div>

Edit: To apply conditions for check-box, Use ternary like this: $(this).replaceWith(this.type == 'checkbox' ? (this.checked ? this.value : "") : this.value);

Comments