Reputation: 326
Here is my code: JS PART
$(document).ready(function(){
$("#parent").hide();
$(".parentcheck").click(function(){
if($(this).val()==="1")
{
$("#parent").show();
$('#switch').attr('disabled', '');
}
else {
$("#parent").hide();
$('#switch').attr('disabled', 'disabled');
}
});
$("#switch").change(function () {
var selectedSwitch = $("#switch").val();
var parentcheck = $(".parentcheck:checked").val();
if (selectedSwitch!='' && selectedSwitch!='0'){
$.ajax({
type: "POST",
url : "optionsgenerator.php",
data: {menu: selectedSwitch},
success: function(result, status, xResponse){
if (result!=''){
if($('#parentcheck').attr('checked')){
$("#parent").hide();
}
else {
$("#parent").html(result);
$("#parent").show();
}
}
else{
alert('Error occured.');
$("#parent").hide();
}
},
error: function(e){
alert(e);
}
});
}
else
$("#parent").hide();
});
});
And HTML Markup
<select name="switch" id="switch">
<option value="" selected="selected">Select one...</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="0">no one</option>
</select>
<div class="parent">
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
</div>
The problems is
If value of radio button with class "parentcheck"
is 1, my js shows selectbox without checking if it has something to show (in my case options returned from backend php code) or not
I'm trying to achieve following
If value of radio button with class "parentcheck"
is 1 then show
selectbox #parent
ONLY if ajax has already returned something, enable selectbox #switch
Upvotes: -1
Views: 110
Reputation: 12025
You are trying to get parentcheck by id, but parentcheck is a class:
var parentcheck = $("#parentcheck:checked").val();
try to change it to
var parentcheck = $(".parentcheck:checked").val();
EDIT: for the unselecting:
if($(this).val()==="1")
{
if ($("#parent option").length > 0) {
$("#parent").show();
}
$('#switch').attr('disabled', '');
}
else {
$("#parent").hide().find('option:selected').removeAttr('selected');
$('#switch').attr('disabled', 'disabled').find('option:selected').removeAttr('selected');
}
Upvotes: 2
Reputation: 2978
Solutions:
1)
if(selectedSwitch != '' && selectedSwitch !=0)
2)
$(".parentcheck").click(function(){
if($(this).val() == "1")
{
$('#parent).show();
$('#switch').attr('disabled', '');
}
else {
$('#parent').val('');
$('#parent').hide();
$('#switch').val("Select one...");
$('#switch').attr('disabled', 'disabled');
}
});
3) Set a boolean flag in your AJAX function, and then in the click listener only enable the selectbox if(flag).
Upvotes: 1