0

I am setting the value of the text field using this function:

var end_limit = 'data';
jQuery(document).on('change', 'select[name=txtSetValue]', function() {
  jQuery("input[name=time]").prop('disabled', false);
  jQuery('input[name=time]').data('endtime', end_limit);
});

jQuery(document).on('change', '.get_value', function() {
  console.log(jQuery("input[name=time]").data('endtime'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" name="time" value="" id="time" class="form-control" autocomplete="off" requried="1" data-endtime="" disabled="disabled">

<select name="txtSetValue">
<option value="0">One</option>
<option value="1">Two</option>
</select>

<input type="button" value="Get Value" class="get_value"/>

Now when I change the select field I can see the data is attached to endtime attribute in the browser but when i try to get it through this script then endLimit does not contains any value, but in another place same function is working there the value is not dynamic set.

jQuery(document).on('change',".get_value",function(){
    var endLimit =  jQuery(this).attr('data-endtime');'
});
user3653474
  • 3,393
  • 6
  • 49
  • 135

2 Answers2

0

In the last block of code you're referencing the input element by .timepicker, but the timepicker class is not set on the input element in the second block of code.

You're also modifying the data attribute with the data method, but retrieving the attribute with the attr method. This should work in theory, but might be failing due to how jQuery interacts and references the DOM.

dzimney
  • 565
  • 1
  • 5
  • 15
  • Now it looks like your `change` event in the third snippet is targeting the `.get_value` button. You'll want to target the `change` event on the `#time` input that's being updated or change the event on the button to `click`. – dzimney Aug 02 '20 at 14:07
0

First of all, as @dzmney says

In the last block of code you're referencing the input element by .timepicker, but the timepicker class is not set on the input element in the second block of code.

Check this and you are using the newer jQuery version.

In newer jQuery versions-

To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use (For newer jQuery versions (jQuery >= 1.4.3))

$(this).data("id")

For lower jQuery version jQuery (jQuery < 1.4.3) use

$(this).attr("data-id");

It is recommended to use lower case in the data key otherwise it just addresses the different attribute.

@VisioN answer

Lokesh Suman
  • 493
  • 5
  • 14