简体   繁体   中英

How to toggle font awesome icon in pure javascript

Below is my html and js codes for enabling and disabling the text box on button click. It's working perfectly, but now I need to keep fontawesome icons for button on edit or save.

HTML

<form name="qtyEdit">
    <input type ="text" id ="textBox1" value="7" readonly>
    <input type="button" id="qtyBtnEdit" onClick="enableDisable()" value="Edit">
</form>

JS

function enableDisable() {
    var form = document.qtyEdit;
    if(form.qtyBtnEdit.value=="Edit"){
        form.textBox1.readOnly = false;
        form.qtyBtnEdit.value="Save"
    }
    else{
        form.textBox1.readOnly = true;
        form.qtyBtnEdit.value="Edit"
    }
}

Thanks in Advance

Try the classList.toggle function:

 function enableDisable() { var form = document.qtyEdit; var icon = document.getElementById("icon"); if(form.qtyBtnEdit.value=="Edit"){ form.textBox1.readOnly = false; form.qtyBtnEdit.value="Save"; icon.classList.toggle('fa-pencil'); icon.classList.toggle('fa-floppy-o'); } else{ form.textBox1.readOnly = true; form.qtyBtnEdit.value="Edit"; icon.classList.toggle('fa-floppy-o'); icon.classList.toggle('fa-pencil'); } } 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" type="text/css"> <form name="qtyEdit"> <input type ="text" id ="textBox1" value="7" readonly> <input type="button" id="qtyBtnEdit" onClick="enableDisable()" value="Edit"> <i id="icon" class="fa fa-pencil"></i> </form> 

Make the input a button so that you can add content inside:

<input type="button" id="qtyBtnEdit" onClick="enableDisable()" value="Edit">

becomes

<button type="button" id="qtyBtnEdit" onClick="enableDisable()">Edit</button>

add the fa icon:

<button type="button" id="qtyBtnEdit" onClick="enableDisable()"><i class='fa fa-fw fa-pencil'></i>Edit</button>

to toggle this between edit/save (I've used jquery as the question was tagged jquery):

function enableDisable() {
    if ($("#qtyBtnEdit i").hasClass("fa-pencil")) {
        // Is edit, so change
        $("#qtyBtnEdit").text("Save");
    }
    else {
        // Back to edit
        $("#qtyBtnEdit").text("Edit");
    }
    $("#qtyBtnEdit i").toggleClass("fa-pencil fa-floppy-io")
}

If you want just an icon and no text, remove the text from the button and code:

<button type="button" id="qtyBtnEdit" onClick="enableDisable()"><i class='fa fa-fw fa-pencil'></i></button>

and

function enableDisable() {
    $("#qtyBtnEdit i").toggleClass("fa-pencil fa-floppy-io")
}

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