Billy Origin Billy Origin - 28 days ago 12
PHP Question

Jquery Add string from button value into an input field

I'm trying to add some string from button that has a value into an input field but doesn't work ..

here's jquery code, can anyone please fix it ?

<script type="text/javascript">
$(function () {
$('#button1').on('click', function () {
var text = $('#kategori');
text.val(text.val() + $('#button1')(text.val());
});
});
</script>


and here html + php code

<div class="form-group">
<label for="kategori">
Kategori:
</label>
<input type="text" class="form-control" id="kategori" name="kategori" />
</div>

<?php $query = $this->db->query("SELECT * from kategori_elibrary");
$hasil = $query->result();

?>

<div class="btn-group">

<?php
foreach($hasil as $row){

echo '<button type="button" class="btn btn-primary" id="button1" value="'.$row->kategori.'">'.$row->kategori.'</button>';
} ?>

</div>

Answer

with the help of data-attributes which makes the button markup look like this:

<button type="button" class="btn btn-primary" id="button1" data-value="Food">
    Food
</button>

Then you can use this script:

$('#button1').on('click', function() {
    var $target = $('#kategori'),
    	text = $('#kategori').val(),
        buttonVal = $(this).data('value');
    $target.val(`${text}${buttonVal}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <label for="kategori">
        Kategori:
    </label>
    <input type="text" class="form-control" id="kategori" name="kategori" />
</div>

<button type="button" class="btn btn-primary" id="button1" data-value="Food">Food</button>