Showing value data from dropdown in html - php

I created a script which get from my database the states and price of shipping by number of products.
So...I have 2 dropdown, one for quantity and the second one for state.
This is my main php file: http://pastebin.com/U6dncsZ6
This is the second php file (for database connect) - findcity.php : http://pastebin.com/AuEXrnpD
As you see, in my second php file I have this line:
<option value=<?=$row['price']?>><?=$row['title']?></option>
I want to display the shipping price from the database ($row['price'] on the page.
I specify that using "Inspect element" in my browser I can see the prices added as value for the states, like:
<option value="48.11">State</option>
Please help :(
Le: As I stated in a comment, I finally found that like here it's working: jsfiddle.net/Dkn4n/1/
But for some reasons, it's not detected but it's not working in my page, maybe because the value is not set in html, I can't see the values in source, only in "Inspect element". The value is set as I specified above, with $row['price']

Your select statement looks like this on the page:
<select id="provincia">
<option value="10.00">CA</option>
<option value="20.00">NY</option>
</select>
So using javascript/jQuery you can do the following to get the value of the selected option.
$(document).ready(function(){
$("#provincia").change(function(){
alert(this.value);
//do stuff here to set the value where you want it.
});
});
Here's a demo: http://jsfiddle.net/Dkn4n/

Adding to "Chase"s Answer:
$(document).ready(function(){
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
});
and expanding it:
at this line:
document.getElementById('provinciadiv').innerHTML=req.responseText;
do
$("#provincia").change(function(){
$("#selectedprice").html(this.value);
//<div id=selectedprice></div> should show your value
});
again!
Because the "change" binding is gone once you replace the part...

Related

Retrieving .data('value') from <select> "sometimes" works

My select box that is generated by PHP:
<select>
<option selected>Select something</option>
<option data-value="test"></option>
</select>
So far I have tried the following ways to retrieve the value within the data-value attribute:
$('select').children(":selected").data('value');
$('select option:selected').data('value')
$('select option:selected').attr('data-value');
$('select').find(':selected').data('value');
Of course there are a couple of more ways to do this. Once the one of these options gets executed I "sometimes" get the value within the data-value attribute. Even using
$('select').on('change', function () { // code });
gives me the same result. Am I missing some underlying thing?
FIXED:
After every select I use the data information for something else. Then I refresh the select box data by retrieving the remaining data information from the database. At that point I forgot to add the attribute data-value to every option..

how to refresh Select2 dropdown menu after ajax loading different content?

I'm using Select2 in a combination of dropdown menus. I have one menu for "Countries" and one for "States/Provinces". Depending on the country that is chosen, the "States/Provinces" dropdown changes in content. The states/provinces are pulled with ajax from a database and then displayed this way:
$display_output = '<select style="width:350px;" tabindex="2" name="state" id="state" data-placeholder="Choose a Country..."> ';
$display_output .= '<option value="" selected>Select a State</option> ';
while ($state_details = $this->fetch_array($sql_select_states))
{
$display_output .= '<option value="' . $state_details['id'] . '" ' . (($selected_value == $state_details['id']) ? 'selected' : ''). '>' . $state_details['s.name'] . '</option>';
}
$display_output .= '</select>';
So far, so good. All the provinces change correctly, however when it initially loads, the Select2 shows "undefined" for the states dropdown, even though I have it set as
data-placeholder="Choose a Country..."
I'm assuming it could be because on loading, the country selected is "United States" and it populates a list of states but none of them is default or selected. Is there any other way to define a default value so that it doesn't show "Undefined"?
And another (but less important) problem is that when someone chooses "United States" for example, and then chooses "Arizona", if the person then changes to "Canada" as the country, the state of "Arizona" still stays but when opening the dropdown the provinces of Canada are selectable. Is there any way to return it to the default value temporarily when someone selects another country, until a province is chosen again?
My loading code is currently just:
<script>
$(document).ready(function() { $("#state").select2(); });
</script>
Select 3.*
Please see Update select2 data without rebuilding the control as this may be a duplicate. Another way is to destroy and then recreate the select2 element.
$("#dropdown").select2("destroy");
$("#dropdown").select2();
If you are having problems with resetting the state/region on country change try clearing the current value with
$("#dropdown").select2("val", "");
You can view the documentation here http://ivaynberg.github.io/select2/ that outlines nearly/all features. Select2 supports events such as change that can be used to update the subsequent dropdowns.
$("#dropdown").on("change", function(e) {});
Select 4.* Update
You can now update the data/list without rebuilding the control using:
fooBarDropdown.select2({
data: fromAccountData
});
It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.
$('#state').trigger('change.select2'); // Notify only Select2 of changes
select2 has the placeholder parameter. Use that one
$("#state").select2({
placeholder: "Choose a Country"
});
Use the following script after appending your select.
$('#state').select2();
Don't use destroy.
Finally solved issue of reinitialization of select2 after ajax call.
You can call this in success function of ajax.
Note : Don't forget to replace ".selector" to your class of <select class="selector"> element.
jQuery('.select2-container').remove();
jQuery('.selector').select2({
placeholder: "Placeholder text",
allowClear: true
});
jQuery('.select2-container').css('width','100%');
Got the same problem in 11 11 19, so sorry for possible necroposting.
The only what helped was next solution:
var drop = $('#product_1'); // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2'); pick krajee attrs of our elem;
var drop_id = drop.attr('id'); // take id
settings = window[settings]; // take previous settings from window;
drop.select2(settings); // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;
It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive.
Hope, this solution will be usefull or may push you in right decision in problem fixing
The solution:
Once the content is loaded via ajax you can no longer attack generically like eg ‘.select2’. Because now other elements have this class as the span generated by select2.
So after loading ajax you need to call a method to check if select2 is already instantiated and instantiate it individually.
jQuery('select.select2').each(function (i, obj) {
if (!jQuery(obj).hasClass("select2-hidden-accessible")) {
jQuery(obj).select2();
}
});
My article about
enter link description here
Suppose you are only interested in replacing select2 data:
$('#selector').html('').select2({
data: //new data
})
Initialize again select2 by new id or class like below
when the page load
$(".mynames").select2();
call again when came by ajax after success ajax function
$(".names").select2();

jquery to signify if an option is not selected

I would like to add a small code snip to check out whether an option is selected
This usually is easily done if the page is html, now my code snip looks something like this
echo "<td>Language</td>";
echo "<td><select id='language' name='language'>
<option value=''>Select...</option>
<option value='en_US'>English(US)</option>
<option value='en_AU'>English(AU)</option>
<option value='en_UK'>English(UK)</option>
</select><span id="info"></span>
</td>";
if it is html
<script>
$('#language').change()
{
if('Select...'==$('#language').text())
{
$('#info').html("Please select a value...");
}
}
</script>
[UPDATE]
I would like to add that the above php source code used to generate html code is put in a form tag that is
echo "<form action='checkdb.php' method='POST'>
// all above and more
</form>"
the page checkdb.php used the posted data to update database.
How can I add in the jquery code piece as mentioned in the current file (the file with the html code is being generated) ? I am thinking as people once told me that javascript can't be called in the middle of the php execution and I wonder if I may need to use ajax get function. Please offer some help. Thank you.
// Listen, and respond to, the change even on our select
$("#language").on("change", function(e){
// Set the html content of our info element
$("#info").html(function(){
// If the selected option has no value, ask to select a value
return e.target.value === "" ? "Please select a value." : "" ;
});
// Trigger upon page load
}).trigger("change");
Demo: http://jsbin.com/owaqaz/2/edit
Note the last line, $.trigger("change") - this will cause the page to immediately populate the #info element if the select element currently has no value.
Change your jQuery to:
$('#language').change(function() {
if ('Select...' == $('#language option:selected').text()) {
$('#info').html("Please select a value...");
}
});​
jsFiddle example.
Update: Or a more brief version:
jQuery:
$('#language').change(function() {
$('#info').html(('Select...' == $('#language option:selected').text()) ? "Please select a value...":"");
});​
jsFiddle example.
Sorry but what was your question?
A PHP page turns into a HTML Page after processing (a user never sees the PHP source code), and you can easily use javascript to check for the value.

javascript and PHP variable passing

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

Categories