jquery get data attributes of select2 inside while loop php - php

I have been reviewing similar questions related to select2 data attributes, but couldn't find what I'm looking for. I have been taking time on this.
Basically I have a select2 dropdown inside a while loop which fetch values from sql database. I need to add an additional data attribute and when an option is selected, I need to display the selected data attributed in the input field. My code goes as below
<select class="select2-dropdown form-control" tabindex="-1" id="user" name="user">
<option value="">Select User</option>
<?php
$fetchuser = mysqli_query($link,"SELECT * FROM user ORDER BY name ASC") or die(mysql_error());
while($row=mysqli_fetch_assoc($fetchuser))
{
$id = $row["id"];
$name = $row["name"];
$status = $row["status"];
?>
<option value="<?php echo $id; ?>" data-status="<?php echo $status; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input id="status" />
My JS:
<script type=text/javascript>
$('#user').on('select2:selecting', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});
</script>
I'm only getting random status (not corresponding to the selected), and some options status is not displayed when selection is changed.
Could anyone suggest where i have made the mistake.
Thank you in advance.

Your code is so weird for me.
Try this:
$('select').on('change', function() {
var status=$(this).find(":selected").data("status");
$('#status').val(status);
});

I think it will change function that you need to use
$('#user').on('change', function() {
var status= $(this).find(":selected").data("status");
$('#status').val(status);
});

Related

Dynamic dependent select boxes (PHP+JQuery+AJAX)

I have been working on a dependent select boxes form using PHP as the server-side language and JQuery with Ajax. I am having an issue with getting the response text, as it is not displaying as options in the second select box.
P.S. I am new to Ajax and there is no video that can help me with my problem.
HTML&PHP:
<center><form method="post" action="php/functions.php" id="catForm">
<select name="catSelect" class="catSelect" name="category">
<option value='null' default>اختر الفئة:</option>
<?php
$selectCategories = mysqli_query($connectionDB, "SELECT * FROM categories");
while($categoriesDisplay = mysqli_fetch_array($selectCategories)){
echo '<option value="'.$categoriesDisplay['id'].'">'.$categoriesDisplay['category'].'</option>';
}
?>
</select><br/><br/>
<select name="subCatSelect" class="subCatSelect">
<option value="null" default>اختر النوع:</option>
<?php
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
?>
</select><br/>
<h1></h1>
<input type="submit" value="اختر" class="submitForm" /><br/>
</form></center>
Jquery code:
$(document).ready(function(){
$('.catSelect').change(function(){
var changeURL = $('#catForm').attr("action");
var data = $('.catSelect').val();
$.post(changeURL, {category : data}, function(subCategory){
$('.subCatSelect').append(subCategory);
});
});
});
The code that should work on getting the options for the second select box:
$catSelectVal = $_POST['catSelect'];
$selectSubCat = mysqli_query($connectionDB, "SELECT * FROM sub_categories WHERE id LIKE '$catSelectVal'");
while($subCatDisplay = mysqli_fetch_array($selectSubCat)){
echo '<option value="'.$subCatDisplay['id'].'">'.$subCatDisplay['subCategory'].'</option>';
}
I could be wrong, but I don't think you've sent 'catSelect' in the ajax request.. rather you've sent category with data being the value from 'catSelect'
So when you look for $catSelectVal = $_POST['catSelect']; there won't be anything to find.
Try instead: $catSelectVal = $_POST['category'];
As #RiggsFolly mentioned, if you print_r($_POST); you'll instantly see if this is the case or not.

How to enable a field if a determined option is chosen?

I have a form in which when the user chooses certain option in a select drop-down, a new field should shows up for entering another piece of information.
Basically, it's the common "Where did you hear about us?" and when the user selects other, a new empty field is shown so that he can type the source if it wasn't in the list.
But I really have no clue about how to do it. I've been using PHP and HTML to do the form and validating it.
To add some code, this is where I create the select
<label for="where_heard">Where heard:</label>
<select name="where_heard"> <?php echo $sources; ?>
</select>
And this is where I get the source list from:
$query = "SELECT source FROM where_heard";
$stmt = $db->prepare($query);
$stmt->execute();
$sources = "";
while ($row = $stmt->fetch()) {
$sources .= '<option value= "'.$row['source'].'">'.$row['source'].'</option>';
}
You can do this with jquery like:
$( document ).ready(function() {
$('select').on("change",function(){
if($(this).val() == "other")
$(".other").html("Other: <input type='text' name='other'/>");
else
$(".other").html("");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="where_heard">Where heard:</label>
<select name="where_heard"><option></option><option value="other">Other</option>
</select>
<div class="other"></div>

Hold country value when submit

<label>Country <font color="8AC007">*</font> </label></td>
<td><select name="country" onchange="print_state('state',this.selectedIndex);" id="country"<?php
$sel_country = $myform->value('country');
if (isset($sel_country)) echo 'selected="selected"'; ?> />
<option value="<?php $myform->value("country"); ?>"/>Select country</option>
</select><br><?php $sel_country.'sample' ?>
<span class="error"><?php echo $myform->error("country"); ?></span>
I want to get hold with the country selected value when I submit form, instead filling the form from starting again. Here is the code Iam trying to get countries from a js file.
Apperciate your help
HTTP is stateless, so you have to put a little effort on keeping data around when moving from page to page. Seeing this as being a form with inputs (select in this case), you can use $_POST to get hold of your submitted value in the next page.
In this case you'd use $_POST['country']. If you want to keep the current form filled next time the page refreshes, make the form submit to the current page, then you'll have access to that value in $_POST.
Other ways to keep data around:
Sessions
Cookies
Database storage
But this require a little bit of additional coding in PHP.
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country"/>
<option <?php if($youroldval==$myform->value('country')){ echo 'selected="selected"'; } ?> value="<?php echo $myform->value("country"); ?>"/><?php echo $myform->value("country"); ?></option>
</select>
You must store your old value of form
Ok, if I am right you should do it as follows.
If you are posting your page to the server. You have the selected value. You store this and return this page. In that case I added bollow code and added $isSelected to the code. Normally it emtpy, but if the value is equal to the selected then you set selected='selected'.
<select name="country">
<?php
$countryList = array("USA", "UK", "France", "Germany", "India", "Netherlands");
$isSelected = "";
foreach($countryList as $country)
{
if($_POST["country"] == $country)
{
$isSelected = "selected='selected'";
}
echo "<option value='" + $country + "' " + $isSelected + ">" + $country + "</option>";
?>
</select>
If you are using jquery / Ajax, you have the selected value which stays selected because the page wont refresh :-) However, you can get the value by using javascript and get value from selectbox.
------ Edit
Mmm ok, I was in the illusion you had your array in php. However you get your collection from javascript. In that case you will get this as solution:
<script type="text/javascript">
var selectedCountry = "<?php echo $myform->value("country"); ?>";
</script>
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country">
/* This is generated by javascript */
</select>
Your javascript function will be like this:
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selectedCountry == country_arr[i])
{
option_str.options[option_str.length].setAttribute("selected", "selected");
}
}
}
----- Edit 2:
http://jsfiddle.net/eLProva/5mU76/ with filling and selecting the country

get selected item from a dropdown list and save it to a php variable

I have a dropdown list(in a php file and without form tag)
print "<select id="animal" onchange="getSelectedItem(this.value)">
<option value = "Dog"> Dog </option>
<option value = "Cat"> Cat </option>
</select>";
and a variable $selAnimal
and a javascript function
function getSelectedItem(opt){
//$selAnimal = opt <- how do i do this?
}
As much as possible I wouldn't like the page to reload so I avoid putting this inside a form and submitting as I select. I can't get to make $.post method work. I know for a fact that this cannot be directly done since php is server side and javascript is client side.
I also thought of putting the selected value inside a hidden component(span or something) and get the value from it. But I have no idea how to get it from the component. I've also seen use of AJAX or jquery but I'm not really knowledgeable enough.
I need to save this value to the php variable since I'll be using it as basis for the options in my second dropdown. For example, if I choose Dog, the dropdown list would have dog breeds as options.
I've spent days looking for possible solutions everywhere. Help would be very much appreciated. Thank you!
here is the solution
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#animal').change(function(){
$.post('loadbreeds.php', { animal:$('#animal').val() },
function(data){
$('#breedList').html(data);
});
});
});
</script>
<form method="post" >
<div id="animalList">
<select id="animal" name="animal">
<option value="">--Select--</option>
<?php if (!empty($animals)) { foreach ($animals as $value) { ?>
<option value="<?php echo $value['animalKey']; ?>"><?php echo $value['animalName']; ?></option>
<?php }} ?>
</select>
</div>
<div id="breedList">
<select id="breed" name="breed">
<option value="">--Select--</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
code for loadbreeds.php
$animalKey = $_POST['animal'];
$breeds = selectByKey($animalKey); // code for selecting breeds
<select id="breed" name="breed">
<option value="">--Select--</option>
<?php if (!empty($breeds)) { foreach ($breeds as $value) { ?>
<option value="<?php echo $value['breedKey']; ?>"><?php echo $value['breedName']; ?></option>
<?php }} ?>
</select>
You cannot have the variable available to the same file since PHP declares all its variables before the JS even starts. You can however simply redirect the user to a new file where the variable is available.
Use something like this:
function getSelectedItem(opt){
location.href = location.href + "?selAnimal=" + opt;
}
In PHP, now you can use the selAnimal variable to display something different, like this:
$selectedAnimal = $_GET["selAnimal"];
if($selectedAnimal == "dog"){
// Whatever you want to do now
}
A better way would be to use POST with forms, but this should work fine for you as well.
Try the following, to rebuild the second dropdown:
http://jsfiddle.net/kAY7M/59/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
print "<script type=\"text/javascript\">var AnimalTypeList = [\"Dog1,Dog2,Dog3,Dog4\",\"Cat1,Cat2,Cat3,Cat4\"];</script>";
<script type="text/javascript">
$("#animal").change(function () {
var sel = $("#animal").prop("selectedIndex") - 1;
var list = AnimalTypeList[sel].split(",");
var Counter = list.length;
$("#type").children().remove();
for (var i = 0; i < Counter; i++) {
$("#type").append("<option value = '" + list[i] + "'> " + list[i] + "</option>");
}
})
</script>
I could do a pure Javascript only version too, but that is a bit more code.

How to change value in input (textbox) by changing select

I'm trying to change the value in an input when a different option gets selected from a select:
View image here.
The idea is that for each ad package you can have a different number of images (free gets 0 images, $20 for 4 images etc.). With this number I then want to display the correct amount of upload fields for images.
I'm already retrieving the values from the database for the number of images for each package as you can see in the code below:
<select name="ad_pack_id" class="dropdownlist required">
<?php foreach ( $results as $result ) { ?>
<option value="<?php esc_attr_e($result->pack_id); ?>" class="<?php esc_attr_e($result->pack_images); ?>"><?php esc_attr_e($result->pack_name); ?></option>
<?php } ?>
</select>
<input type="hidden" value="" name="packimages" id="packimages" />
I've tried getting the value from the select directly by doing:
mainform.ad_pack_id.options[selectedIndex].class.innerHTML
but this isn't getting the number of images.
How can I get the number of images for the selected ad package without submitting the form first?
you could also try jquery:
$("#ad_pack_id option:selected").val()
this should get you the value. to show/hide upload fields you can use for example the CSS display attribute:
$("#uploadfield_1").css("display", "none")
$("#uploadfield_1").css("display", "block")
try this:
document.mainform.ad_pack_id.options[Selected].className;
This code will set the input's value to the selected option's value.
I just added "id" attribute to select menu
<select id="ad_pack_id" name="ad_pack_id" class="dropdownlist required">
<?php foreach ( $results as $result ) { ?>
<option value="<?php esc_attr_e($result->pack_id); ?>" class="<?php esc_attr_e($result->pack_images); ?>"><?php esc_attr_e($result->pack_name); ?></option>
<?php } ?>
</select>
<input type="hidden" value="" name="packimages" id="packimages" />
<script type="text/javascript">
var selectmenu = document.getElementById("ad_pack_id");
selectmenu.onchange = function()
{ //run some code when "onchange" event fires
var chosenoption = this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing")
{
document.getElementById("packimages").value = chosenoption.value ;
}
}
</script>

Categories