How to make select onchange event happen when page loads? - javascript

The code (below) works fine when the user chooses a dropdown option, but the first option is populated by php based on previous pages. How can I get the onchange event for the select to happen when the page loads, picking up the php added value and acting on it?
<?php
$value = $_GET["value"];
if (!$value){
$value = 'Y';
}
?>
<html>
<head>
<style>
.inv {
display: none;
}
</style>
<script>
function jb(){
document.getElementById("target").value = "Y";
document.getElementById("target").onchange();
}
window.onload = jb;
</script>
</head>
<body>
See more?&nbsp
<select name='see_more' id='target'>
<option value='<?php echo $value; ?>'><?php echo $value; ?></option>
<option value='Y'>Y</option>
<option value='N'>N</option>
</select>
<div id="Y" class='inv'>
Additional content goes here
</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>

I managed to find a solution using php:
<?php
$value = $_GET["value"];
if (!$value){
$value = 'Y';
}
?>
<html>
<head>
<style>
.inv {
display: none;
}
</style>
</head>
<body>
See more?&nbsp
<select name='see_more' id='target'>
<option value='<?php echo $value; ?>'><?php echo $value; ?></option>
<option value='Y'>Y</option>
<option value='N'>N</option>
</select>
<?php
if ($value == 'Y'){
echo "<!--";
}
?>
<div id="Y" class='inv'>
<?php
if ($value == 'Y'){
echo "-->";
}
?>
<?php
if ($value == 'N'){
echo "<!--";
}
?>
<div id="Y" class='vis'>
<?php
if ($value == 'N'){
echo "-->";
}
?>
<br>
Additional content goes here
</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>

If you are using jQuery, you could just do $('#target').change();. So:
$(document).ready(function () {
$('#target').change();
});

Related

php jquery - disable the required attribute for checkbox group on page load

I have a checkbox group where I need to disable the required validation check on page load.
I have tried like below, but the "required" check still appears.
Below is the div that appears from the browser console as is:
<div class="key-class-div">Key :
<select class="targetSelect" name="Keys[]" id="key_H3UKE01hlI" rel="H3UKE01hlI" onchange="return getPreferenceValues(this, 'H3UKE01hlI');">
<option value="">Choose one</option>
<option value="25/checkbox//" alt="25">Gender</option>
<option value="26/checkbox//" alt="26" selected="">Marital Status</option>
<option value="27/radio//" alt="27">Education Status</option>
<option value="28/checkbox//" alt="28">Employment Status</option>
<option value="29/checkbox//" alt="29">Professional Status</option>
<option value="30/checkbox//" alt="30">Interests</option>
<option value="31/checkbox//" alt="31">Age</option>
<option value="40/date/range/" alt="40">DOB</option>
<option value="52/text//" alt="52">Home City/Town</option>
<option value="53/text//" alt="53">Year of Birth</option>
</select>
<span style="color:red;" class="key-error-class" id="key_error_H3UKE01hlI"></span>
<span id="valueResponse_H3UKE01hlI" class="valueResponse-class">
Value :
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" checked="" id="value_H3UKE01hlI" value="211">Single</label>
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" id="value_H3UKE01hlI" value="212">Married</label>
<label id=""><input class="targetSetting" type="checkbox" name="Values[26][]" id="value_H3UKE01hlI" value="0">Any</label>
<span style="color:red;" class="value-error-class" id="value_error_H3UKE01hlI">Required</span>
</span>
HTML : (Have mentioned "problem here below")
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return optinUpdateUsersFun()
}
else if($('input[name=target_criteria]:checked').val() == 'registered_users')
{
return registeredUsersUpdateFun()
}
else if($('input[name=target_criteria]:checked').val() == 'preference_based_users')
{
return validateForm() //Problem here
}
else{
return false;
}
">
JS function which gets called on click of button.
This is where validation is checked as "Required"
(have pasted entire function- so its big)
validateForm = function()
{
console.log('not---');
var validation = true;
var Keys = $('select[name="Keys[]"]');
jQuery.each(Keys,function( key, object )
{
var preferenceData = $("#"+object.id).find('option:selected').attr("value");
var keyId = $("#"+object.id).attr("rel");
$("#key_error_"+keyId).html("");
$("#value_error_"+keyId).html("");
$("#startValue_error_"+keyId).html("");
$("#endValue_error_"+keyId).html("");
var res = preferenceData.split("/");
var preferenceId = res[0];
var dataType = res[1];
var EqualRange = res[2];
var SingleMultiple = res[3];
var value = $(this).val();
if (value.length ==0)
{
$("#key_error_"+keyId).html("Required");
validation = false;
}
var arrayDataTypesOne = [ "number", "date", "time", "text", "dropdown" ];
var arrayDataTypestwo = [ "checkbox", "radio" ];
if (jQuery.inArray(dataType, arrayDataTypesOne) > -1)
{
if (EqualRange == 'equal' || EqualRange == '')
{
if (SingleMultiple == "single")
{
preferenceValue = jQuery("#value_"+keyId).val();
if (preferenceValue.length == 0)
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}else if (SingleMultiple == "multiple")
{
preferenceValue = jQuery("#value_"+keyId).val();
if (preferenceValue.length == 0)
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}
}else if (EqualRange == 'range')
{
StartValue = jQuery("#startValue_"+keyId).val();
EndValue = jQuery("#endValue_"+keyId).val();
if (StartValue.length == 0)
{
$("#startValue_error_"+keyId).html("Required");
validation = false;
}
if (EndValue.length == 0)
{
$("#endValue_error_"+keyId).html("Required");
validation = false;
}
}
}else if (jQuery.inArray(dataType, arrayDataTypestwo) > -1)
{
Values = $('input[name="Values['+preferenceId+'][]"]');
if(!Values.is(':checked'))
{
$("#value_error_"+keyId).html("Required");
validation = false;
}
}
//alert(dataType+'/'+SingleMultiple);
});
// alert(validation);return false;
if (validation == false )
{
return false;
}else{
return true;
}
}
PHP phtml Code for the same (part of the code- for comparison with browser console)
<div class="key-class-div">Key :
<select class="targetSelect" name="Keys[]" id="key_<?php echo $randomString; ?>" class="key-class" rel="<?php echo $randomString; ?>" onchange="return getPreferenceValues(this, '<?php echo $randomString; ?>');">
<option value="">Choose one</option>
<?php foreach ($AdminpreferncesData as $value) { ?>
<option value="<?php echo $value['id'] . '/' . $value['FieldType'] . '/' . $value['EqualRange'] . '/' . $value['SingleMultiple']; ?>" alt="<?php echo $value['id']; ?>" <?php if ($value['id'] == $Fields['PreferenceFieldID']) { ?> selected <?php } ?> ><?php echo $value['FieldName']; ?></option>
<?php } ?>
</select>
<span style="color:red;" class="key-error-class" id="key_error_<?php echo $randomString; ?>" ></span>
<span id="valueResponse_<?php echo $randomString; ?>" class="valueResponse-class">
<?php
$Options = explode(',', $Fields['options']);
$OptionIds = explode(',', $Fields['optionIds']);
$expOptions = array_combine($OptionIds, $Options);
$divid = $randomString;
?>
<?php if ($Fields['FieldType'] == "text") { ?>
Value :<label id="">
<input class="targetSetting" type="text" name="Values[<?php echo $Fields['PreferenceFieldID']; ?>][]" id="value_<?php echo $divid; ?>" value="<?php echo $Fields['KeyValue']; ?>">
<span style="color:red;" class="value-error-class" id="value_error_<?php echo $divid; ?>" ></span>
</label>
...
This is how i am trying to disable the 'required' attribute on page load using jQuery.
$(document).ready(function() {
//Tried using this
$('.targetSetting').removeAttr('required');​​​​​ //not working
$('.valueResponse-class').prop('disabled',true); //not working
});
I want to disable required attribute for all checkboxes/radiobuttons on click of Update button (update button code's HTML have posted above)

My selectbox becomes disabled when accessed through session

I am using Laravel framework and some jquery code.
The problem is that, when i submit the data, it is successfully saved in session. when i get back to previous page, My select box shows the selected value but select-box is disabled. i am totally confused. what shall i do here?
Here is my HTML code:-
<div class="one-row">
<?php foreach ($services as $key => $allservices){
if($key <= 3){
if(!empty($data['services'])){
if(in_array($allservices['id'],$data['services'])) {
$checked = "checked";
} else {
$checked = "";
}
} else {
$checked = "";
}
?>
<div class="div_img_part-2">
<span class="img_part_class-2">
<img src="{{
asset('images/ServiceImages/'. $allservices['image'])}}"></span>
<span class="text_part_class-2">
<span class="check-box">
<input type="checkbox" name="services[]" value="
<?php echo $allservices['id']; ?>" <?= $checked; ?>><?php echo $allservices['name']; ?></span>
</span>
<select name="services[<?php echo $allservices['name'];?>]"class="selectpicker">
<option value="">Select Your Sevice</option>
<option value="Salon" <?php if(!empty($data['services'][$allservices['name']])){ if($data['services'][$allservices['name']] == "Salon") {?> selected
<?php } } ?> >Salon</option>
<option value="Mobile beautician" <?php if(!empty($data['services'][$allservices['name']])){ if($data['services'][$allservices['name']] == "Mobile beautician") {?> selected
<?php } }?> >Mobile beautician</option>
<option value="Both" <?php if(!empty($data['services'][$allservices['name']])){ if($data['services'][$allservices['name']] == "Both") {?> selected
<?php } } ?>>Both</option>
</select>
</div>
<?php } } ?>
</div>
And my Jquery Code looks:-
<script>
$(document).ready(function () {
$(".div_img_part-2 .selectpicker").attr("disabled",true);
$('.selectpicker').selectpicker('refresh');
$(".check-box input[type='checkbox']").on("change", function () {
if ($(this).prop("checked") == true) {
$(this).parents(".div_img_part-2").find(".selectpicker").removeAttr("disabled");
$('.selectpicker').selectpicker('refresh');
}else{
$(this).parents(".div_img_part-2").find(".selectpicker").attr("disabled",true);
$('.selectpicker').selectpicker('refresh');
}
});
});
</script>
Firstly Select
After Select(Edit)
Note:- when user selects the checkbox, the selectbox will be active at first time of registration. All my data are saved in session in Laravel please help me :(
You need to run this once the page is loaded:
$(".check-box input[type='checkbox']").trigger("change");
So the checkbox values will be recognised by the page.

html selection enable disable attribute

I have three selection boxes in one of my web page. I set the two of it to be dependent on the value of the first one like when the value of select a is 1 then the other two will be enabled and I did but the problem lies after I press the submit because after that I cannot clicked the other two even if the value of the first s still selected to 1. Here is my select boxes:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
<label>Department</label>
<select class="field" id="cmbdept" name="dept" onchange="handleSelect()">
<option value=""></option>
<?php
try{
$query1 = $con->prepare("SELECT * FROM departments");
$query1->execute();
} catch(PDOException $e){
echo $e->getMessage();
exit();
}
while($r = $query1->fetch()) {
extract($r);
echo <<<EOL
<option value='$Deptname'>$Deptname</option>
EOL;
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbdept').value = "<?php echo $_GET['dept'];?>";
</script>
<label><strong>Section</strong></label>
<select id="cmbsection" name="section" disabled="disabled">
<option value=""></option>
<?php
try {
$query2 = $con->prepare("SELECT * FROM section");
$query2->execute();
} catch(PDOException $e) {
echo $e->getMessage();
exit();
}
while($s = $query2->fetch()) {
extract($s);
echo "<option value='$sectionName'>$sectionName</option>";
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbsection').value = "<?php echo $_GET['section'];?>";
</script>
<label><strong>Line</strong> </label>
<select id="cmbline" name="line" disabled="disabled">
<option value=""></option>
<?php
try{
$query3 = $con->prepare("SELECT * FROM line");
$query3->execute();
} catch(PDOException $e){
echo $e->getMessage();
exit();
}
while($t = $query3->fetch()) {
extract($t);
echo "<option value='$lineName'>$lineName</option>";
}
?>
</select>
<script type="text/javascript">
document.getElementById('cmbline').value = "<?php echo $_GET['line'];?>";
</script>
<label for="from">From</label>
<input type="text" id="from" name="from">
<script type="text/javascript">
document.getElementById('from').value = "<?php echo $_GET['from'];?>";
</script>
<label for="to">To</label>
<input type="text" id="to" name="to">
<script type="text/javascript">
document.getElementById('to').value = "<?php echo $_GET['to'];?>";
</script>
<br/>
<input type="submit" name="submit" value="Submit">
</form>
and here is the javascript that i use:
function handleSelect() {
var item1 = document.getElementById("cmbdept");
var item2 = document.getElementById("cmbsection");
if(item1.value == 'SEWING') {
document.getElementById('cmbsection').disabled = false;
document.getElementById('cmbline').disabled = false;
} else {
document.getElementById('cmbsection').disabled = true;
document.getElementById('cmbline').disabled = true;
}
}
See if this is what you are trying to do. The key here is to limit repetitions in your script. If you are doing things over and over again, like the same database call sequence, that is a signal you should be creating a function (or class) to go in place of it:
/functions/form.php
<?php
// Since you are doing the same query sequence over and over,
// just do it once and make it reusable
function fetch_query($con,$sql,$keyname = false)
{
try{
$query = $con->prepare($sql);
$query->execute();
} catch(PDOException $e){
// Let's not announce issues to users. You reveal the error
// only if the user is logged in as an administrator otherwise
// You should be able to just return an empty array so the
// web app keeps on going (unless you really want to exit, you can)
//echo $e->getMessage();
return array();
}
while($r = $query->fetch()) {
$result[] = (isset($r[$keyname]))? $r[$keyname] : $r;
}
return (!empty($result))? $result : array();
}
// Create a get_departments function
function get_departments($con)
{
return fetch_query($con,"SELECT * FROM `departments`","Deptname");
}
// Create a get_section function
function get_section($con)
{
return fetch_query($con,"SELECT * FROM `section`","sectionName");
}
// Create a get_line function
function get_line($con)
{
return fetch_query($con,"SELECT * FROM `line`","lineName");
}
// Create a sanitizer function that checks for set array keys
function to_page($array = false,$key = false)
{
if(!is_array($array))
return false;
return (isset($array[$key]))? htmlspecialchars($array[$key],ENT_QUOTES) : "";
}
/form.php (or whatever the name of this page is)
<?php
// include the php functions above
include_once("functions/form.php");
?>
<!-- INCLUDE JQUERY LIBRARIES IF NOT ALREADY SET -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>">
<label>Department</label>
<select class="field" id="cmbdept" name="dept">
<option value="">Select</option>
<?php foreach(get_departments($con) as $Deptname) {
?> <option value="<?php echo $Deptname; ?>"><?php echo $Deptname; ?></option>
<?php }
?>
</select>
<label><strong>Section</strong></label>
<select id="cmbsection" name="section" disabled="disabled">
<option value="">Select</option>
<?php foreach(get_section($con) as $sectionName) {
?> <option value="<?php echo $sectionName; ?>"><?php echo $sectionName; ?></option>
<?php }
?>
</select>
<label><strong>Line</strong> </label>
<select id="cmbline" name="line" disabled="disabled">
<option value="">Select</option>
<?php foreach(get_line($con) as $lineName) {
?> <option value="<?php echo $lineName; ?>"><?php echo $lineName; ?></option>
<?php }
?>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from" value="<?php echo to_page($_GET,"from");?>" />
<label for="to">To</label>
<input type="text" id="to" name="to" value="<?php echo to_page($_GET,"to");?>" />
<br/>
<input type="submit" name="submit" value="Submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
<?php
// Fetch the values of the get
$set['line'] = to_page($_GET,"line");
$set['cmbdept'] = to_page($_GET,"dept");
$set['section'] = to_page($_GET,"section");
// Remove empty
$set = array_filter($set);
// If there are any left, loop through them
if(!empty($set)) {
foreach($set as $idName => $value) {
?>$('#<?php echo $idName; ?>').val('<?php echo $value; ?>');
<?php }
}
?>
// Run on load
handleSelect();
// Run on change
$("#cmbdept").change(function() {
handleSelect();
});
});
function handleSelect()
{
var item2 = $("#cmbsection");
var item1 = $("#cmbdept");
if(item1.val() == 'SEWING') {
item2.prop("disabled",false);
$("#cmbline").prop("disabled",false);
} else {
item2.prop("disabled",true);
$("#cmbline").prop("disabled",true);
}
}
</script>

javascript combo box fill second combo error

I have a rental inspection page I wrote for my work. All the selected
work except anything with more than one. Like bedroom1,bathroom1, fireplace1
works fine as does all the others selections. But when bedroom2,3,4,5,
bathroom2,3,4,5 etc. are selected they do not work at all. I have a work around, just click on the first one then the 2nd etc. uses it.
I have included the bedroom.items.php file at the bottom.
Thanks in advance for any help.
<script type="text/javascript">
function fillSecondCombo()
{
var combo1 = document.getElementById('Combobox1');
var combo2 = document.getElementById('Combobox2');
var selected = combo1.options[combo1.options.selectedIndex].value;
if (selected == "attic")
{
<?php include_once "item.lists/attic.item.php"; ?>
}
else
if (selected == "basement")
{
<?php include_once "item.lists/basement.item.php"; ?>
}
else
if (selected == "bathroom1")
{
<?php include_once "item.lists/bathroom.items.php"; ?>
}
else
if (selected == "bathroom2")
{
<?php include_once "item.lists/bathroom.items.php"; ?>
}
else
if (selected == "bathroom3")
{
<?php include_once "item.lists/bathroom.items.php"; ?>
}
else
if (selected == "bathroom4")
{
<?php include_once "item.lists/bathroom.items.php"; ?>
}
else
if (selected == "bathroom5")
{
<?php include_once "item.lists/bathroom.items.php"; ?>
}
else
if (selected == "bedroom1")
{
<?php include_once "item.lists/bedroom.items.php"; ?>
}
else
if (selected == "bedroom2")
{
<?php include_once "item.lists/bedroom.items.php"; ?>
}
else
if (selected == "bedroom3")
{
<?php include_once "item.lists/bedroom.items.php"; ?>
}
else
if (selected == "bedroom4")
{
<?php include_once "item.lists/bedroom.items.php"; ?>
}
else
if (selected == "bedroom5")
{
<?php include_once "item.lists/bedroom.items.php"; ?>
}
else
if (selected == "cooling")
{
<?php include_once "item.lists/cooling.item.php"; ?>
}
else
if (selected == "diningroom")
{
<?php include_once "item.lists/diningroom.item.php"; ?>
}
else
if (selected == "electric")
{
<?php include_once "item.lists/electric.item.php"; ?>
}
else
if (selected == "water")
{
<?php include_once "item.lists/water.item.php"; ?>
}
else
if (selected == "gas")
{
<?php include_once "item.lists/gas.item.php"; ?>
}
else
if (selected == "exterior")
{
<?php include_once "item.lists/exterior.item.php"; ?>
}
else
if (selected == "foundation")
{
<?php include_once "item.lists/foundation.item.php"; ?>
}
else
if (selected == "garage")
{
<?php include_once "item.lists/garage.item.php"; ?>
}
else
if (selected == "heating")
{
<?php include_once "item.lists/heating.item.php"; ?>
}
else
if (selected == "interior")
{
<?php include_once "item.lists/interior.item.php"; ?>
}
else
if (selected == "kitchen")
{
<?php include_once "item.lists/kitchen.item.php"; ?>
}
else
if (selected == "laundry")
{
<?php include_once "item.lists/laundry.item.php"; ?>
}
else
if (selected == "roof")
{
<?php include_once "item.lists/roof.item.php"; ?>
}
else
if (selected == "waterhtr")
{
<?php include_once "item.lists/waterhtr.item.php"; ?>
}
else
if (selected == "livingroom")
{
<?php include_once "item.lists/livingroom.item.php"; ?>
}
else
if (selected == "fireplace1")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "fireplace2")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "fireplace3")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "fireplace4")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "fireplace5")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "fireplace10")
{
<?php include_once "item.lists/fireplace.items.php"; ?>
}
else
if (selected == "poolspa")
{
<?php include_once "item.lists/poolspa.item.php"; ?>
}
else
if (selected == "other")
{
<?php include_once "item.lists/other.item.php"; ?>
}
else
{
combo2.options.length = 0;
}
}
</script>
</head>
<body>
<div id="space"><br></div>
<div id="container">
<button id="AdvancedButton1" type="button" style="position:absolute;left:19px;top:119px;width:137px;height:44px;z-index:12;" onclick="window.location='main.php'" name="Your Account" value="">
<div style="text-align:center"><span style="color:#FFFFFF;font-family:Arial;font-size:16px"><b>Main Menu</b></span></div>
</button>
<button id="AdvancedButton2" type="button" style="position:absolute;left:176px;top:119px;width:124px;height:44px;z-index:13;" onclick="window.location='logout.php'" name="Logout" value="">
<div style="text-align:center"><span style="color:#FFFFFF;font-family:Arial;font-size:16px"><b>Logout</b></span></div>
</button>
<div id="wb_Form1" style="position:absolute;left:20px;top:209px;width:302px;height:574px;z-index:14;">
<form name="Form1" method="post" action="make.all.php" enctype="multipart/form-data" id="Form1" onsubmit="return ValidateForm1(this)">
<textarea name="a4" id="TextArea1" style="position:absolute;left:1px;top:275px;width:279px;height:143px;z-index:0;" rows="7" cols="32" tabindex="4"></textarea>
<div id="wb_Text5" style="position:absolute;left:4px;top:249px;width:152px;height:16px;z-index:1;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;">Notes: 300 Chars Max.</span></div>
<div id="wb_Text4" style="position:absolute;left:0px;top:164px;width:170px;height:16px;z-index:2;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;">Passed-Needs Repare-N/A:</span></div>
<select name="a2" size="1" id="Combobox2" style="position:absolute;left:0px;top:109px;width:280px;height:43px;z-index:3;" tabindex="2">
</select>
<div id="wb_Text3" style="position:absolute;left:4px;top:85px;width:140px;height:16px;z-index:4;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;">Item Being Inspected:</span></div>
<select name="a1" size="1" id="Combobox1" onchange="fillSecondCombo();return false;" style="position:absolute;left:1px;top:32px;width:279px;height:43px;z-index:5;" tabindex="1">
<option value="<?php include "$dirPath/all.areas.php"; ?>"></option>
</select>
<div id="wb_Text2" style="position:absolute;left:4px;top:0px;width:142px;height:16px;z-index:6;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;">Area Being Inspected:</span></div>
<div id="wb_Text1" style="position:absolute;left:4px;top:436px;width:59px;height:16px;z-index:7;text-align:left;">
<span style="color:#000000;font-family:Arial;font-size:13px;">Photo:</span></div>
<input type="file" id="FileUpload1" style="position:absolute;left:2px;top:452px;width:279px;height:41px;line-height:41px;z-index:8;" name="userfile[]" tabindex="5">
<input type="submit" id="Button1" name="" value="Submit" style="position:absolute;left:44px;top:513px;width:102px;height:30px;z-index:9;" tabindex="6">
<select name="a3" size="1" id="Combobox3" style="position:absolute;left:0px;top:188px;width:280px;height:43px;z-index:10;" tabindex="3">
<option selected value="Passed">Passed</option>
<option value="Needs Repair">Needs Repair</option>
<option value="N/A">N/A</option>
</select>
</form>
</div>
<div id="wb_TextArt1" style="position:absolute;left:18px;top:8px;width:285px;height:100px;z-index:15;">
<img src="images/img0018.png" id="TextArt1" alt="Enter Inspection Data" title="Enter Inspection Data" style="width:285px;height:100px;"></div>
</div>
</body>
</html>
bedroom.items.php
combo2.options.length = 9;
combo2.options[0] = new Option("Electrical Wall Plugs", "Electrical Wall Plugs");
combo2.options[1] = new Option("Walls and Ceiling", "Walls and Ceiling");
combo2.options[2] = new Option("Floor Covering", "Floor Covering");
combo2.options[3] = new Option("Windows (curtains, blinds, etc...)", "Windows (curtains, blinds, etc...)");
combo2.options[4] = new Option("Doors", "Doors");
combo2.options[5] = new Option("Lighting/Light Fixtures", "Light Fixtures");
combo2.options[6] = new Option("Closet(s)", "Closet(s)");
combo2.options[7] = new Option("Smoke Detector(s)", "Smoke Detector(s)");
combo2.options[8] = new Option("Heating/Cooling", "Heating/Cooling");

How to hide select dropdown select?

I want to hide my #wait_1 and #result_1 when the value of select name="drop_1" id="drop_1" is equal to 'ALL' ? I'm new in jquery/javascript, please guide me.
Please check the code below.
app.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$tbl_name="login_admin";
session_start();
if(! isset($_SESSION['id'])){
header('location:go.php');
exit;
}
$id = $_SESSION['id'];
$sql = $mysqli->query("SELECT * FROM $tbl_name WHERE username='$id'");
$accounts = $sql->fetch_assoc();
include('func.php');
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin Page</title>
<script type="text/javascript" src="javascript/jquery-latest.js"></script>
<script type="text/javascript" src="javascript/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#wait_1').hide();
$('#drop_1').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func: "drop_1",
drop_var: $('#drop_1').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#wait_1').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('app_list.php?q='+str)
}
</script>
</head>
<body style="background: radial-gradient(ellipse at center center , rgb(255, 255, 255) 0%, rgb(246, 246, 246) 47%, rgb(237, 237, 237) 100%) repeat scroll 0% 0% transparent;" onload=showUser(str="ALL")>
<br/>
<br/>
<div id="id3">
<div style="text-align:center;">
<form action="app_list.php" method="post">
<select name="drop_1" id="drop_1" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php getTierOne(); ?>
</select>
<span id="wait_1" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_1" style="display: none;"></span>
</form>
</div>
<div id="txtHint"></div>
</div>
</body>
</html>
func.php
<?php
function getTierOne()
{
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT * FROM app GROUP BY app_cn ORDER BY app_cn");
while($row = $result->fetch_assoc())
{
echo '<option value="'.$row['app_cn'].'">'.$row['app_cn'].'</option>';
}
}
if($_GET['func'] == "drop_1" && isset($_GET['func'])) {
drop_1($_GET['drop_var']);
}
function drop_1($drop_var)
{
$mysqli = new mysqli("localhost", "root", "", "app");
$results = $mysqli->query("SELECT * FROM app GROUP BY app_plan_no ORDER BY app_plan_no");
echo '<select name="tier_two" id="tier_two">
<option value=" " disabled="disabled" selected="selected">Choose one</option>';
while($drop_2 = $results->fetch_assoc())
{
if($drop_2['app_plan_no'] != '')
{
echo '<option value="'.$drop_2['app_plan_no'].'">'.$drop_2['app_plan_no'].'</option>';
}
}
echo '</select> ';
echo '<input type="submit" name="submit" value="Submit" />';
}
?>
Try something like this:
$("select[name=drop_1]").change(function() {
if($(this).val() == "All") {
//hide here
$("select[name=tier_two]").hide();
}
});
Note: this is untested
use this function
$(document).ready(function(e){
$("#drop_1").on("change", function(e) {
if( $(this).val() == "ALL") {
$("#tier_two").hide();
}
});
});
and change your html from this
<select name="drop_1" id="drop_1" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
to this
<select name="drop_1" id="drop_1" style="overflow:scroll;width:100px;">
or else if you want to go with your old html code then use this script
your html would be like this
<select name="drop_1" id="drop_1" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
and script would be look like this.
function showUser(comboValue)
{
if(comboValue == "ALL")
$("#tier_two").hide();
}
If you want to keep your showUser function than you can
put the hide and show logic in it as Sohil Desai said.
function showUser(str) {
var $txtHint = $('#txtHint');
if(str == "ALL"){
$("#wait_1").hide();
$("#result_1").hide();
} else {
$("#wait_1").show();
$("#result_1").show();
}
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('app_list.php?q='+str)
}

Categories