So to continue my last question (link). I've finally got that sorted out (with help), but now the value of the name is only the first value of the drop down list.
A brief explanation, I have 2 drop down menu's and when you select a option from one (A) the other drop down menu is updated (B). I know it has something to do with an array but I can't figure this out.
Here are my files.
HTML
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<?php
$sttub = str_replace('&', 'en', $stub);
$q = $row["Categorie"];
echo "
<option class='dropdownmenu_A' value='".$sttub."' name='".$q."'>"
.$row["Categorie"]."
<span style='font-size:1.2rem;color:#F8F8F8;'>
(" . $row['x'] . ")
</span>
</option>
";
}}?>
</select>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
JavaScript
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
var $mainName = $(".dropdownmenu_A").attr("name");
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat + '&main_name=' + $mainName,
success:function(results)
{
// alert(results);
console.log($mainCat,$mainName);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
function.php
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$q = $_POST['main_catid'];
$x = $_POST['main_name'];
echo '<option value="-1" selected="selected">'.$x.'</option>'.$option;
die();
} // end if
}
I have tried using <select id="main_cat" name="main_cat[]"> like I found on google but this didn't work. Using $x[] = $_POST['main_name']; just echos the word Array. How do I get this to work and display the correct option that is selected and not just the first every time.
To be clear, here are my drop down menu's (sometimes my brain goes faster then I can type, so I hope it's clear).
select{height:30px}
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_A' value='option-1' name='Option 1'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
</select>
<select id="sub_cat" name="sub_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_B' value='sub-option-1' name='Sub Option 1'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
</select>
So right now if I select Option 1 from dropdownmenu_A it only echo's the first value from dropdownmenu_A to dropdownmenu_B and not Option 2 or Option 3.
1- You can't have <span/> tags inside <option/> tags as the latter cannot have any child elements.
2- <option/> doesn't have a name attribute. If you want to create a custom attribute, use HTML5 data attributes. That's what they are for.
3- printf is your new friend.
printf('<option class="dropdownmenu_A" value="%s" data-name="%s">%s (%s)</option>', $sttub, $q, $row["Categorie"], $row['x']);
4- I believe the problem is $(".dropdownmenu_A").attr("name") as this would always pull the same name and not the selected name. In your particular case, I would do
$(function(){
$('#main_cat').change(function(){
var $option = $(this).find('option:selected'),
id = $option.val(),
name = $option.data('name');
// open your browser's console log and ensure that you get the correct values
console.log(id, name);
$("#sub_cat").empty();
// call ajax
$.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data: {
action: 'my_special_ajax_call',
main_catid: id,
main_name: name
},
success: function (results) {
$("#sub_cat").removeAttr('disabled').html(results);
}
});
});
});
You should add a selected attribute to your selected option:
https://www.w3schools.com/tags/att_option_selected.asp
Related
I using Datatable library to show a table in wordpress custom plugin where I need to return selectbox input. The select box option should display the option as it is saved in database but it is showing the first option always.
How to code the same thing in js when the select input is returned for a column in datatable. I have tried the following way:
columns: [{
{
'data': null,
'render': function (data, type, row, meta) {
return '<select class="selectpicker" name="pm" id="pm-' + row.mls + '"><option value="Tafolla">Tafolla</option><option value="Lucy">Lucy</option></select>';
}
},
}]
Well first get the JS value that is selected then based off return call the php value in a separate call not inlineHTML . Try not overcomplicate cross language calls ...
document.getElementById('my-select').addEventListener('change', function() {
console.log('You selected: ', this.value);
//Call PHP values based on selection e.g
if(this.value == 2)
{
var text = " <?php echo ($row['status'] == 'AR')?'selected='selected':''; ?>";
}
});
<select id="my-select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
The other way of doing it is in plain php with HTML select
<select name="formGender">
<option value="">Select...</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
//PHP
<?php
if(isset($_POST['formSubmit']) )
{
$varGender = $_POST['formGender'];
}
?>
I have 2 drop down menu, let it be:
<select name="" id="district" onchange="selectbyDistrict()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
And for Next drop down menu, I have to retrive from database and display according to the selected values of above options
I use script as
$('#district').change(function(){
var value = $('#district').val();
$.get('get_ajax.php', {id:value}, function(data){
$('#new_location').html(data);
});
});
In get_ajax.php code var_dump($_GET); display nothing.
So How to complete this. Please Suggest me
Many Thanks in Advance
<select name="" id="district" onchange="selectbyDistrict(this)">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
Now Right the code for onchange Event And also include the ajax
function selectbyDistrict(obj){
var selectedValues = obj.value;
$.ajax({ method: "POST",
url: "district_subpart.php",
data: {'district':selectedValues}
}).success(function( msg ) {
// this is place you can right where you want to display
});
}
Now on the php File You right the code
district_subpart.php
$district = $_POST['district'];
// Mysql Connect Here
mysql_connect("hostname","mysql_username","mysql_password");
mysql_select_db("database_name");
$sql = "select * from district_subpart where district_id = ".$district;
$results = mysql_query($sql);
while($row=mysql_fetch_array($results)){
// right here code
}
die;
Is there any function to set value of a <select> tag option? I have an ajax response array and I want to put this array in a <select> tag.
This is my code :
$.ajax({
type: "GET",
url: "http://.......api/1/AbsenceType",
dataType: "json",
success: function (data) {
// It doesn't work
var ind = document.getElementById('mySelect').selectedIndex;
document.getElementById('mySelect').options.value="2";//
}
})
And my select tag is :
<select id=mySelect name="mySelect" required="required" data-mini ="true" onchange="myFunction3();"/>
<option id ="type" value=""></option>
</select>
I have an ajax response array and I want to put this array in a tag.
Why don't you just add the options from the array to the select, then set the selected value, like this :
Start with an empty select :
<select id="mySelect" name="mySelect">
</select>
Then use this function as a callback :
var callback = function (data) {
// Get select
var select = document.getElementById('mySelect');
// Add options
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
// Set selected value
$(select).val(data[1]);
}
Demo :
http://jsfiddle.net/M52R9/
See :
Adding options to a select using Jquery/javascript
Set selected option of select box.
try this...
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>`
</select>
$("select").val("3");
visit live demo here: http://jsfiddle.net/y4B68/
thank you
Are you looking for something like that -
DEMO
You can add option like this -
$(function(){
$("#mySelect").html('<option value="2">2</option>');
});
Sorry i just missed that you are doing it in ajax callback. i have also updated in my demo.
you can also this too-
document.getElementById("mySelect").innerHTML = '<option value="2">2</option>';
Why don't you add new option instead of adding a value in option.
A dropdown select box is populated from a database and the selected option is matched against a variable $comp_cntry currently on the page:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
Then later on a telephone prefix (dialling code) box is populated from the same database, matching the dialling code to the country:
<?php
// Get Dialling Codes
$telephone_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country = $tq['country_name'];
// Show Prefix
if ($country == $comp_cntry) {
$prefix = $tq['dialling_code'];
}
}
?>
<input type="text" name="telephone_prefix" value="+<?=$prefix?>" readonly>
How, using JavaScript, can I get the telephone prefix to automatically change on page when a new option is chosen from the country dropdown? I have no real knowledge of JavaScript at all, unfortunately, but assume I would need to somehow convert my PHP associated array in to JSON so that I can use it?
I know I haven't provided any JavaScript code to show that I've made a start on this part of the problem, but if someone could point me in the right direction that would be swell.
Disclaimer: please ignore my terrible use of the mysql_ extension
I would add a data attribute (here it might be called data-prefix) to the element, like
<option value='country' data-prefix='+44'/>
and get this when the onChange event is fired for the select. In jQuery you could do something like
$('[name="country"]').change(function(){
$('[name="telephone_prefix"]').val($(this).find(':selected').data('prefix'));
});
which would update the value accordingly.
I would say the best way of doing this would be joining the two PHP codes like this:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $cq['dialling_code'];
// Select Current Country
echo "<option data-prefix='{$prefix}' value='{$country}' ";
if($country == $comp_cntry) echo "selected";
echo ">{$country}</option>";
}
?>
</select>
<input type="text" name="telephone_prefix" value="" readonly>
And this would return a list of the countries in a dropdown each with a data-prefix attribute of the appropriate prefix that they have.
We would then need to trigger jQuery on change and update the value, and this would look something like:
$("select[name=country]").on('change', function() {
var prefix = $("option:selected", this).attr('data-prefix');
$("input[name=telephone_prefix]").attr('value', prefix);
})
And this would have the following effect: http://jsfiddle.net/Tm75y/1/
I hope that's what you need.
Simply pass the prefix as an attribute of the select options:
<select id="country-select" name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $tq['dialling_code'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" prefix="<?=$prefix?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
<input id="prefix-input" type="text" name="telephone_prefix" value="" readonly>
JAVASCRIPT
Then add a change handler to your select to get the prefix attribute of the selected option and set the text input:
$(function(){
$("#country-select").change(function(){
var prefix = $(this).find("option:selected").attr("prefix");
$("#prefix-input").val(prefix);
});
});
My suggestion would be to saving a javascript object which maps countries to phone codes, so when your country select has a change, you can trigger a change to the telephone prefix via javascript.
So let's assume you have a map (associative array) in javascript that is something like this:
$country_to_phone_prefix_map = array(
'country name A' => 'phone prefix A',
'country name B' => 'phone prefix B',
...
);
This could be built in your query while loop:
$country_to_phone_prefix_map = array();
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country_to_phone_prefix_map[$tq['country_name']] = $tq['dialing_code'];
}
Then when rendering the page, inject this map into javascript
<script type="text/javascript">
var countryToPhonePrefixMap = <?php echo json_encode($country_to_phone_prefix_map); ?>;
</script>
Now, you build a change event listener on the country dropdown to change the value:
$('select[name="country"]').change(function() {
// get phone prefix from map
var selectedCountry = $(this).val();
var phonePrefix = countryToPhonePrefixMap[selectedCountry];
// change value of telephone prefix input
$('input[name="telephone_prefix"]').val(phonePrefix);
}
I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});