I have multiple selects and would like to add or remove a name attribute depending on the option that is chosen in the first select.
Here is a fiddle for an example:
I have multiple selects and would like to add or remove a name attribute depending on the option that is chosen in the first select.
Here is a fiddle for an example:
This should work:
$("#mySelect").change(function() {
var x = $(this).val();
if ($("#" + x).length > 0) {
$("#" + x).attr("name", "myName");
} else {
$(".selectorClass").removeAttr("name");
}
});
You just had a few things backwards and you forgot the '.' in the class selector: $('.class')
. I fixed the fiddle: http://jsfiddle.net/DZFFe/7/
$("#mySelect").change(function() {
$(".selectorClass").removeAttr("name");
var x = document.getElementById("mySelect").value;
if($("#" + x)) {
$("#" + x).attr("name", "myName");
}
});
Something like the following?
$("#mySelect").change(function() {
$('.selectorClass').removeAttr('name');
$('#' + $(this).val()).attr('name', 'myName');
});
there were problems when !!x === false
(ex: empty string in this case). I added a simple check on the if
I also added a missing .
to select by class
$("#mySelect").change(function() {
var x = document.getElementById("mySelect").value;
if(x && $("#" + x)) { //added to check if x != ""
$("#" + x).attr("name", "myName");
} else {
$(".selectorClass").removeAttr("name"); //added missing "." to actually select classes
}
});
Here is a jsFiddle