Nelie
Nelie

Reputation: 93

Make text bold via an onclick event

I would like to make the text bold by clicking a button. See below code, the problem I'm having is that I'm unable to pass the textarea ID to the boldTF() function.

<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<script>
$(document).ready(function() {
    var tfCont = 0;
    var InputsWrapper = $("#InputsWrapper");
    var x = InputsWrapper.length; 
    var namefield = $("#tfButton");

    $(namefield).click(function() {
        tfCont++;
        $(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Type Here"/>' + '<br /><button type="button" onclick="boldTF("field_' + tfCont + '")">Bold</button>' + '<br>' + '</div>' + '</div>');
        x++;
        return false;
    });

    function boldTF(tmp){
        document.getElementById(tmp).style.fontWeight = "bold";
        //alert(tmp);
    };
});
</script>

Thank you.

Upvotes: 0

Views: 7548

Answers (2)

mplungjan
mplungjan

Reputation: 177885

Many issues

  1. <input type="textarea" should be <input type="text" or <textarea ...></textarea>
  2. Use the class to get at the field
  3. No need to mix DOM access with jQuery
  4. jQuery can attach event handlers on dynamically created objects using delegation.

Working fiddle

$(function () {
    $("#tfButton").on("click", function(e) {
        e.preventDefault;
        var tfCont = InputsWrapper.length;
        $("#InputsWrapper").append(
            '<div class="name" id="InputsWrapper_0' + tfCont + '">' +
            '<input type="text" id="field_' + tfCont + '" class="fTypex" placeholder="Your first name"/>' +
            '<br /><button type="button" class="boldTF">Bold</button><br /></div>');
    });
    $("#InputsWrapper").on("click", ".boldTF", function(e) {
        e.preventDefault();
        $(this).parent().find(".fTypex").css({"font-weight":"bold"});
    });
});

Upvotes: 1

j08691
j08691

Reputation: 207901

Remove the inline event handler and use event delegation:

$(document).on('click', 'button', function () {
    $(this).closest('div.name').find('input').css('font-weight', 'bold')
})

jsFiddle example

Upvotes: 1

Related Questions