You can directly read the value using $(selector).val()
and send it directly using $.ajax
without needing to put it on the button, however if you want to manipulate your data-attribute
you can use the method .attr
$(function() {
'use strict';
var boton = $('#btnbusca');
var input = $('#source');
var resultado = $('#resultado');
boton.on('click', function() {
boton.attr('data-user', input.val());
resultado.text(boton.attr('data-user'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<input id="source" type="text" class="form-control">
<br>
<button data-user="12345" id="btnbusca" name="btnbusca" class="btn btn-primary input">
Actualizar
</button>
<br>
<br>El valor almacenado es
<div id="resultado">
</div>
Another variant would be using .data
$(function() {
'use strict';
var boton = $('#btnbusca');
var resultado = $('#valor');
var input = $('#source');
boton.on('click', function() {
var valor = input.val()
boton.data('user', valor);
resultado.text(boton.data('user'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<input id="source" type="text" class="form-control">
<br>
<button id="btnbusca" name="btnbusca" class="btn btn-primary input">
Actualizar
</button>
<br>
<br>El valor almacenado es
<div id="valor"></div>
The difference between the two is that the method .data
reads from the attributes data-
of the element
Returns the value stored in the corresponding key for the first element in the collection, as it was stored by the .data(name, value)
method or by an HTML5 attribute data-*
.
but when you type in them the html attribute is not updated, however when you use .attr
what is changed is the attribute as such. Usually the recommended method is $.data
since it is an api designed to store arbitrary data
Stores arbitrary data in the specified elements or returns the value that was stored.