Hendrik Eka Hendrik Eka - 7 months ago 23
Javascript Question

Copy attribute value of link to input value onclick

I want to copy the attribute value

val="ok"
of my link to an input field in my bootstrap modal :



$('#link').on('click', function() {
var x = document.getElementById("link").getAttribute("val");
$("#mail").find(".compose").value = x;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control" placeholder="To:" class="compose" value="" />




Answer

You should create custom data attribute data-val for example and then you can access it like yourElem.dataset.val

var a = document.getElementById('link');
a.addEventListener('click', function() {
  var val = a.dataset.val;
  document.querySelector('.compose').value = val;
})
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />

You can also use JQuery use data()

$('a').click(function() {
  $('input').val($(this).data('val'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-toggle="modal" data-target="#mail" id="link" data-val="ok" class="btn btn-warning btn-flat" title="Mail"><i class="fa fa-envelope"></i>Link</a>
<input class="form-control compose" placeholder="To:" value="" />