Last active
August 24, 2016 15:36
-
-
Save pierre-H/11e1a2c39b34a3c1e11623cd14f95ab6 to your computer and use it in GitHub Desktop.
JQuery : conditional field depending on another field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form> | |
<select id="my-select"> | |
<option value="1">1</option> | |
<option value="2">2</option> | |
</select> | |
<input type="text" data-conditional="my-select" data-conditional-on="1" /> | |
</form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.conditional-hidden { | |
display: none; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var jquery_conditional = { | |
updateField: function (idToCheck, inputToUpdate) { | |
var value = null; | |
var toCheck = $('#' + idToCheck); | |
if (toCheck.is("select")) { | |
value = $('#' + idToCheck + ' :selected').val(); | |
} else if (toCheck.attr('type') == 'checkbox') { | |
if (toCheck.is(':checked')) { | |
value = 1; | |
} else { | |
value = 0; | |
} | |
} else { | |
value = toCheck.val(); | |
} | |
if ($.inArray( | |
value, | |
$(inputToUpdate).attr('data-conditional-on').split(',') | |
) > -1) { | |
$(inputToUpdate).removeClass('conditional-hidden'); | |
} else { | |
$(inputToUpdate).addClass('conditional-hidden'); | |
} | |
}, | |
launch: function () { | |
$('[data-conditional]').each(function (key, value) { | |
var idToCheck = $(value).attr('data-conditional'); | |
this.updateField(idToCheck, value); | |
$('#' + idToCheck).change(function() { | |
this.updateField(idToCheck, value) | |
}.bind(this)); | |
}.bind(this)) | |
} | |
}; | |
jquery_conditional.launch(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment