jquery about attributes ( load from loaded html ) - javascript

I have a 2 select options. When I select the first one it posts to a link using javascript then return full options to the second one with data from a database.
I have an attributes in the second select called data-price. When I'm trying to use it, it shows nothing:
var x = $("#services").find(':selected').attr('data-price');
However when I'm trying with the first select attribute it works correctly. Anyone know how to fix ? Thanks
<script type="text/javascript">
$(document).ready(function(){
var category = document.getElementById("category").value;
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
$('#category').on('change',function(){
var category = $(this).val();
if(category){
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
}else{
$('#services').html('<option value="">Select category first</option>');
}
});
});
var x = $("#services").find(':selected').attr('data-price');
document.getElementById("demo").innerHTML = x;
</script>
<div class="form-group">
<label>Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($categories->result() as $cat): ?>
<option data-price="55" value="<?=$cat->id;?>">- <?=$cat->title;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Service</label>
<select name="service" id="services" class="form-control">
<option data-price=""></option>
</select>
</div>
<div id="demo"></div>

To find the selected one you do:
$("#services option:selected")
then you can get whatever you want from that option.
For a data attribute it can be:
$("#services option:selected").data('price');
or alternatively
$("#services option:selected").attr('data-price');
This answer is based on the assumption that your select as an id attribute of services, if it is not all the above code will fail
Based on the updated code you posted you probably are looking to update the selected value when the user changes the selection.
I'd do it binding the change event like this:
$("#services option:selected").change(function(){
var price = $(this).attr('data-price');
$('#demo').html(price);
});

Related

Select option and display content related to option with JQuery

this is my first question and after grinding through several threads on here I am still completely lost and can't find a proper solution to my problem.
What I want to do?
A select Box with various options, each options is connected with a JQuery script which makes a related div visible when selected.
<center>
<select onclick="changeview()">
<option value="foo" id="location1" class="ticketbuttons my_active">Location 1</option>
<option value="bar" id="location2" class="ticketbuttons">Location 2</option>
</select>
</center>
When you switch between the options, I want specific DIVs to appear or not appear by this script
<script>
jQuery( document ).ready(function() {
jQuery( "#location1" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc1").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location1").addClass("my_active");
alert('Hello1');
});
jQuery( "#location2" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc2").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location2").addClass("my_active");
alert('Hello2');
});
jQuery( "#location3" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc3").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location3").addClass("my_active");
alert('Hello3');
});
jQuery( "#location4" ) function changeview() {
jQuery(".changing_ticket").hide();
jQuery("#loc4").fadeToggle();
jQuery(".ticketbuttons").removeClass("my_active");
jQuery("#location4").addClass("my_active");
alert('Hello4');
});
});
</script>
and last but not least the frontend output
<div id="loc1" class="change_ticket">Info about location 1</div>
<div id="loc2" class="change_ticket hidden">Info about location 2</div>
I have read about several options like change, onselect, on("change", function () .. and tested but nothin really worked for me.
Hope someone can help me! Thanks in advance!
You could try something like this. Create a variable to store the value of the select dropdown ID & then check which option is selected and hide() the other values and display only the one necessary.
<!-- original dropdown. Replaced by updated for loops in PHP
<center>
<select id="changeEvent">
<option value="1">Location 1</option>
<option value="2">Location 2</option>
<option value="3">Location 3</option>
<option value="4">Location 4</option>
</select>
</center>
-->
<!-- Changes made for dynamic option list-->
<!--Add a data attribute for counter to pass to your jquery loop-->
<center>
<!-- Counter used for creating number of necessary options-->
<?php $counter = 20;?>
<select id="changeEvent" data-counter-id="<?php echo $counter;?>">
<?php
for($i = 1;$i <= $counter; $i++){
?>
<option value="<?php echo $i;?>">Location <?php echo $i;?></option>
<?php
}
?>
</select>
</center>
Your divs use the same counter variable
<!-- Original divs. Replaced by for loop to create dynamic option list
<div id="loc1>" style="display:none;">Info about location 1</div>
<div id="loc2>" style="display:none;">Info about location 2</div>
<div id="loc3>" style="display:none;">Info about location 3</div>
<div id="loc4>" style="display:none;">Info about location 4</div>
-->
<?php
for($x = 1;$x <= $counter; $x++){
?>
<div id="loc<?php echo $x?>" style="display:none;">Info about location <?php echo $x?></div>
<?php
}
?>
In your jQuery function you could add an on('change') event instead of inline on your select dropdown & grab the value of the Select option list and do a check to see which one was selected and display the appropriate DIV. Add a fadeIn() to the item you want to show()
<script>
$(document).ready(function() {
$("#changeEvent").on('change', function() {
/*Original code
var options = $(this).val();
if(options == '1'){
$("#loc1).fadeIn('slow').show();
$("#loc2).hide();
$("#loc3).hide();
$("#loc4).hide();
}else if(options == '2'){
$("#loc1).hide();
$("#loc2).fadeIn('slow').show();
$("#loc3).hide();
$("#loc4).hide();
}else if(options == '3'){
$("#loc1).hide();
$("#loc2).hide();
$("#loc3).fadeIn('slow').show();
$("#loc4).hide();
}else{
$("#loc1).hide();
$("#loc2).hide();
$("#loc3).hide();
$("#loc4).fadeIn('slow').show();
}
*/
/* This will loop through options and display the selected*/
var options = $(this).val();
var counter = $(this).data("counter-id");
for(let i = 1; i <= counter; i++){
if(options != i){
$("#loc" + i).hide();
}else{
$("#loc" + options).fadeIn('slow').show();
}
}
});
});
</script>
Try using onchange instead of onclick on the select tag
<select onchange="changeview()"></select>
or you could try putting ID on the select tag and do some jQuery
<select id="selectOption"></select>
jQuery
$(document).on('change','#selectOption', function () {
// DO THINGS HERE
});

Dynamic dropdown list not loading in modal

I have a dependent dynamic drop listing that works fine but as soon as I include it inside a modal, it doesn't work.
This is my code within the modal:
<script src="plugins/jQuery/2.1.1.jquery.min.js"></script>
<script src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#BugMaster').on('change',function(){
var bugmasterID = $(this).val();
if(bugmasterID){
$.ajax({
type:'POST',
url:'ajax/bugs/populate.cat.php',
data:'id_bug_master='+bugmasterID,
success:function(html){
$('#BugMasterCat').html(html);
}
});
}else{
$('#BugMasterCat').html('<option value="">Select BugMaster first</option>');
}
});
});
</script>
This is the html part of the form with the list :
<select class="form-control" name="BugMaster" id="BugMaster">
<option value="0" selected="selected">Please select module</option>
<?
while($r_b_c = mysqli_fetch_array($q_b_c)){
?>
<option value="<? echo $r_b_c['id_bug_master']; ?>"><? echo $r_b_c['name']; ?>
</option>
<? } ?>
</select>
This is the dependent list
<select name="BugMasterCat" id="BugMasterCat">
<option value="">Select country first</option>
</select>
The 'populate.cat.php' file looks like this:
if(isset($_POST["id_bug_master"]) && !empty($_POST["id_bug_master"])){
$id_bug_master = clean_data($_POST['id_bug_master']);
$q_cat = mysqli_query($sqllink,"SELECT * FROM bugs_categories
WHERE valid='1' AND id_bug_master='$id_bug_master'");
while($r_cat = mysqli_fetch_array($q_cat)){
echo "<option value='$r_cat[id_cat]'>$r_cat[name]</option>";
}
}
Then again, all this works fine if I load it directly from a page, but as soon as I open it in a modal, it fails and no categories are shown. I'm thinking it has to do with $(document).ready(function() that is not loading.
By not working I mean that the second drop down list is not being loaded.
Any help will be appreciated. Thank you.
I think no event is attached to your drop down
change your code:
... $('#BugMaster').on('change',function(){ ....
with
$(document).on('click', '#BugMaster', function() {
You need to load your JAVASCRIPT code from model itself, not from the parent / Base page.
But if you want to use another option that either use delegate or use inline javascript function call.
$(document).delegate('#BugMaster', 'change', function(){
//Implement your code here
});
OR
<select class="form-control" name="BugMaster" id="BugMaster" onchange="CALLJAVASCRIPTFUNCTIONHERE();">

PHP get selected value of select form

I'm using Laravel and currently creating a form, where users can first choose a category, and then choose a relating subcategory.
A category has an id and a name, a subcategory has an id and a name, as well as a parent_id (so that's the id of the parent category).
Now I try the following:
The user can pick a category, after he did that, the second select appears and the user can choose the subcategory from the subcategories that belong to the parent category (and only those!).
Therefore, the view gets all categories and all subcategories from the controller.
Then, for the categories I did this:
<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
<label for="category" class="col-md-4 control-label">Kategorie</label>
<div class="col-md-6">
<select>
#foreach($categories as $category)
<option value="<?php echo $category['id'];?>">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
And for the subcategories I have the same, just with subcategories:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select>
#foreach($subCategories as $subCategory)
<option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option>
#endforeach
</select>
</div>
</div>
Now the question is: What I need to do is (in the subcategory foreach) a #if and check for the value of the chosen option of the category select and then check if($subcategory->parent_id == $chosenOptionID), to say it in pseudo code. How can I do this? I don't want to send the form or something, before somebody didn't choose the subcategory as well.... Of course, I maybe could send an ajax request to the controller whenever a category is chosen, then check the value of the option in the controller and send back the id. But this would cause very much traffic and would propably not be the best solution, so I'd like to do this only, if I don't get a better way to do....
PS: The question is not about hiding the subcategories when no category is chosen, thats basic js, I know how to do that. I only want to know, if it is possible to read the value of the category select while form is not sent yet.
EDIT: I now tried the AJAX thing but there seems to be a little error...
What I changed:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id);
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
But it doesn't work.. The ajax request is defintely sent on selecting an option, as well the correct id is sent. But somehow nothing is outputted... Any ideas why?
I finally got it working with AJAX. This is my initial subCategorySelect.
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id)->get();
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
And it works perfectly.
hope this will help you understand how it works with php anyway for one selected option:
<div class="form-group">
<label class="control-label" for="country">Country:<span>*</span></label>
<select name="country" type="text" class="form-control" id="country">
<option value="">--Country--</option>
<?php
include "../db/db.php"; //db-connection cause i want to load a country list
$sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //check if an entry is there
while($row = $result->fetch_assoc()) { //get the values from the db
//now this is the part you have to implement in your script
if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something
$optionSelected = "selected='selected'";
} else{
$optionSelected = "";
}
//your foreache loop goes here / add the value that is selected here
/*#foreach($categories as $category)
<option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
#endforeach*/
/**for my attempt it was this
{the id like as your category[id]} {set the selected here inside the option tag}
↓ ↓ */
$countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
echo $countrySet;
}
}
$conn->close();
?>
</select>
</div>

Is This jQuery Bug On First Option Selected?

I have weird situation with Select2 plugins :
When, #state is changed, it will do ajax request to get list of #city. once #city is selected, it will do ajax request to get #area list.
if I select #city option number 2, 3, etc... it will trigger #area to get the list. but if I choose option number 1, none will happen.
but once, I choose option number 2, 3, etc... then go back to choose option number 1, then it will run ajax perfectly.
pic 1 : Badung (option #1) is selected for the first time, not trigerring AJAX to get #area
pic 2 : Bangli (option #2) is selected, it's trigerring AJAX to get #area
pic 3 : Back to Badung (option #1), now it's trigerring AJAX to get #area
here's my HTML structure :
<div class="row">
<div class="col-sm-12">
<div class="form-group form-group-default form-group-default-select2 required">
<label class="">State</label>
<select id="state" class="full-width" data-init-plugin="select2" name="state">
<option select="selected"></option>
<?
for ($i = 0; $i < $num_propinsi; $i++) {
$value = $propinsi[$i]['province_id'];
$text = $propinsi[$i]['province'];
echo '<option value="'.$value.'">'.$text.'</option>';
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<label>City</label>
<select id="city" class="full-width" data-init-plugin="select2" name="city" disabled>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<label>Area</label>
<select id="area" class="full-width" data-init-plugin="select2" name="area" disabled>
</select>
</div>
</div>
</div>
and here's my jquery :
<script>
$(function() {
$("#form-flogin").validate();
$("#state").change(function() {
$("#city").html("");
$("#s2id_city").find("#select2-chosen-2").html("");
$("#s2id_area").find("#select2-chosen-3").html("");
$("#area").prop("disabled", true);
$("#flogin-submit").prop("disabled", true);
var propinsi = $("#state").val();
$.ajax({
url: "controller/ctrl.getcityarea.php?req=city&val="+propinsi,
dataType: "JSON",
success: function(json){
var city = "";
$.each(json, function(i,o){
city += "<option value="+o.id+">"+o.city_name+"</option>";
});
$("#city").append(city);
event.preventDefault();
$("#city").prop("disabled", false);
}
})
});
$("#city").change(function() {
$("#area").html("");
$("#s2id_area").find("#select2-chosen-3").html("");
var city = $("#city").val();
$.ajax({
url: "controller/ctrl.getcityarea.php?req=area&val="+city,
dataType: "JSON",
success: function(json){
var area = "";
$.each(json.rajaongkir.results, function(i,o){
area += "<option value="+o.subdistrict_id+">"+o.subdistrict_name+"</option>";
});
$("#area").append(area);
event.preventDefault();
$("#area").prop("disabled", false);
}
});
});
$("#area").change(function() {
event.preventDefault();
$("#flogin-submit").prop("disabled", false);
});
})
</script>
any idea why .change method is not working on first attempt? but works on next attempt. thank you for your help
This is because you have written a change event listener for city dropdown and first city is default selected hence when you select it again it won't change the value therefore change event listener won't get fire.
You can do one of following two options
Option 1 : put extra option as "Select City" and then select first city of your choice.
$("#city").append("<option value=''>Select City</option>");
$("#city").append(city);
Opetion 2 : trigger change event through code
$("#city").append(city).change();

How to add 1 select field onclick per click

I want to add a select field multiple times depending on the number of clicks the user makes. A toggle or show/hide function will only work for 1 select field.
How would I be able to do that?
e.g: 1 click = add 1 select field
<select name='' id='' class="">
<option value='en-us'>USA</option>
<option value='de-de'>Germany</option>
<option value='en-in'>India</option>
<option value='en-gb'>United Kingdom</option>
<option value='en-au'>Australia</option>
</select> <br>
<button id='add-countries'>add more countries</button>
I have prepared a sample html for this: http://jsfiddle.net/stan255/Wh274/
Something like this should do the trick. jQuery is used here for simplicity, but is not required.
<div id="template">
<select name='' id='' class="">
...
</select>
</div>
<button id='add-countries'>add more countries</button>
var $template = $('#template');
$('#add-countries').on('click', function () {
$(this).before($template.clone());
});
Here's an updated fiddle: http://jsfiddle.net/Wh274/3/.
Note that this does not account for assigning unique names to each <select> so you will need to add that logic or account for it on the server side.
if you could javascript (jQuery)
<script>
$(function(){
$('button#add-countries').click(function(){
newName = prompt('Please input new name');
newAttr = prompt('Please input new short name');
newItem = '<option value="'+newAttr+'">'+newName+'</option>';
$('select').append(newItem);
});
})
</script>
OR
<script>
$(function(){
$('button#add-countries').click(function(){
alert($('select option:selected').val())
});
})
</script>

Categories

Resources