Reputation: 129
$('a#noday').click(function()
{ for(g=1;g<=10;g++)
var ddl = document.getElementById('daySelect_'+g);
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == ""){
ddl.options[i].selected = true;
break;
}
})
$('a#wed').click(function()
{ for(g=1;g<=10;g++)
var ddl = document.getElementById('daySelect_'+g);
var opts = ddl.options.length;
for (var i=0; i<opts; i++){
if (ddl.options[i].value == "wed"){
ddl.options[i].selected = true;
break;
}
})
Below is my select html code
<select class="form-control daySelect" id="daySelect_1" name="daySelect_1">
<option value="">Select</option>
<option value="wed">Wed</option>
<option value="sat">Sat</option>
<option value="sun">Sun</option>
<option value="satsun">Sat/Sun</option>
<option value="wedsatsun">WedSatSun</option>
</select>
Below is my hyperlink html
Set all to:
<a id="noday" href="#"><span class="label label-info">No Day</span></a>
<a id="wed" href="#"><span class="label label-info">Wednesday</span></a>
I tried to click the hyperlink, but my dropdownlist selected does not change. I did try the alert to make sure my link work, and it manage to execute alert.
My JsFiddle
Upvotes: 0
Views: 88
Reputation: 414
why to write for loop, same can be achieved by a single line statement :)
$("#daySelect_1").val("wed");
Upvotes: 1
Reputation: 78595
A few things. You are missing a lot of braces, you would have noticed errors in your console. You also assumed that daySelect_
1 through 10 existed, according to your Fiddle they might not.
$('a#noday').click(function() {
for (g = 1; g <= 10; g++) { // This was missing
var ddl = document.getElementById('daySelect_' + g);
if (!ddl) continue; // What if there is no daySelect_10?
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == "") {
ddl.options[i].selected = true;
break;
}
} // Missing this brace too
}
});
$('a#wed').click(function() {
for (g = 1; g <= 10; g++) {
var ddl = document.getElementById('daySelect_' + g);
if (!ddl) continue;
var opts = ddl.options.length;
for (var i = 0; i < opts; i++) {
if (ddl.options[i].value == "wed") {
ddl.options[i].selected = true;
break;
}
}
}
});
Lastly, you might want to think about using jQuery for all of this, rather than just the DOM events. It will save you having to do so many nested for loops, for example:
$('a#noday').click(function() {
$("[id^=daySelect_").val("");
});
$('a#wed').click(function() {
$("[id^=daySelect_").val("wed");
});
Much neater! jsFiddle
Upvotes: 2