简体   繁体   中英

Changing text dynamically, how to not remove the <i> element?

I have this button:

<button disabled="" id="btnGuardarPaso1" class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Save</button>

And then through jQuery I change the text dynamically based on user selection on a select element. See the code:

if (tipoTramiteSolVal != 1 && tipoTramiteSolVal !== "" && tipoTramiteSolVal != undefined ) {
    $("#btnGuardarPaso1").removeClass("btn-primary").text("Edit");
} else {
    $("#btnGuardarPaso1").addClass("btn-primary").text("Save");
}

But, this code has a problem: the <i class="fa fa-save"></i> element is also removed/changed and I'll like to maintain it. How I can fix this?

Also since the button has a FontAwesome icon, can I change it dynamically too? For example fa-save will change for fa-edit and viceversa depending on the choice by user

You can place a span tag inside of the button and set the text of the span rather than the button. The italics would then be outside of the span.

<button disabled="" id="btnGuardarPaso1" class="btn btn-primary" type="submit"><i class="fa fa-save"><span id="textItem"></span></i> Save</button>


if (tipoTramiteSolVal != 1 && tipoTramiteSolVal !== "" && tipoTramiteSolVal != undefined ) {
$("#btnGuardarPaso1").removeClass("btn-primary");
$("#textItem").text("Edit");
} else {
$("#btnGuardarPaso1").addClass("btn-primary");
$("#textItem").text("Save");
}

[edit] also if you use jQuery to look up the italic tag (either directly by ID or by traversing the DOM) you can definitely set the class using:

 $(this).attr('class','classname');

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