Reputation: 794
I am trying to select a dynamic variable from a checkbox to disable or enable depending upon that state of the checkbox. HTML Code:
<input type="checkbox" name="only_once_1" id="only_once_1" class="onlyonce" >
<input type="text" id="temp_1" name="temp_1">
JAVASCRIPT
$(".onlyonce").change(function($){
var parts = this.name.match(/(\D+)(\d+)$/);
if(this.value == "on"){
$("#"+"temp_"+parts[2]).disable()
}else{
$("#"+"temp_"+parts[2]).enable()
}
});
The idea is that I may have many copies of these boxes that are added dynamically. Any ideas how to get this to work?
Thanks!
Upvotes: 1
Views: 166
Reputation: 42109
If you have control over your HTML structure, you can:
$('.onlyonce').change(function(){
$(this).next('input[type=text]').prop('disabled', this.checked);
});
http://jsfiddle.net/vol7ron/XR9me/2/
Upvotes: 1
Reputation: 193261
You have 3 errors. Here is working code:
$(".onlyonce").change(function() { // <-- error #1: remove $ parameter
var parts = this.name.match(/(\D+)(\d+)$/);
if (this.checked) { // <-- error #2: use checked property
$("#" + "temp_" + parts[2]).prop('disabled', true) // <-- error #3: use prop method
} else {
$("#" + "temp_" + parts[2]).prop('disabled', false)
}
});
Main problem was here: $(".onlyonce").change(function($) {
. By passing $
as parameter to change
method you overwrite reference to jQuery (inside a closure $
became an event object).
Also you can write it a little cleaner:
$(".onlyonce").change(function() {
var parts = this.name.match(/(\D+)(\d+)$/);
$("#temp_" + parts[2]).prop('disabled', this.checked);
});
Upvotes: 3