Fanservice Fanservice - 1 year ago 58
Javascript Question

html - <input type=button> and <button>

I'm trying to get a button value in my textarea which is working fine if I use

<button>
but if I use
<input type=button>
then it not works. Could you find out what is the problem?

HTML

<textarea id="txt-area" readonly></textarea>
<button class="buttons">1</button>
<button class="buttons">2</button>
<button class="buttons">3</button>
<button class="buttons">4</button>
<input type="button" class="buttons" value=" Test">


JavaScript

$(document).ready(function () {
$(".buttons").click(function () {
var cntrl = $(this).html();
$("#txt-area").val(function (_, val) {
return val + cntrl + ","
});
});
});


My code is also in this jsFiddle

Answer Source

BUTTONs have innerHTML but INPUTs don't. You need to check if the element's tag name is Input or Button

Check this updated fiddle

$(document).ready(function () {
    $(".buttons").click(function () {
        var cntrl = $(this).html();
        if ($(this)[0].nodeName == "INPUT" )
        {
                cntrl = $(this).attr( "value" );
        }
        $("#txt-area").val(function (_, val) {
            return val + cntrl + ","
        });
    });
});