-3

I know to get/set values to input fields using jQuery like follow example.

//Get
var bla = $('#txt_name').val();

//Set
$('#txt_name').val(bla);

I want to get/set values using data attribute. For an example, if I have following input I want to set/get values using "data-wpt-id".

<input type="text" data-wpt-id="wpcf-latitude">

Note : Please note that this input field doesn't have id attribute.

  • Use attr https://www.w3schools.com/jquery/html_attr.asp – Sorix Oct 18 '19 at 08:29
  • I think you need to explain better. Do you need help with writing your selector? – Sorix Oct 18 '19 at 08:34
  • If you can't select the element directly then you need to retrieve it from the surrounding HTML structure, eg `$('#container .left-column.foo input').data('wpt-id')` – Rory McCrossan Oct 18 '19 at 08:36

4 Answers4

1
// Get 
var bla = $('input[data-wpt-id="wpcf-latitude"]').val()

// Set
$('input[data-wpt-id="wpcf-latitude"]').val(bla)
cnrhgn
  • 703
  • 4
  • 18
1

You need to use Attribute Selector

//Get
var bla = $('input[data-wpt-id="wpcf-latitude"]').val();

//Set
$('input[data-wpt-id="wpcf-latitude"]').val(bla);
0

You can do it like this:

$('input[data-wpt-id]').val(function() {
  return $(this).data("wpt-id")
});

Demo

$('input[data-wpt-id]').val(function() {
  return $(this).data("wpt-id")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" data-wpt-id="wpcf-latitude">
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
0

Following the jQuery documentation for the data function: https://api.jquery.com/data/

Following the Vanilla documentation for the dataset attribute: https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

Example:

<input type="text" class="container" data-wpt-id="5">

// jQuery
const $inputElement = $('.container');

const wptId = $inputElement.data('wptId');

console.log(wptId); // 5

$inputElement.data('wptId', 10);

console.log($inputElement.data('wptId')); // 10

// Vanilla
const inputElement = document.querySelector('.container');

const wptId= inputElement.dataset.wptId|| 0;

console.log(wptId); // 5

inputElement.dataset.wptId= 10;

console.log(inputElement.dataset.wptId); // 10


// If the `<input>` element has no Id/Class, you can use following selector instead:

const $jquery = $('input[data-wpt-id]');
const vanilla = document.querySelector('input[data-wpt-id]');
Cagatay Ulubay
  • 2,491
  • 1
  • 14
  • 26