简体   繁体   中英

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?

there you go.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM