default values from selected item before select item - php

I'm using ajax post method for send data in my php file. my code is:
<script type="text/javascript" >
ccc = jQuery.noConflict();
function getArticles(catid){
ccc.post('articles.php',{catid: catid},function(data){
ccc('#articlediv').html(data);}
);
}
</script>
and my select list this is:
<select type="list" name="categorylist" onChange="getArticles(this.value)">
<?php
foreach($categoryid as $catid){
$title = modadcatarticlesHelper::getCatById($catid);
?>
<option value="<?php echo $catid ?>"><?php echo $title ?></option>
<?php } ?>
</select>
it's work and show result when select an item but my problem is i want show default items from a default selected item before select an item but my code only show result when select an item.
how can do it?

If you just want to get something going you can simply add the following:
ccc(function () {//run after the page loads and jquery is ready
getArticles(ccc("select[name='categorylist']").val());
});
I would advise you take care of your naming conventions ccc is not very readable and will make the code harder to understand.

Related

Showing sub-category list when an option select in parent category

I have a list of standards (or classes) and when a person selects the standard 9th or 10th I want to show another drop down list where he/she can select specific groups.
Here is the code for first list (classes)
<?php
/*Getting the data to show in drop down list*/
$sql = $DB_con->prepare( "SELECT DISTINCT cls_id, cls_name FROM class ORDER BY cls_id ASC" );
$sql->execute();
$results = $sql->fetchAll();
?>
And in the form I have displayed the items using foreach...
<html>
<form method="post">
<select name="class">
<option value="">SELECT CLASS</option>
<?php
foreach ($result as $r)
{
echo '<option value="' .
$r["cls_id"] .
'">' .
$r["cls_name"] .
'</option>';
}
?>
</select>
</form>
Now selecting the specific class from first list, I want to show the next list which will have groups. I have code ready to display the items in the list, but no idea how I'm going to show or hide the second list.
I have more than 6 items in first list and groups (which will appear in next list) are only for 2 of the items from first list. As you can see, I have used foreach to populate the first list and plan to use same code to populate the subcategory list. I just don't know how on selection of those 2 items sub-category list should appear.
Unless there are many options in the selectboxes, I would just output all of the group selectboxes with PHP and then hide and show them with JavaScript.
For the PHP, just loop through all the classes, and for every class add a selectbox with the groups. If you have classes A and B you would want HTML like this:
<select name="groups-A" data-class="A" class="group-select">
<option>Option 1</option>
<option>...</option>
</select>
<select name="groups-B" data-class="B" class="group-select">
<option>...</option>
</select>
Then this jQuery will take care of the hiding and showing:
//Run this code when the DOM is ready.
$(function() {
//Execute the function when the select named class changes.
$("select[name=class]").change(function() {
//Hide all of the selectboxes.
$("select.group-select").hide();
//Show the selected one.
var selector = "select[data-class=" + $(this).val() + "]";
$(selector).show();
}
//Trigger the change event so you show the right one to begin with.
$("select[name=class]").trigger("change");
});
You might want to give the class selectbox an ID so you can use #class instead of select[name=class]. Also, you might want to use this CSS
.group-select { display: none; }
to avoid having the selectboxes show before the JS runs.
Disclaimar: I have not tested this code.

Splitting a Select Input for on page Dynamic Form Creation as well as sending value to Form

I need to split a select input in two parts in order to use one part for dynamic form creation on the same page and the second part to be sent to the receiving form.
This is what I have now to dynamically create the div below based on the select input selection:
$a = 0;
while ($row = mysql_fetch_array($result)) {
$people_array[$a] = array(
"ID" => $row['ID'],
"event" => $row['name'],
"time_needed" => $row['time_needed'],
);
$a = $a + 1;
}
$count = count($people_array);
<form>
<?php for($p=0,$p<$count,p++){
$segment_id = $people_array[$p][ID]; ?>
<select name="name_segment" id="name_segment">
<option value="female" >
<?php echo $people_array[$p][name]; ?>
</option>
<option value="male" >
<?php echo $people_array[$p][name]; ?>
</option>
</select>
<?php } ?>
</form>
<div id="name_segment_female" class="name_segment_input" style="display:none;">
Allow at least 30 extra minutes for bathroom usage.
</div>
<div id="name_segment_male" class="name_segment_input" style="display:none;">
No extra bathroom time needed.
</div>
and the javascript
<script>
$("#name_segment").change(function() {
var name_segment = $(this).val();
$(".name_segment_input").hide();
$("#name_segment_" + name_segment).show("slow");
});
</script>
Searching here on stackoverflow, I have found this post that got me started with this: <option value="{type:'amount',segment_id:'<?php echo $segment_id; ?>'} >. I just need to know how I can split this object up with javascript before submitting the page. I need to have the hidden div display dynamically using the same value from the option input as a more specific value that will be sent to the receiving page for the form.
First I changed options values all to be the same length for simplicity.
for example I left "male" the same but changed female to "fmle"
Then I changed the javascript:
$("#name_segment").change(function() {
var name_segment = $(this).val();
var local_segment = name_segment.slice(0,4);
$(".name_segment_input").hide();
$("#name_segment_" + local_segment).show("slow");
});
to parse out just the four letter section and use similarly as the original design. Then I changed the options values to <option value="fmle_<?php echo $segment_id; ?>" >. The segment_id will be parsed out server side after the submission of the form.
If completely necessary we can do a little more work to only send the segment_id as the original question asked but this will achieve the desired objective.

pass the value inside php while loop to javascript using button onclick

I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>

Two drop down list values auto selected based on php session value

I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'

Retrieving value (not display item) of DropDown

I am filling DropDown dynamically using AJAX. The DropDown code looks like this:
<select class="element select medium" id="inDistrict" name="inDistrict" onclick="MakeRequest('divDistrict', 'inDistrict', 'SELECT * FROM districtmaster');" onchange="alert(document.getElementByID('inDistrict').value);">
<option value="Select" selected="Select">Select</option>
</select>
Another file that executes on AJAX request contains following code:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = $_GET['SqlQuery'];
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?= $row[0] ?>"><?= $row[1] ?></option>
<?php } ?>
</select>
Everything works fine and the DropDowns also get filled, except that I am not following how to pick the value of the Option. In the above code you can see that I am using row[0] as value and row[1] as the display item. I want to pick the row[0] value whenever a user selects any row[1] display item.
In the first code above, you can see that I added an onchange event and there is just an alert box. But it is not executing. How to pick the row[0] value and why onchange event is not firing?
onchange doesn't fire in response to DOM manipulation of the selected value. You can fire it manually with some simple javascript:
var inDistrict = document.getElementById('inDistrict');
if (inDistrict.onchange)
inDistrict.onchange();
If you're using jQuery, it's even easier:
$('#inDistrict').change();
Since it looks like you're replacing the entire dropdownlist with your ajax request, just throw some of that javascript in there to fire the change event when it's done populating, and you should be good to go.
Wrong case usage in your onchage event line:
document.getElementByID
Correct:
document.getElementById
Note that rather than using above; you can alert dropdown value like this too:
onchange="alert(this.value);"
Then for dropdown:
If you add [ ] to the names of elements, they become array eg:
<select name="myselect[]">
Now from php you can access each of its element like this:
(assuming that you post method in the form)
echo $_POST['myselect'][0]; // this prints first item value
echo $_POST['myselect'][1]; // this prints second item value
echo $_POST['myselect'][2]; // this prints third item value
//and so on...

Categories