traffske
traffske

Reputation: 111

Change attribute in jQuery

I am beginner in JS. I have this code:

<input type="text" name="address[company_name]" class="form-control " id="address[company_name]" value="" data-rule-required="false">

I have many inputs on my page. I need change only input with name address[company_name] => data-rule-required="true"

I try this, but it's not working:

$(".mybutton").click(function () {
  $('address[company_name]').prop(true);
});

How can I repair it?

Upvotes: 0

Views: 42

Answers (2)

ROOT
ROOT

Reputation: 11622

You can use .data() method to modify data attributes, here is a working snippet:

$(".mybutton").click(function () {
    $('input[name="address[company_name]"]').data('rule-required', true);
    console.log($('input[name="address[company_name]"]').get(0));
});
<input type="text" name="address[company_name]" class="form-control " id="address[company_name]" value="">
<button class="mybutton">Click</button>
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>

Upvotes: 1

Giorgos Yiakoumettis
Giorgos Yiakoumettis

Reputation: 97

there you go.

$(".mybutton").click(function () {
    $('[name="address[company]"]').attr('data-rule-required', 'true');
});

Upvotes: 2

Related Questions