Reputation: 1
Here's what I'm trying to do. When the page loads, the option "Self" will be selected and there will be no text area next to it. When the user chooses "Other" then the text area will show up next to it. Any help would be much appreciated. I've been stuck on this for a bit and I'm about to pull out what hair I have left.
Here is my code.
HTML
<select name="employee_choice" id="employee_choice" data-role="slider" data-theme="c"data-track-theme="a">
<option value="0">Self</option>
<option value="1">Other</option>
</select>
<input type="text" id="pernr" name="pernr" width="12em" />
JS
$('#employee_choice').change(function(){
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1'){
pernrField.show();
}
if (empSelect == '0'){
pernrField.hide();
}
});
Upvotes: 0
Views: 82
Reputation: 41
First initialize the status, and also on the change() event:
show_pernrfield();
$('#employee_choice').change(function(){
show_pernrfield();
});
function show_pernrfield() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
if (empSelect === '1') {
pernrField.show();
}
else {
pernrField.hide();
}
}
Take a look: http://jsfiddle.net/YhaCh/1/
Try using console.log() to examine values of your variables - then it will become apparent which actions your script takes.
Upvotes: 0
Reputation: 318252
Just toggle the input's visiblity based on the selects value :
$('#employee_choice').on('change', function() {
$('#pernr').toggle(this.value==='1');
});
Upvotes: 2
Reputation: 9244
You need to run it first when the page loads. As seen in this jsFiddle, your code does work if you change the JavaScript to the following:
function showOrHidePernr() {
var pernrField = $('#pernr');
var empSelect = $('#employee_choice').val();
pernrField.hide();
if (empSelect == '1') {
pernrField.show();
}
if (empSelect == '0') {
pernrField.hide();
}
}
$('#employee_choice').change(showOrHidePernr);
$(function() {
showOrHidePernr();
});
Upvotes: 0
Reputation: 1156
you need to check on the selected value.
var empSelect =$('select[name="employee_choice"]').val()
and instead of multiple if you can use else too
Upvotes: 0