简体   繁体   中英

Unable to dynamically use Font Awesome icon in submit button

I am able to use a font-awesome icon as button text using the following HTML:

<button tabindex="4" type="submit" id="submit" class="btn btn-primary btn-lg disabled" onclick="sendemail(); return false;"><i class="fa fa-paper-plane" aria-hidden="true"></i></button>

However, I need to do this dynamically using JQuery:

var contact_form = $('div#contact.pbmodal div.modal-dialog div.modal-content form');
var submit_button = contact_form.find('button#submit');
submit_button.text('<i class="fa fa-paper-plane" aria-hidden="true"></i>');

The above JQuery outputs the font-awesome element as a text tag, ie the button says <i class="fa fa-paper-plane" aria-hidden="true"></i> instead of showing the actual icon.

Use .html() instead to add HTML tags to your DOM, else the .text() will add the code as text :

submit_button.html('<i class="fa fa-paper-plane" aria-hidden="true"></i>');

Hope this helps.

 var submit_button = $("#submit"); submit_button.html('<i class="fa fa-paper-plane" aria-hidden="true"></i>'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <button tabindex="4" type="submit" id="submit" class="btn btn-primary btn-lg disabled" onclick="sendemail(); return false;"></button> 

Change this line:

submit_button.text('<i class="fa fa-paper-plane" aria-hidden="true"></i>');

to

submit_button.after('<i class="fa fa-paper-plane" aria-hidden="true"></i>');

If you want a button only with a icon the better is to add the font class into the button :

submit_button.addClass('fa fa-paper-plane');

You button will look at:

<button tabindex="4" type="submit" id="submit" class="btn btn-primary btn-lg disabled fa fa-paper-plane" onclick="sendemail(); return false;"></button>

This is a jsFiddle with the previous HTML

https://jsfiddle.net/s0dw6yp4/1/

Change submit_button.text('...') to submit_button.html('...')

Text inserts the exact text you entered while html interprets the html-code.

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