I have two dropdown lists containing customers info.
Using PHP for loop, I have allowed to enter 5 customers details at a time.
for($i=1; $i<6; $i++)
{
echo "<tr><td><select id=\"customer_" . $i . "_class\"></select></td>";
echo "<td><select id=\"customer_" . $i . "_age\"></select></td></tr>";
}
Now I want to execute a jQuery function in such a way that if, for example, customer_2_class changes, it executes some function to its corresponding customer_2_age.
$("#customer_?_clas").change(function()
{
//some function to execute on corresponding customer_?_age
});
Add class to your <select> and move the id to another attribute, like data:
echo "<tr>";
echo "<td><select class=\"customer_class\" data-id=\"$i\"></select></td>";
echo "<td><select class=\"customer_age\" data-id=\"$i\"></select></td>";
echo "</tr>";
And in your javascript:
$('.customer_class').change(function() {
var id = $(this).attr('data-id');
// process customer_class with this id
});
You could use the attribute ends-with selector:
$('select[id$="_class"]').change(function() {
It might be worth browsing through the full list of jQuery selectors.
$('select').
filter(function() {
return /^customer_[0-9]_class$/.test(this.id); // filter on select
// based on id format
})
. change(function() { // binding change
// to filtered select
var num = this.id.match(/\d/)[0]; // get numerical value
// of select box on change
$('#customer_' + num + '_age') // point to target select
.css('background', '#f00'); // do something
});
Working sample
Related
I have a table that is being populated by a given sql query, that has a radio button at the end.
How can i get the entire row value of a selected radio button passed to a different page?
results=mysqli_query($conn,$sqlitem);
while ($dat=mysqli_fetch_assoc($results)){
echo "<tr>";
echo "<td>".$dat['sellername']."</td>";
echo "<td>".$dat['itemname']."</td>";
echo "<td>".$dat['maker']."</td>";
echo "<td>".$dat['details']."</td>";
echo "<td>".$dat['condition']."</td>";
echo "<td>".$dat['price']."</td>";
echo "<td> <input type='radio' name='selc' width ='5px'> </td>";
echo "</tr>";
}
I have tried various combinations but for some reason the entire row value doesn't come. The last and closest option that I tried was this SOMETHING CLOSELY SIMILAR
I took the script portion and updated still isn't working. I believe there should be some solution for this.
You should probably use the MySQL primary key for each row, pass that info to the next page and have PHP perform a query for that item on the new page rather than explicitly passing content around from page to page.
That said, you can keep track of the order that you are echoing the keys in an array, then use that array to turn the row into an object:
var keys = ['sellername','itemname','maker','details','condition','price'];
$('input[type=radio]').on('change', function(event) {
if (this.checked) {
var $tr = $(this).closest('tr');
var $cells = $tr.find('td');
var obj = {};
$.each($cells, function(index, cell) {
obj[keys[index]] = cell.textContent;
});
console.log('row data', obj);
}
});
Note this is untested, but just demonstrates how you can match up an array of key names to the index their data can be found in a table cell
I am trying to get all selected checkbox values with JavaScript, but I have not been able to accomplish it until now. This is what I have tried. What am I doing wrong?
JS:
var femaleMatches = [];
$(".selectFemaleService:checked").each(function() {
console.log('found a female');
femaleMatches.push(this.value);
});
PHP:
echo "<div class='checkbox'><label><input id='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description</label></div>";
Your jQuery is selecting by class, yet your checkboxes have an id. If there are multiple checkboxes you should change the id to class so you don't end up with duplicates.
echo "<div class='checkbox'>"
. "<label>"
. "<input class='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description"
. "</label>"
. "</div>";
You should use the input name instead of the class to select it using jQuery
$("input[name='selectFemaleServices']:checked").each(function() {
I think this will help, the included fiddle shows how it does populate the array. You might need to change the way in which it is adding / or add remove functionality, but this will get you the value in the array
var femaleMatches = [];
$(".selectFemaleService").click(function() {
if($(this).is(':checked')){
console.log('found a female');
femaleMatches.push($(this).val());
console.log(femaleMatches);
}
});
http://jsfiddle.net/8uZ3e/
try this:
var femaleMatches = [];
$(".selectFemaleService").each(function() {
if(this.checked){
console.log('found a female');
femaleMatches.push(this.value);
}
});
http://jsfiddle.net/JPvwJ/
Is there any way I can select a certain value in a dropdown list and according to that selection display a second dropdown list?
I know how to do it with just normal words, but what if I use variable names?
University Name: <select name="university" id="university">
<?php
while($row = mysql_fetch_array($uniName)) {
echo "<option>" . $row['uni_name'] . "</option>";
}
?>
</select>
<br/>
Course Name: <select name='course' id='course'>
<?php
while($row = mysql_fetch_array($courseNames)) {
echo "<option>" . $row['course_name'] . "</option>";
}
?>
</select>
So as you can see, in the first dropdown list I've added all the retrieved university names from my database. I did the same for the courses as well.
Now how can I modify the code below:
$(document).ready(function() {
$('#course').hide();
$('#university').change(function () {
if ($('#university option:selected').text() == "Harvard University"){
$('#course').fadeIn('slow');
}
else {
$('#course').fadeOut('slow');
}
});
});
Instead of "Harvard University", I want to put a variable there according to what the user has selected. Something like $university_name and then I'll create a new query and display only the courses belong to a certain $university_name.
As already stated in my comments, I recommend using AJAX to fill the course box.
$.ajax("getCourses.php", {
data: { UID: uid },
type: 'POST',
done: function(result) {
$("#course").html(result);
});
This will fill the select tags with whatever getCourses has for output.
UID would of course be the ID of the university in question.
This page has all the info you need. For further information and examples, Google is your friend :)
In Dreamweaver I have a list box or menu/list.
I am dynamically adding data from an array into it, so when the page loads, I have a list-box with names in.
This is how it looks
<?php
echo "<select name="."username"."id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
Now how do I go about making the listbox executesomething when the user selects something in it?
Because I have three other textboxes, and when the user selects a name in the list box, I want to put that name he selected into a variable (also don't know how I'm going to do that with a list box) and then search through my database and insert some of the data of that person in the textboxes.
So all i need to know is:
How to create that on event click event and
How to put that selected value then in a variable (inside the event)
You can easily execute a javascript function by using something like this:
<select name=".$username."id=".$username." onchange='yourfunction()' >
The following php code generated a select field with a dynamic number of options.
<?php
$user_array = Array("Smith", "John", "Bob", "Jake");
echo "<select name="."username"." id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
The following JavaScript handles change events on the select element.
$(document).ready(function() {
var username = $('#username');
var selectedValue = null;
username.change(function(){
alert(username.val());
selectedValue = username.val();
});
});
Very simply, I have one dropdown menu dynamically populated with data:
SQL Code
$querycourse = "SELECT course, COUNT(course) AS count FROM acme WHERE course IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
PHP Code
echo "<select name='course[]' value='' multiple='multiple' size=10>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
What I need is another dropdown that is populated with data based on a selection from the first dropdown box.
I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. I have no experience in Ajax.
Would anyone be kind enough to point me in the right direction?!
Thanks in advance, as always,
Homer.
First and Best Method (If you have or may have enough option specific data)
Use AJAX. It is the easiest way, I think, compared to the other ways to implement the same. Use Jquery to implement AJAX. It makes AJAX a piece of cake! Here I share my piece of cake for you -
Following is roughly the complete code you need -
Call a javascript function populateSecondDropdown() on your first select like this -
echo "<select name='course[]' value='' multiple='multiple' size=10 onchange='populateSecondDropdown(this, 'http://yourprojectUrl','Any Subject');'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
Define an ajax call inside inside the populateSecondDropdown() function -
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
function populateSecondDropdown(object,baseUrl)
{
$.ajax({
type: "POST",
url: baseUrl+"/ajax/fetchOptions.php",
data: { id_option: $(object).val(), operation: 'get_subjects' },
dataType: "json",
success: function(data)
{
//Clear options corresponding to earlier option of first dropdown
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data.subjects, function()
{
$('select#secondDropdown').append('<option value="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+'</option>');
});
$('select#secondDropdown').focus();
},
beforeSend: function()
{
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Loading...</option>');
},
error: function()
{
$('select#secondDropdown').attr('disabled', true);
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">No Options</option>');
}
});
}
</script>
And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. You can use $_POST['id_option'] here to fetch the options under it. The database query here should fetch the option_id and option_name fields for every option (as expected by the jquery code inside $.each) and return a json encoded array like this:-
return json_encode(array("subjects" => $resultOfQuery));
Second Method (Using only javascript)
Fetch all the data for the second dropdown grouped by the field of the first dropdown. E.g. let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd
Create all the options of the 2nd dropdown. Assign classes equal to the courses while creating the options like this:-
$querycourse = "SELECT course, subject FROM subjects WHERE subject IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
echo "<select name='subjects[]' value='' multiple='multiple' size=100>";
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[subject]\" class=\"$ntc[course]\">\"$ntc[subject]\"</option>";
}
echo "</select>";
Then define onchange="displaySubjectsUnderThisCourse(this);" for the first dropdown and write this javascript :-
function displaySubjectsUnderThisCourse(object)
{
var selectedCourse = $(object).val();
//Display the options with class = the selected option from first dropdown
$("."+selectedCourse).removeClass("hidden"); //define a class hidden with display:none;
$('option:not(.selectedCourse)').hide(); // hide all options whose class is other than selectedCourse - Not sure whether this will work or not, though
//Deselect any previous selections
//If single option selection is allowed
$('select#secondDropdown option').attr('selected', false);
// or following if multiple selection is allowed (needed for IE)
$('select#secondDropdown option').attr('selectedIndex', -1);
}
The basic idea here is to hide/display option groups but my code may have errors.
Finally, please note, the second method (fetching all the option values) would be better only if you have limited small amount of data and are very sure there will always be less data in future. But, since nobody can be so certain about the future, it is advisable to use the AJAX method always.
There are two methods:
First, you can load all choices for
the second select list into a
JavaScript array. When an option is
selected in the first select,
populate the second with the
appropriate options.
Second, you can use Ajax to make a
call to the server and fetch the
options for the second select based
on the choice of the first. The
server would then return a list of
options (one per line, tab delimited
is how I do it) that you parse and
use to populate the second select.
The first option is very fast and easy, but may take a while to load if you have a large list of options for the second select.
The second option is more complicated, but much more flexible.
Here's some Ajax code to get you started:
Create a request:
var HTTP_UNINITIALIZED = 0;
var HTTP_SETUP_NOTSENT = 1;
var HTTP_PROCESSING = 2;
var HTTP_PARTIAL_RESULT = 3;
var HTTP_COMPLETE = 4;
function createRequest()
{
var request = null;
try
{
request = new XMLHttpRequest();
}
catch( failed_once )
{
try
{
request = new ActiveXObject( "Msxml2.XMLHTTP" );
}
catch( failed_twice )
{
try
{
request = new ActiveXObject( "Microsoft.XMLHTTP" );
}
catch( failed_thrice )
{
request = null;
}
}
}
return( request );
}
Send the request:
var request = createRequest();
function doSearch( value )
{
getURL = "<url to get list>?Value=" + value;
request.open( "POST", getURL, true );
request.onreadystatechange = showResults;
request.send( null );
}
Use the results:
function showResults()
{
if( request.readyState == HTTP_COMPLETE && request.status == 200 )
{
if( request.responseText != "" )
{
var lines = request.responseText.split( "\n" );
for( i = 0 ; i < lines.length ; i++ )
{
var parts = lines[i].split( "\t" );
// populate the second select
}
}
}
}
How you handle the server side portion is up to you.