Set Option Value as Select text - php

Need assistance
I need to have a select function where as
<select class="form-control">
<option value="4100">4100 : Mass Collections</option>
<option value="4200">4200 : Stole Fees</option>
<select>
now I don't want to include the code description after selecting an option, it should be code only appearing on the select box like this.
I have tried this Jquery script
$('select').change(function() {
var code= $('option:selected',this).text().split(' : ');
$('option:contains('+code[0]+')',this).val(code[0]);
})
but every time I do this checking in dropdown the option omitted the description entirely. How do I prevent this.
thanks in advance

You can follow the idea of this answer: add the description only when the element have focus:
$('select').on("focus", function(s) {
for (var o of this.options) {
o.textContent = o.getAttribute('value') + ': ' + o.dataset.descr;
}
});
$('select').on("blur", function(s) {
for (var o of this.options) {
o.textContent = o.getAttribute('value');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control">
<option value="4100" data-descr="Mass Collections">4100</option>
<option value="4200" data-descr="Stole Fees">4200</option>
<select>

This is the best that I could do.
$(document).ready(function (){
$('select').change(function(s) {
for (var option of this.options) {
option.label = option.text;
};
this.selectedOptions[0].label = this.selectedOptions[0].value;
});
});
Better to check it with more options,
<select class="form-control">
<option value="4100">4100 : Mass Collections</option>
<option value="4200">4200 : Stole Fees</option>
<option value="4300">4300 : Something Else</option>
<select>

Related

build conditional select with codeigniter form helpers

I am trying to create two dropdown lists with the condition, that the second one should show the list based on the value, selected in the first one.
1st is city.
2nd is district within the city.
Both lists are populated from the database.
Here is an example
<td>City:</td>
<td>
<?=form_dropdown('contact_city', $sel_city, set_value('contact_city'), "class='select2'"); ?>
</td>
<td>District:</td>
<td >
<?=form_dropdown('contact_district', $sel_contact_district, set_value('contact_district'),"class='select2'"); ?>
</td>
$sel_contact_district should be reloaded and list selection updated after city value is changed.
Which approach should I use?
Using ajax you could populate the second dropdown based on the value of the first. Would look something like that:
$("#cityDropdown").on('change', function(){
$.post('api/listdistrictsfromcity',
{ city_id : $(this).val() },
function(response){
var $district_dropdown = $("#districtsDropdown").empty();
$.each(response, function(i, item){
$district_dropdown.append("<option value='" + item.value + "'>"+ item.text +"</option>");
});
});
});
Select2 supports methods that allow programmatic control of the component.
// var $example = $(".js-example-programmatic").select2();
$('body').on('click', '.select2', function(e) {
//var select_name = $(this).attr("your_select2_name");
$(this).val("your_option").trigger("change");
});
You can also add options like this:
$('.select2').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
3rd Edit:
As you mention in your question that you need to select the option on the select dropdown to depend on the first dropdown selected option.
Here is the Two select box which changes the option depending on the first select box.
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>

retrieving values from selected option to another select

I'm trying to write this code to retrieve data from the first Select option to the second Select:
Fist Select:
<select name="league">
<option value="0">------------Please Select League-------</option>
<?php
$sql_league="select * from ".$prev."league";
$re_league=mysql_query($sql_league);
while($d_league=mysql_fetch_array($re_league))
{
?>
<option value="<?=$d_league['id']?>" <?php if($_SESSION['id']==$d_league['id']){?> selected="selected" <?php }?>><?=$d_league['title']?></option>
<?php
}
?>
</select>
Second Select:
<select name="team">
<option value="0">------------Please Select team-------</option>
<?php
$sql_team="select * from ".$prev."team where leagueID=".$d_league['id']."";
$re_team=mysql_query($sql_team);
while($d_team=mysql_fetch_array($re_team))
{
?>
<option value="<?=$d_team['id']?>" <?php if($_SESSION['id']==$d_team['id']){?> selected="selected" <?php }?>><?=$d_team['title']?></option>
<?php
}
?>
</select>
Second Select should depend on the selection from the first Select (If I chose League1, the Second select options should show teams assigned to that league).
any Ideas how to make this work?
try this
<select name="league" onChange="bindSecondSelect()">
<option value="0">select</option>
// your php code
</select>
<select name="team">
// your php code
</select>
<script type="text/javascript" src="jquery-1.7.js"></script>
<script type="text/javascript">
function bindSecondSelect()
{
if($('[name="league"]').val() != "0")
{
$('[name="team"]').find('option').css('display','none');
$('[name="team"]').find('option[value="'+$('[name="league"]').val()+'"]').css('display','block');
}
}
</script>
Send an ajax request to a function with the first select value. This function should get the details of that value and returns the details to the browser. Use that details and append it into the second select.
I have created a little fiddle for you http://jsfiddle.net/TqKG3/3/.
I have used some default values to demonstrate, you will have to use ajax call and return json.
For eg :
$("#opt_leg").change(function () {
$("#opt_mem").find('option').remove();
var url = "your_url.php?league_id=" + $(this).val();
$.get(url, function(data){
var list = jQuery.parseJSON(data);
$.each(list, function (i, item) {
$("#opt_mem").append("<option value=\"" + item.id + "\">" + item.name + "</option>");
});
});
});

Ajax call for dynamic menu works for first <select> element, but not additional ones

i'm trying to create a dynamic menu with jquery, and I want to populate the subsequent menu with Ajax data (taken from a DB).
I then want to be able to add additional dropdowns and retain the same functionality. I have it working for a single drop down and the ajax call is working, but it wont work for additional dropdowns that are addded via jquery (Repeat) function.
I dont think that I need to add a counter variable to the php as I'm handling the incrementation in the jquery, but I just cant get the input from the additional dropdowns (the ones that go into (.additionalsubj') into the Ajax - i cant even get them to show in Firebug.
I'm a bit stuck - any thoughts would be massively appreciated.
HTML:
<h3>Primary Subject</h3>
<div class="subjselect">
<div class="select">
<select id="subject">
<option value="">Subject</option>
<option value="math">Math</option>
<option value="science">Science</option>
<option value="languages">Languages</option>
<option value="humanities">Humanities</option>
<option value="econ">Economics/Finance</option>
<option value="gmat">GMAT</option>
<option value="sat">SAT</option>
</select>
<select id="topic">
<option value="">Topic</option>
<option value="math">Math</option>
<option value="science">Science</option>
<option value="languages">Languages</option>
<option value="humanities">Humanities</option>
<option value="econ">Economics/Finance</option>
<option value="gmat">GMAT</option>
<option value="sat">SAT</option>
</select>
</div>
</br>Add Another Subject
</div>
Jquery:
var counter=1;
$(document).on('change', 'select#subject'+counter+'', function(){
var subject = $("select#subject"+counter+">option:selected").text();
var selector=$("select#subject"+counter+"");
console.log(selector);
console.log(subject);
$.ajax({
type: 'GET',
url: 'tutorprofileinput.php',
data: {"subject": subject},
dataType:'json',
success:function(data){
console.log(data);
var options = [];
$.each(data, function (key, val) {
options += '<option value="' + val.topic + '">' + val.topic + '</option>';
console.log(options);
});
$("select#topic").html(options);
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
});
function Repeat(obj){
counter++;
console.log(counter);
var selecoptions = '<div class="select"><select id="subject'+counter+'"><option value="">Subject</option><option value="math">Math</option><option value="science">Science</option><option value="languages">Languages</option><option value="humanities">Humanities</option><option value="econ">Economics/Finance</option><option value="gmat">GMAT</option><option value="sat">SAT</option></select></div><div class="select"><select id="topic'+counter+'"><option value="">Topic</option></select></div>';
$('.additionalsubj').append(selecoptions);
console.log($('.additionalsubj'));
}
and the PHP getting the data from the database:
<?php
include("php_includes/db_conx.php");
if (isset($_GET['subject'])){
$subject = $_GET['subject'];
$query = ("SELECT subject.id, topic FROM topics, subject WHERE subject='$subject' AND subject.id=topics.subjID ORDER BY subject");
$result = mysqli_query($db_conx, $query);
$rows = array();
while($r = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $r;
}
echo json_encode($rows);
exit();
}
?>
Use
$(document).on('change','select[id^=subject]',function(){
because you are adding counter which is set to one by default so i don't think its even work for first select box.
So use above code that will work for all selects whose id starts with subject.

Pass option select variable with jquery

Noob here trying to do something simple with Jquery. Basically I have a small select-option dropdown like this:
<select onchange="javascript:swapContent('con3');">
<option>selection 1</option>
<option>selection 2</option>
<option>selection 3</option>
</select>
Currently it is posted via ajax to a $php variable here:
$contentVar = $_POST['contentVar'];
javascript function is here:
<script language="JavaScript" type="text/javascript">
function swapContent(cv) {
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "myphpscript.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#myDiv").html(data).show();
});
}
</script>
How can I instead post the value of the select-option dropdown?
I realize this is basic, but I have to start somewhere and cannot find a tutorial that shows me how to do what I need. Thank you for your help.
How can I instead post the value of the select-option dropdown?
If you want to send values yo tour script you should start by giving values to your option elements (and an id to your <select> element to be able to use it and retrieve the selected value):
<select onchange="javascript:swapContent('con3');" id="myselect">
<option value="value1">selection 1</option>
<option value="value2">selection 2</option>
<option value="value3">selection 3</option>
</select>
and then:
// get the currently selected value from the dropdown
var value = $('#myselect').val();
$.post(url, { contentVar: cv, selectedValue: value }, function(data) {
$("#myDiv").html(data).show();
});
If on the other hand you wanted to send the text of the selected option you could use this:
// get the currently selected value from the dropdown
var text = $('#myselect option:selected').text();
$.post(url, { contentVar: cv, selectedText: text }, function(data) {
$("#myDiv").html(data).show();
});
Now inside your PHP script you could fetch the value:
$_POST['selectedValue']
HTML:
Remove the inline javascript change event from the select.
<select>
<option>selection 1</option>
<option>selection 2</option>
<option>selection 3</option>
</select>
jQuery:
Bind a change event to your select. Inside this event, this.value with be the value of the select.
$(document).on("change", "select", function(){
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "myphpscript.php";
$.post(url, {contentVar: this.value} ,function(data) {
$("#myDiv").html(data).show();
});
});
var val = $('select option:selected').text();
Using jQuery's selector syntax, you first select the "select" control, and then the "option" child of the select control. You then look for the selected state. Finally, return the text.
Of course, as is, this code will select every "select" control on the page. It would be better to give your select control an id:
<select id="mySelect">
<option>Some option</option>
<option>Some other option</option>
</select>
Then the code becomes
var val = $('#mySelect option:selected').text()
You might want to consider an unobtrusive JavaScript approach and not have the on-change event in your html mark-up, instead attach an event handler as shown below, from the jQuery API site
<!DOCTYPE html>
<html>
<head>
<style>div { color:red; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select name="sweets">
<option>Chocolate</option>
<option>Candy</option>
<option>Taffy</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
</script>
</body>
</html>

Related dropdown using javascript and php

I have this script and I want to get the value of drop down select list in the PHP and check the if (jws1 != "") then show 1 to 10 value in the second drop down box using of for loop...
JavaScript code:
<script language="javascript" type="text/javascript">
function test()
{
var e = document.getElementById("JWSections");
var Sections = e.options[e.selectedIndex].value;
alert(Sections);
}
</script>
HTML code:
<select name="JWSections" id="JWSections" onchange="test();">
<option value="">Select Sections</option>
<option value="jws1">Section 1.1</option>
<option value="jws2">Section 1.2</option>
<option value="jws3">Section 1.3</option>
<option value="jws4">Section 1.4</option>
</select>
I want to get the value like jws1, and check in the PHP.
For PHP to be able to do anything with your HTML form data, you'll have to submit it to PHP.
You can either submit the form itself or use AJAX to pass in the value of jws1 and build the options from the result. Jquery is pretty good with doing that kind of thing, all you gotta do is set your AJAX request's data type to HTML and assign the data from the "success" callback to your destination drop down list.
<select name="JWSections" id="JWSections" onchange="test(this);">
<option value="">Select Sections</option>
<option value="jws1">Section 1.1</option>
<option value="jws2">Section 1.2</option>
<option value="jws3">Section 1.3</option>
<option value="jws4">Section 1.4</option>
</select>
<select name="JWSections" id="secondDropDown"> </select>
<script language="javascript" type="text/javascript">
function test(dropdown)
{
var selectedjws = dropdown.options[dropdown.selectedIndex].value;
var secondDropDown = document.getElementById('secondDropDown');
$.post('path', { selectedjws : selectedjws }, function(key, value){
// Remove all options from second dropdown
for(var i = 0; i < secondDropDown.options.length; i++){
secondDropDown.remove(i);
}
// Add options by key value pair returned from server
secondDropDown.add(new Option(value, key))
});
}
</script>
jsfiddle: http://jsfiddle.net/KTq6y/1/

Categories