Reputation: 4056
I am new to Bootstrap and jQuery, and am having trouble determining best practices for changing properties and attributes of html
elements within js
files.
For example, I have a button that is enabled by default and contains some text. On a click event, I want to disable the button but also change the button text and color.
I have some sample code below where you can see I've been working through some button changes and testing the results. Also, I've referenced that I should use .prop
instead of .attr
when employing jQuery v 1.6 or higher, and I am using jQuery v 3.2.1 for my project.
HTML
<!-- Submit Button -->
<div class="form-group">
<a href="#" class="btn btn-primary" data-toggle="modal" data-target="#submitModal" id="submitButton">Submit</a>
</div>
JavaScript
$(document).ready(function() {
$("#submitButton").click(function(){
//Disable button
// $("#submitButton").prop('disabled', true) //Did not work
// $("#submitButton").attr('disabled', true) //Did not work
$("#submitButton").addClass('disabled')
//Use aria-disabled when button disabled for screen readers
$("#submitButton").prop('aria-disabled', true) //How to confirm this worked?
//$("#submitButton").attr("aria-disabled","true") //use `.attr` instead of `.prop`?
//Change button color
$("#submitButton").button('reset').addClass('btn-success'). //Do I need `.button('reset')? Works fine without this code snippet as shown below in next line of code
//Change button text
$("#submitButton").html('Submission received') //Again, should I use `.button('reset') before `.html('Submission received')?
})
})
Upvotes: 0
Views: 3838
Reputation: 33933
About disabled
, that is a property, so use .prop()
.
About background-color and text color, that is to be changed using .css()
.
About button text, that is .text()
.
$("#submitButton").click(function(){
console.log("HEY");
$(this).prop("disabled",true);
$(this).css({"background-color":"red", "color":"white"});
$(this).text("I'm disabled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submitButton">Submit</button>
This has nothing to do with Bootstrap...
The "chained" way:
$("#submitButton").click(function(){
console.log("HEY");
$(this).prop("disabled",true)
.css({"background-color":"red", "color":"white"})
.text("I'm disabled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="submitButton">Submit</button>
Upvotes: 1