I have written a jquery code for the following purpose:
There is a list of Fields, and a list of sub-fields. When user clicks on a field, the relevant subfields would be shown. Both lists are multiple-enabled <select>.
HERE IS THE JS FIDDLE (exploring it with FF it works, yet with chrome fails)
http://jsfiddle.net/mostafatalebi/WUR7F/
I use the most recent versions of Chrome, Firefox, and IE8. This code works fine for Firefox but fails in the other two.
Here is the jquery code:
$(document).ready(function(){
$('select[name="branch[]"]').change(function () {
var $branch = $(this).children(':selected'),
$subbranch = $('[name="subbranch[]"]').children('option');
$subbranch.hide()
$branch.each(function () {
var branch = $(this).val();
$subbranch.each(function () {
if ($(this).attr("id") == "par"+branch) {
$(this).show();
}
});
});
}).change();
});
And here is the HTML (for Mother-Fields) which the jquery is applied to:
<option selected value="false">Please Select the Field:</option>
<?php
$db->where("parent", 1);
$db->where("type", 1); // means institute
$branches = $db->get("fields")->result_array();
$brancc = count($branches);
for($i=0; $i < $brancc; $i++)
{
?>
<option class='branch-item' value="<?php echo $branches[$i]['id']; ?>" >
<?php echo $branches[$i]['title']; ?></option>
<?php
}
?>
</select><br />
And here is the HTML (Child-Fields) to which jquery is applied:
<select multiple class="form-option-multiple" name="subbranch[]">
<?php
$db->where("parent", 0);
$db->where("type", 1); // means institute
$suboptions = $db->get("fields")->result_array();
$suboptionscc = count($suboptions);
for($i=0; $i < $suboptionscc; $i++) {
?>
<option class='subbranch-item' id='par<?php echo $suboptions[$i]['parent_id']; ?>'
value="<?php echo $suboptions[$i]['id']; ?>" ><?php echo $suboptions[$i]['title']; ?></option>
<?php
}
?>
</select>
<br />
Both lists are initially filled with the data retrieved from Database.
Two things:
dozens of your subbranch-options have the same DOM id. DOM ids are supposed to be unique in the document. I've changed your code to use a class instead: jsFiddle
if ($(this).hasClass("par"+branch)) {
The problem is that you are trying to hide options in a multiselect by setting display: none. Both Chrome and IE do not support that. You will have to add and remove options instead.
I've build a second fiddle that does that: jsFiddle
I added a third, invisible select that holds all your generated options. Whenever the user changes the branch, we clear the subbranch select and copy all the matching options from the hidden third into it.
Why do you have the two instances of .change() first of all?
Isn't that redundant? That could be resetting your on change event also.
Because this is the real issue... rather than:
$('select[name="branch[]"]').change(function() {})
For compatibility, you need to use:
$('select[name="branch[]"]').on('change', function() {})
Here is another problem. This code needs to be moved out the each() it is in:
var branch = $(this).val();
And because the selects are multi-selects, this code will not work:
if ($(this).attr("id") == "par"+branch) {
$(this).show();
}
Sometimes branch will be multiple values.
This works in Chrome: http://jsfiddle.net/digitalextremist/3rzLs/
Check that out to see extreme changes needed to solve all your problems:
$(document).ready(function(){
$('select[name="branch[]"]').on('change', function() {
var $branch = $(this).children(':selected'),
$subbranch = $('#suboptions').children('option');
$('[name="subbranch[]"]').empty()
var branch = $(this).val();
console.log( branch )
$branch.each(function () {
$subbranch.each(function () {
if ( branch.indexOf( $(this).attr("id").replace("par","") ) >= 0) {
$('[name="subbranch[]"]').append( $(this).clone() ).show();
}
});
});
}).change();
});
With HTML:
Selecting on any Box of Parents' item should show a list related to the parent in Box of Children
<label>Box of Parents</label>
<select id="branches" class="form-option-multiple" name="branch[]" multiple="">
<option selected="" value="false">لطفا زمینه فعالیت خود را انتخاب نمایید</option>
<option class="branch-item" value="14">
هنرهای دستی</option>
<option class="branch-item" value="15">
کامپیوتر</option>
...
</select>
<!-- Then here is the second Child --><br/>
<label>Box of Parents</label>
<select size="9" multiple="" class="form-option-multiple" name="subbranch[]">
</select>
<div id="suboptions" style="display: none">
<option style="display: none;" class="subbranch-item" id="par14" value="40">قالیبافی</option>
<option style="display: none;" class="subbranch-item" id="par14" value="48">نقاشی</option>
<option style="display: none;" class="subbranch-item" id="par14" value="49">گرافیک</option>
...
</div>
Related
I have a DIV element as drop-down in PHP as below:
<div id="files" value="fileselect" selected="selected">Choose Folder1
<input type="hidden" name="test" id="hiddenfield" />
</div>
<div id="files2" value="fileselect2" selected="selected">Choose Folder2
<input type="hidden" name="test2" id="hiddenfield2" />
</div>
Now I try to get the value of selected option as follows:
<?php $content = ?>
<script type = text/javscript>
document.getElementById("files").value;
</script>
<?php echo $content; ?>
but I get unknown variable $content error.
And, I tried to create 'change' event handling in DIV element as follows:
$(document).ready(function()
{
//Bind a change event to the folder selector
$("#files").change(function()
{
var dir = $(this).val();
// Get file names in directory dir and pass it to the next drop-down DIV
$.get("listfiles.php", {"dir":dir}, function(response){
//Show the files
$("#files2").html(response);
//alert($('#files2 option:selected').val());
alert(response);
$(response).appendTo('#hiddenfield2');
});
});
});
But this doesn't help passing the 'response' to the second DIV "files2".
I need to use the two DIVs like dependent drop-down lists. I make the dropdown-list "selection1" interact with DIV "selection2" like dependent dropdowns as follows:
<select name="field1" id="selection1">
<option selected="selected" name ="selection1">Folder 1</option>
<?php
$selections = array('Folder A', 'Folder B', 'Folder C');
foreach($selection as $selections){
?>
<option value="<?php echo strtolower($selection); ?>"><?php echo
$selection; ?></option>
<?php
}
?>
</select>
$("#selection1").change(function()
{
var dir = $(this).val();
$.get("listdirs1.php", {"dir":dir}, function(response){
//Show the files
$("#files").html(response);
// alert($('#selection2 option:selected').val());
//alert(response);
$(response).appendTo('#selection2');
});
});
But this doesn't work in case both "selection1" and "selection2" are DIVs.
I already referred to how to submit a div value in a form stackoverflow answer
I am all new to PHP and JavaScript. Please help. Thanks in advance.
I am using PHP to dynamically populate a select box (a list of equipment). The value is set with the ID of the item selected so I can use it later in my programming.
What I need help with...
Based on the item selected I need to show/hide one of two form fields but I can't use the value as this is the id.
What I need to be able to do is read the text in the select box which will contain the item name with either (Service: Set by dates) or (Service: Set by hours) and show either the form field for the date or the form field for the hours?
Is this possible? I can find loads great resources based on the value but not on the text in the select.
I think something like this should work but not sure how to use the text in the select rather than the value.
$(function() {
$('#system').change(function(){
$('.system').hide();
$('#' + $(this).val()).show();
});
});
Any help would be greatly appreciated!!!!
Regards
Matt
(N.B this is what I'm working with at the mo based on the answers so far, thank you all so much for the help (and for your example Louys Patrice Bessette) - not quite there yet... I was getting an error and managed to track it back to the script not getting the result from the select box. See below now working code! Thanks all!!!
<div class="col">
<div class="form-group">
<label for="system_select">Equipment or System to be serviced</label>
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name; ?></option> <?php
}
?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$("#due_dates").hide(); // Hide both divs
$("#due_hours").hide(); // Hide both divs
$('#system_select').change(function(){
var dataType = $(this).find(':selected').attr('data-type') // should be "Set by dates" or "Set by hours"
if (dataType == 'Set by dates') {
$("#due_hours").hide();
$("#due_dates").show();
} else if (dataType == 'Set by hours') {
$("#due_dates").hide();
$("#due_hours").show();
}
});
});
</script>
<div class="row">
<div class="col-md-3" id="due_date">
<div class="form-group">
<label for="service_date">Next Service (Set by dates)</label>
<input type="date" class="form-control" name="service_date" id="service_date" value="<?php echo escape(Input::get('service_date')); ?>" autocomplete="off">
</div>
</div>
<div class="col-md-3" id="due_hour">
<div class="form-group">
<label for="service_hours">Next Service (Set by hours)</label>
<input type="number" class="form-control" name="service_hours" id="service_hours" value="<?php echo escape(Input::get('service_hours')); ?>" autocomplete="off">
</div>
</div>
</div>
I think that you PHP $system->service_type; is echoing either "Set by dates" or "Set by hours".
If you echo that in a data attribute like this:
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type; ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name . ' (Service: '. $system->service_type .')'; ?></option> <?php
}
?>
</select>
Then, in jQuery, you could use it like this to decide to show <div id="due_hours" class="col-md-3"> or <div id="due_hours" class="col-md-3">.
$(function() {
$('#system').change(function(){
$('.system').hide(); // I don't know what this is for...
$("div[id=^'due']").hide(); // Hide both divs
var dataType = $(this).data("type"); // should be "Set by dates" or "Set by hours"
var type = dataType.split(" by ")[1]; // should be "dates" ot "hours"
$("#due_"+type).show();
});
});
Now be carefull with the s on dates...
Try this out... Console.log the values to make sure you have the correct one to match the id to show.
;)
If $(".classname").text() is not working you could try to add that info that you need in a "data" attribute.
Something like this ->
<option data-service="service name" class="myClass">15</option>
Using data attributes can give you a lot of freedom on what you can add. You could add lots of information that a normal user cant read (without inspecting element).
Then you would simply do something like this ->
$(".myClass").on("click", function() {
var serviceData = $(this).attr("data-service");
})
You can then do if checks, compare and whatever you need.
EDIT: Or you can use your approach with on.change and get the selected data attr, it would probably be better
If you change your select into something like this:
<select class="form-control" name="system_select" id="system_select">
<option data-hide='#due_date' data-show='#due_hours'>Show Hours</option>
<option data-hide='#due_hours' data-show='#due_date' value="B">Show Dates</option>
</select>
And your jquery like this:
$('#system_select').change(function () {
$($(this).children("option:selected").attr("data-hide")).hide();
$($(this).children("option:selected").attr("data-show")).show();
});
It could work.
I need to implement this js in order to fill in different fields on change event of a select field.
<select class="form-control" name='brands_list'>
<option value="0">Seleziona il produttore</option>
<?php
while ($listabrand=mysqli_fetch_array($brands)){
echo '<option value="'.$listabrand[0].','.$listabrand[1].','.$listabrand[2].'">'.$listabrand['0'].' - '.$listabrand['1'].'</option>';
}?>
</select>
This is the js to implement. I should add a second action that fill in the input field named 'brand_link' assuming the array value [2]:
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
</script>
I made several attempts but without results such as
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
$('select[name="brands_list"]').change(function(){
$('input[name="brand_link"]').val($('select[name="brands_list"] option:selected').text()[2]);
});
Any help?
You can do it all within the one function. The reason your pastebin didn't work is because 1) you aren't operating on the .val() of the selected item (rather the element itself) and 2) you didn't split the value by comma, like you split the .text() by hyphen.
$('select[name="brands_list"]').change(function(){
var $selectedOption = $('select[name="brands_list"] option:selected');
$('input[name="brand_name"]').val($selectedOption.text().split(' - ')[1]);
$('input[name="brand_link"]').val($selectedOption.val().split(',')[2]);
});
$(".form-control").change(function()
{
//alert( this.value );
var sl_value = this.value;
$('input[name="brand_name"]').val(sl_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="brand_name" value="">
<?php $listabrand=mysqli_fetch_array($brands);?>
<select class="form-control" name='brands_list'>
<option value="Seleziona il produttore">Seleziona il produttore</option>
<?php
foreach($listabrand as $brand){ ?>
<option value="<?php echo $brand;?>"><?php echo $brand;?></option>
<?php } ?>
</select>
in first step, get dropdown selected value in jquery on change. And save this value in jQuery variable. And then insert this value in textbox using jQuery. Thanks
I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select name="SearchIn[]" multiple="multiple" onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php
//Loop over the options
for($i=0;$i<sizeof($SearchCriteria);$i++){
?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php
}//!End of looping over search criteria
?>
</select>
<!-- Hidden heading field for search report -->
<input type="hidden" name="Heading" valtue="" />
</div>
in another php file, I have included firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
$Heading = $dat->if_default('Heading', '');
but it only gives me the first option that the user has selected, but I need all of them. How can I get them?
First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3
You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];
$selectedArr = array();
foreach($SearchCriteria as $item) {
if (in_array($item["value"], $SearchIn)) {
$selectedArr[] = $item["display"];
}
}
$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3
2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php } ?>
</select>
<!-- Hidden heading field for search report -->
<input id="heading" type="hidden" name="Heading" value="" />
</div>
<input type="submit">
</form>
<script>
$('#section').on("change", function() {
selectedArray = new Array();
$(this).find("option:selected:not([disabled])").each(function() {
selectedArray.push(this.text);
});
$("#heading").val(selectedArray.join(", "));
});
</script>
3) For a pure JavaScript solution (use the same HTML as above):
<script>
document.getElementById("section").onchange=function(){
selectedArray = new Array();
for (x = 0; x < this.length; x++) {
if (this[x].selected && !this[x].disabled) {
selectedArray.push(this[x].text);
}
}
document.getElementById("heading").value = selectedArray.join(", ");
};
</script>
I have the following Drop Down List in php:
<select id="choice" name="choice" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select><input TYPE = "button" id="addbt" Name = "addbt" VALUE = "Add Pizza">
and I am using the following Jquery:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().insertAfter("#choice");
});
</script>
I am trying to clone the Drop Down List which is attached to an xml file (I managed till here) and add the Jquery necessary so each new drop down list clone has a new id (a single number difference would be enough. Something like choices_00 then choices_01 and so on).
Since I am totally new to Jquery and php I am asking for any advice or help.
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'newid')
.attr('name', 'newname')
.insertAfter("#choice");
});
To ensure you get a new name and id each time, consider adding a class name to the select so you can count how many exist.
HTML:
<select id="choice" name="choice" class="ddl" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select>
JS:
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'choice' + $('.ddl').length)
.attr('name', 'choice' + $('.ddl').length)
.insertAfter(".ddl:last");
});
Otherwise, track how many times the button has been clicked with a global variable (ugh) or data attribute.
I think you are after this: http://jsfiddle.net/ehQan/
$("#addbt").click(function () {
$('#choice').clone().attr( 'id', 'choices_' +$(this).index()).insertAfter("#choice");
});
You can change the id using the jQuery attr() method before you insert it:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().attr('id','Your new id').insertAfter("#choice");
});
</script>
With this code you can push the button as many times as you want:
<script type="text/javascript">
var times = 0;
$("#addbt").click(function () {
times++;
$('#choice').clone().attr( 'id', 'choices_' + times ).insertAfter("#choice");
});
</script>