简体   繁体   中英

Add/Remove html element dynamically

I am trying to show form dynamically according to request.

HTML

<label for="Type" class="required">Type</label>
<br>
<input id="f01" name="fieldid[]" type="hidden" value="23">
<input class="23" id="01" required="1" name="type" type="checkbox" value="g_magic"><span>   G magic</span>
<div>
  <div id="div0g_magic"></div>
</div>
<input id="f02" name="fieldid[]" type="hidden" value="23">
<input class="23" id="02" required="1" name="type" type="checkbox" value="four_five"><span>   Four five</span>
<div>
  <div id="div0four_five"></div>
</div>
</div>

JAVASCRIPT

$("#01").on("change", function () {
  var valueid = $("#01").val();
  var fieldid = $("#f01").val();
  if ($(this).is(":checked")) {
    send(valueid, fieldid);
  } else {
    $("#div0" + valueid).empty();
  }
});

function send(valueid, fieldid) {
  $.ajax({
    url: '/echo/js/?js=hello%20world!',
    success: function (response) {

      $("#div0" + valueid).html(response.responseText);

    },
    error: function (response) {
      $("#div0" + valueid).html(response);
    }
  });
}

$("#02").on("change", function () {
  var valueid = $("#02").val();
  var fieldid = $("#f02").val();
  if ($(this).is(":checked")) {
    send(valueid, fieldid);
  } else {
    $("#div0" + valueid).empty();
  }
});

function send(valueid, fieldid) {
  $.ajax({
    url: '/echo/js/?js=hello%20JS!',
    success: function (response) {

      $("#div0" + valueid).html(response.responseText);

    },
    error: function (response) {
      $("#div0" + valueid).html(response);
    }
  });
}

CSS

.required:after {
  color: #e32 !important;
  content: ' * ' !important;
  display: inline !important;
}

method send() making conflict. Give different name for send() in on change function.

Removing html content from an html element

document.getElementById("element_id").innerHTML=""

Adding html content to an html element

document.getElementById("element_id").innerHTML="<p>This is a new content</p>"

I can't see your code, so I can't be completely sure on this, but it sounds like you want to dynamically show/hide a form or forms depending on a request. This is pretty easy to accomplish with jQuery. You would use this code:

$("#element-id").hide();

or

$("#element-id").show();

Where #element-id is the id of the element you want to show/hide. If you want to avoid ID's or hide multiple elements at once, you can give the elements a class like 'element-class', and then you would use:

$(".element-class").hide();

If this isn't what you were looking to accomplish, please update/comment and hopefully someone can help more!

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