简体   繁体   中英

jQuery - Append and Remove HTML code

In jQuery, how can I append a line of HTML to some HTML, as well as remove the line of HTML?

Here is the before code:

<div class="form-group">
    <label class="control-label col-md-2" for="txtCvc">Cvc</label>
    <div class="col-md-10">
        <input class="form-control text-box single-line" id="txtCvc" name="Cvc" type="text" value="" />
    </div>
</div>

Here is the after code:

<div class="form-group">
    <label class="control-label col-md-2" for="txtCvc">Cvc</label>
    <div class="col-md-10">
        <input class="form-control text-box single-line" id="txtCvc" name="Cvc" type="text" value="" />
        <span class="field-validation-error" data-valmsg-for="txtCvc" data-valmsg-replace="true">Test message.</span>
    </div>
</div>

I am needing to add this line of code:

<span class="field-validation-error" data-valmsg-for="txtCvc" data-valmsg-replace="true">Test message.</span>

Also, the reverse. How can I remove this line of code?

Here is the before code:

<div class="form-group">
    <label class="control-label col-md-2" for="txtCvc">Cvc</label>
    <div class="col-md-10">
        <input class="form-control text-box single-line" id="txtCvc" name="Cvc" type="text" value="" />
        <span class="field-validation-error" data-valmsg-for="txtCvc" data-valmsg-replace="true">Test message.</span>
    </div>
</div>

Here is the after code:

<div class="form-group">
    <label class="control-label col-md-2" for="txtCvc">Cvc</label>
    <div class="col-md-10">
        <input class="form-control text-box single-line" id="txtCvc" name="Cvc" type="text" value="" />
    </div>
</div>

Sorry, I forgot to mention that I am a beginner when it comes to jQuery. I am looking at the append and remove functions right now. Thanks in advance.

只需使用.append().remove()方法。

It would be more appropriate if you use show() and hide() for an error message like

$('.field-validation-error').show();

for showing the message and

$('.field-validation-error').hide();

for hiding it, use if else for checking your condition.

Providing that you know input field element that you want to show/hide validation messages for, you can use after method to add message:

$field.after('<span class="field-validation-error" data-valmsg-for="txtCvc" data-valmsg-replace="true">Test message.</span>');

and remove to remove it:

$field.next('.field-validation-error').remove();

So $field can be something like this:

var $field = $('#txtCvc');

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