HTML control functionalities - javascript

I have a select html element
like this:
<select>
<option id="US" value="US">
</option>
<option id="Canada" value="Canada">
</option>
</select>
I want two things:
I want to post request to server on selection of option
And I want to put html elements inside option
Are these two things possible (for all browsers, especially modern browser)?

Use change event on select.
$('select').on('change', function() {
$.ajax({
url: '',
data: {
...
}
});
});
Embedding HTML inside option.NOT RECOMMENDED
$('option:first').html('<div>Hello</div>');

If you are using jquery :
$(function() {
$('select').on('change', function() {
$.post('your/path', $(this).val(), function(data) {
var option = $('select option[value="'+$('select').val()+'"]');
// Do what you want with your option
};
});
});

Related

Add database default value to dropdown list using jQuery AJAX

I'm working with CRUD operation using jQuery AJAX and bootstrap modal in laravel. But the problem is when I want to edit something. I can't populate my dropdown list after an AJAX success request. How can I set database default value in my edit modal Dropdown List?
My Code:
$(document).ready(function() {
$('.acedit').click(function() {
$('#form')[0].reset();
$('#modal_form').modal('show'); // show bootstrap modal
var id = $(this).data('id');
$.ajax({
url: "{{route('academic.edit')}}",
method: 'post',
data: {
id: id,
'_token': "{{csrf_token()}}"
},
success: function(data) {
//$('#mycontrolId').selectmenu('refresh').val(myvalue).attr("selected", "selected");
$('.degree').val(data.degree).attr('selected', true);
$('.divison').val(data.division);
$('.year').val(data.year);
console.log(data); //{id: 2, user_id: 5, degree: "ssc", division: "First", year: "2009", …}
}
});
});
});
My Controller Method:
public function acadedit(Request $request){
$id=$request->id;
$info=Academic::find($id);
return $info;
}
My edit modal Dropdown list:
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
There is no selected attribute on the <select> element, it's only for the <option>s. However, you don't really need it, because setting the value of the <select> element is enough to change the selection. But you need to match the value exactly with the proper letter casing, so all capital letters in your case.
Change this:
$('.degree').val(data.degree).attr('selected',true);
To:
$('.degree').val(data.degree.toUpperCase());
If you really prefer to do it with the attribute on the <option> instead of the value of the <select>, then you need to add the <option> to the jQuery selector like this:
$('.degree option[value=' + data.degree.toUpperCase() + ']').attr('selected', true);
Demo:
$('.degree option[value=SSC]').attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
If you want to use response data from your Controller by Ajax, then it better to return it in Json format:
Use return response()->json($info); instead of return $info;
As I can see from your console.log output you receive degree: "ssc", whereas
your select option is SSC, so you need to uppercase the data before use it: $('.degree').val(data.degree.toUpperCase()); or to downcase values of select options: <option value="ss">SSC</option>.

Is this a proper way of using AJAX with jQuery and PHP?

I need some help. I'm going use AJAX (for the first time) and I'd like you to tell me whether the way I am going to show you is optimal.
Let's say that I have a select element.
<select class="update-db" data-id="25" data-original-value="2">
<option value="1">Yellow</option>
<option value="2" selected="selected">Red</option>
<option value="3">Blue</option>
</select>
So here is what I do:
$(document).on('change', 'select.update-db', function() {
// Get needed data
var select = $(this);
var id = select.attr('data-id');
var originalValue = select.attr('data-original-value');
var newValue = select.val();
// Perform the request
$.ajax({
method: 'POST',
url: 'update-db.php',
data: { id: id, 'original-value': originalValue, 'new-value': newValue }
});
// Then, if everything is okay, change the "original value" of the select element
// so that we can perform the updating operation again without having to refresh the page
.done(function() {
select.attr('data-original-value', newValue);
});
});
Then, on the other side, a PHP script validates everything and updates the database.
Is this the correct way of using AJAX? I feel it's not. What am I doing wrong?

Jquery Chosen Ajax call not rendering the options

I am using Jquery 1.6.4 and chosen 1.4.1. I am facing issue while rendering the options from AJAX. Following is my code.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".chzn").data("placeholder","Select Frameworks...").chosen();
jQuery("#item").chosen().change(function(e, params){
values = jQuery("#item").chosen().val();
$('#item_selected').val(values);
});
});
$('#customer').click(function() {
var url = "ajax_common.php?action=getItem&companyid=1";
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function(data){
$("#item option").remove();
$("#item").append(data);
$("#item").trigger("liszt:updated");
}
});
</script>
<select class="chzn inpt-fld" multiple="true" name="item" id="item" style="width: 96%">
</select>
But the value is not appending in the multi-select drop-down?
The problem seem came from the way you output ajax response. You can not append options in the select tag dynamically because it is not belong to the current select. Meaning this select can not detect the options that previously not exist (as hard code).
You should include select and option together in ajax_common.php and render in div as innerHtml.
// inside ajax_commond.php :
<select class="chzn inpt-fld" multiple="true" name="item" style="width: 96%">
<option> xxxx </option>
</select>
// render the ajax response in :
<div id="item"></div>

Handle event for specific div among multiple div

I'm looking for guidance on the following scenario:
Context: A page displays a dynamically generated list with X (changes based on the user) number of items, each formatted as follows:
<div class="dashboard_section_item">
<label for="add_listname_label">Assign to list</label>
<br/>
<select name="mod_list" class="mod_list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</div>
I need to handle the user selection in the dropdown list in JQuery. The problem is the list is repeated x times on the page, so it will only work for the first item displayed.
$(document).ready(function () {
$(".mod_list").change(function () {
$.ajax({
type: 'POST',
url: 'mod.php',
data: 'prod_uid=' + $('.prod_uid').val() + '&mod_list=' + $(this).find(':selected').val(),
dataType: 'json',
success: function (response) {...
},
error: function () {...
}
});
return false;
});
});
I'm thinking about concatenating a UID to the list name tag like:
<select name="mod_list_34745727" class="mod_list">
but I'm unsure whether there is a better way to do this.
How can I uniquely identify each item list to select its dropdown value?
Supposing that there are a lot of selects with class mod_list you can use on() delegation:
$(document).ready(function () {
$(document).on("change", ".mod_list", function () {
// this is the select you changed the value
var $changedValueSelect = $(this);
// do stuff, ajax and so on
// print in console the selected value
console.log($changedValueSelect.val());
});
});
Why delegation? Because you have dynamically appended elements in your page.
JSFIDDLE

Jquery - Grab multiple selections' data in Jquery

This originates from my original question. I'm expanding on it.
Html select options
<select id="1d" name="camp" multiple="multiple">
<option data-url0="week_1" value="Week 1">30th July</option>
<option data-url1="week_2" value="Week 2">6th August</option>
</select>
<input type="hidden" name="camp_url0" id="1e">
<input type="hidden" name="camp_url1" id="1f">
Jquery script I'm struggling with.
$("#1d").on("change", function () {
var url1 = $(this).children(":selected").data("url0");
var url2 = $(this).children(":selected").data("url1");
$("#1e").val(url0);
$("#1f").val(url1);
});
This code works beautifully (maybe not the cleanest?), except for one important issue. Even though it is a multiple selector, whenever both options are selected, only one option is marked as :selected in DOM, meaning only one data-url{row_id} is being inputted. I need both, if both are selected.
I hope that makes sense. Thanks for your help.
UPD:
Add some additional “routing” data to the html
<select id="1d" name="camp" size="5" multiple>
<option data-url="week_1" data-id="1e" value="Week 1">30th July</option>
<option data-url="week_2" data-id="1f" value="Week 2">6th August</option>
</select>
and use it
$("#1d").on("change", function () {
$('input[type=hidden]').val('');
$('option:selected', this).each(function() {
$('#' + $(this).data('id')).val($(this).data('url'))
})
})
http://jsfiddle.net/5ctDC/1/
OLD:
Just .map it and you will get an array with the data.
$('option:selected', this).map(function() {
return $(this).data('url')
})
["week_1", "week_2"]
http://jsfiddle.net/5ctDC/
Go through ALL of the selected elements:
$("#1d").on("change", function () {
var allurl1 = '', allurl2 = '';
$(this).children(":selected").each(function(){
allurl1 += $(this).data("url0");
allurl2 += $(this).data("url1");
});
$("#1e").val(allurl1);
$("#1f").val(allurl2);
});
Working Demo: http://jsfiddle.net/maniator/mtAgS/ (I made the inputs shown so you can visually see what happens)
In an unrelated note, you should'nt be using id that don't start with a letter.

Categories