I have two select boxes, one is for products and the other is for product type. what a appears in the product type list is dependent on what is selected in the product. What i want to achieve is a null option at the top of the loaded list so that i can search just on the product. How would i go about this?
so far i have
<select class="form-control" name="product_type" id="producttype">
<option value=""></option>
</select>
and JS/jquery
$('#product').on('change', function(e) {
console.log(e);
var prod_id = e.target.value;
$.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
$('#producttype').empty();
$.each(data, function(index, subcatObj) {
$('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
});
});
});
You can append that default options before filling your select in the each, something like this:
$('#product').on('change', function(e) {
console.log(e);
var prod_id = e.target.value;
$.get('/ajax-subcat?prod_id=' + prod_id, function(data) {
$('#producttype').empty();
$('#producttype').append('<option selected disabled>Select a product type</option>');
$.each(data, function(index, subcatObj) {
$('#producttype').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
});
});
});
Related
I have a JSON array in a JSON file looks like this:
{
"states": [
{
"state": "Andhra Pradesh",
"districts": [
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Krishna",
"Kurnool",
"Nellore",
"Prakasam",
"Srikakulam",
"Visakhapatnam",
"Vizianagaram",
"West Godavari",
"YSR Kadapa"]
}
]
}
and I am successfully able to load all states in the select element as a dependent select option
. when I select a state from a select element it populates a related array in the district select element.
but instead of the array showing a separate option it shows as one option:
Should I modify my JSON array in a different format?
jquery
$('#statePicker').on('change', function() {
$("#cityPicker").html('');
$.ajax({
url: "{{ asset('json/in-sc-list.json') }}",
type: "GET",
dataType: 'json',
success: function(res) {
$('#cityPicker').html('<option value="">Select City</option>');
$.each(res.states, function(key, value) {
if (value.state == $('#statePicker').val()) {
console.log(value.districts);
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
});
}
});
});
blade
<span>
<select id="statePicker" name="statePicker" required class="form-control"></select>
<select id="cityPicker" name="cityPicker" required class="form-control"></select>
</span>
Your data structure is fine. The issue is that you're not creating multiple option elements, you're only creating one. This part is off:
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
What you want to do is create an option element for each district, as follows:
for (const district of value.districts) {
$("#cityPicker").append('<option value="' + district + '">' + district + '</option>');
}
let statePicker = $('#statePicker').val();
let list = $("#cityPicker");
$.each(res.states, function(key, value) {
if (value.state == statePicker) {
$.each(items, function(item) {
list.append(new Option(item, item));
});
}
});
You need to loop value.districts because its an array, and also, you are doing it in a dirty way, you are initializing $("#cityPicker") on every loop, This might give some performance issues in future if the list items increases.
I have the following pseudo code for example: I want to use the same ajax script to select phone_type and method per record, I tried using .attr()
<script>
$('#phone_type').on('change', function (e) {
console.log(e);
var phone_type = e.target.value;
//ajax
$.get('../get_conversion_method_by_phone_type?phone_type=' + phone_type, function (data) {
//success data
$('#method').empty();
$('#method').append('<option value="0" selected>Choose Method</option>');
$.each(data, function (index, conMethObj) {
$('#method').append('<option value="' + conMethObj.id + '">' + conMethObj.method + '</option>');
});
});
});
</script>
foreach($foo as $bar){
<tr>
<select id="phone_type" name="phone_type">
<option>Choose</option>
</select>
<select id="method" name="method">
</select>
</tr>
}
well i hope i understand correctly what you want to do, try this code
<script>
$('.phone_type').on('change', function (e) {
console.log(e);
var $self = $(this);
var phone_type = e.target.value;
//ajax
$.get('../get_conversion_method_by_phone_type?phone_type=' + phone_type, function (data) {
//success data
$method = $self.next('.method');
$method.empty();
$method.append('<option value="0" selected>Choose Method</option>');
$.each(data, function (index, conMethObj) {
$method.append('<option value="' + conMethObj.id + '">' + conMethObj.method + '</option>');
});
});
});
</script>
and the html
foreach($foo as $bar){
<tr>
<select class="phone_type" name="phone_type">
<option>Choose</option>
</select>
<select class="method" name="method">
</select>
</tr>
}
I have a table of unique tasks and underneath it a dropdown list of tasks that can be added.
I want the dropdown list and table to be dynamic because a task cant be in both dropdownlist and table.
So the dropdownlist only containts tasks that are not in the table already.
So if I select a task and click add, it moves to the table (and is no longer in the dropdown). But then if I remove the task from the table it should go back in the dropdown list. This functionality works if the row is already in the table (i.e. in the initial page load), however if I add one to the table and remove it it doesnt go to the dropdown lists.
Here is the js code that moves from dropdown to table
$('#addTaskButton').on('click',function() {
var taskId = $('select[id=processorTasksId]').val();
if (taskId == 0) {
return;
}
var task = $( "#processorTasksId option:selected" ).text();
$('#tasksTable').append('<tr><td>' + taskId + '</td>'
+ '<td>' + task + '</td>'
+ '<td contenteditable=\'true\'>0</td>'
+ '<td><input type="button" value="X"></td></tr>');
$( "#processorTasksId option:selected" ).remove();
});
and here is the JS to remove from table.
$('#tasksTable').on('click', 'input[type="button"]', function(){
var taskId = $(this).closest('tr').children('td.taskIdCol').text();
var taskDescription = $(this).closest('tr').children('td.taskDescriptionCol').text();
$(this).closest('tr').remove();
console.log("id = " + taskId);
console.log("desc = " + taskDescription);
$('#processorTasksId')
.append($("<option></option>")
.attr("value",taskId)
.text(taskDescription));
});
The console log for the problem scenario shows as follows and it just adds an empty option to the dropdown list
id =
desc =
Any idea as to how to fix it?
The problem is with the missing classes for td's added to the table as part of the script.Check below working code
$(function() {
$('#addTaskButton').on('click',function() {
var taskId = $('select[id=processorTasksId]').val();
if (taskId == 0) {
return;
}
var task = $( "#processorTasksId option:selected" ).text();
$('#tasksTable').append('<tr><td class="taskIdCol">' + taskId + '</td>'
+ '<td class="taskDescriptionCol">' + task + '</td>'
+ '<td contenteditable=\'true\'>0</td>'
+ '<td><input type="button" value="X"></td></tr>');
$( "#processorTasksId option:selected" ).remove();
});
$('#tasksTable').on('click', 'input[type="button"]', function(){
var taskId = $(this).closest('tr').children('td.taskIdCol').text();
var taskDescription = $(this).closest('tr').children('td.taskDescriptionCol').text();
$(this).closest('tr').remove();
console.log("id = " + taskId);
console.log("desc = " + taskDescription);
$('#processorTasksId')
.append($("<option></option>")
.attr("value",taskId)
.text(taskDescription));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="processorTasksId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="button" id="addTaskButton" value="Add" />
<table id="tasksTable">
</table>
so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/
Say I have a ListBox populated with a name value pair SelectList(myUsers, "Key", "Value"):
#Html.ListBox("ListReviewers", (SelectList)ViewBag.ListOFReviewers, new { style = "width:120px;" })
I want to double click an option in this ListBox, and place it in a SelectionList like below:
<div class="selectedEmployees">
<select class="selectionList" multiple="multiple" name="AssignedReviewer" style="width:120px;">
<!--x.UserID, x.FirstName + " " + x.LastName) -->
<option value=""></option>
</select>
</div>
Once this collection is placed in the above, I want to store all the values in another SelectionList Collection for later use.
Here is the start of my jQuery code:
<script type="text/javascript">
$('#ListReviewers').dblclick(function (i, selected) {
//double click on this value of listbox of type SelectList(myUsers, "Key", "Value")
//store this value and text
var value = $(this).val;
//var empName = $(this).data[0];
var empName = $(selected).text();
alert(empName);
//append an option element <option value=""></option>
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
I can get the value of the dblclicked collection object, but not the text of the collection object. Is there a better way to do this?
Try attaching your event to the option within the select itself. You can then use this to access it's properties.
$('#ListReviewers option').dblclick(function () {
var value = $(this).val();
var empName = $(this).text();
$('.selectionList').append('<option id="' + value + '">' + empName + '</option>');
});
Alternatively, you can use clone() and append() to move the option from one select to the other. This will save you having to worry about duplicate options being appended.
$('#ListReviewers option').dblclick(function () {
var $newOptions = $(this).clone(false);
$(this).remove();
$('.selectionList').append($newOption);
});