0

Can someone help me how to update the Ng-Pattern using Jquery

I have gone through below question but didn't help me(Most of the Question are related to updating to dynamic values using Angular JS)

  1. Question 1
  2. Question 2
  3. Question 3

HTML

<div class="col-md-1" style="width: 50px;" id="hourmain">
    <span ng-show="addItem.Hour.$error.pattern">The number must be between 0-4</span>
    <input class="form-control" type="text" name="Hour" ng-model="form.Hour" placeholder="Hour" required="required" ng-pattern="/^[0-4]+(\.[5]{1})?$/" step="0.5" min="0" max="3" maxlength="3" id="hour">
</div>

Now using Jquery How Can I update the ng-pattern value to ng-pattern="/^[0-9]+(\.[5]{1})?$/"

Vaibhav Bhavsar
  • 432
  • 4
  • 12
Mahesh G
  • 1,226
  • 4
  • 30
  • 57

1 Answers1

1

In jQuery, you can grab the specific element using:

var input = $('input[name="Hour"]');

and then set the value of the ng-pattern attribute, using:

input.attr('ng-pattern', '/^[0-9]+(\.[5]{1})?$/');

Working Example:

$(document).ready(function(){

var input = $('input[name="Hour"]');
input.attr('ng-pattern', '/^[0-9]+(\.[5]{1})?$/');

console.log('input ng-pattern is now: ' + input.attr('ng-pattern'));

});
<div class="col-md-1" style="width: 50px;" id="hourmain">
<span ng-show="addItem.Hour.$error.pattern">The number must be between 0-4</span>
<input class="form-control" type="text" name="Hour" ng-model="form.Hour" placeholder="Hour" required="required" ng-pattern="/^[0-4]+(\.[5]{1})?$/" step="0.5" min="0" max="3" maxlength="3" id="hour" />
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Alternatively, in vanilla javascript, you can grab the specific element using:

var input = document.querySelector('input[name="Hour"]');

and then set the value of the ng-pattern attribute, using:

input.setAttribute('ng-pattern', '/^[0-9]+(\.[5]{1})?$/');

Working Example:

var input = document.querySelector('input[name="Hour"]');
input.setAttribute('ng-pattern', '/^[0-9]+(\.[5]{1})?$/');

console.log('input ng-pattern is now: ' + input.getAttribute('ng-pattern'));
<div class="col-md-1" style="width: 50px;" id="hourmain">
<span ng-show="addItem.Hour.$error.pattern">The number must be between 0-4</span>
<input class="form-control" type="text" name="Hour" ng-model="form.Hour" placeholder="Hour" required="required" ng-pattern="/^[0-4]+(\.[5]{1})?$/" step="0.5" min="0" max="3" maxlength="3" id="hour" />
</div>
Rounin
  • 27,134
  • 9
  • 83
  • 108