Select combo box dynamically in jquery mobile - javascript

I want to append value from data base on option tag combo box. But when I first doing option tag's value empty and then I appending through AJAX then it only showing one value. But I want like all option should be visible but one should selected automatically.
my code
$('#b').on("click", "a", function () {
var patid= $(this).attr('id');
$.ajax({
type:"GET",
url:"https://localhost/patient_details1.php?patid="+patid,
dataType:'JSON',
success:function(response)
{
("#pat_type").html("");
for (var i=0;i<response.length;i++)
{
$('<option value="'+ response[i].pattype +'">'+
response[i].pattype +'</option>').appendTo("#pat_type");
}
}
}
});
});

use $('#pat_type').empty().
check when you get data from your request. You need to get it
only after loading your page.

You having typo error ("#pat_type").html("");
make it $("#pat_type").html(""); or $('#pat_type').empty();
for (var i = 0; i < response.length; i++){
listItems+= "<option value='" + response[i].pattype + "'>" + response[i].pattype + "</option>";
}
$("#pat_type").append(listItems);
// for setting selected item based on value
$('#pat_type').val('selectedvalue');

Related

Append a dynamic select box to a div after button click

I am trying to append an accordion div after a button click. That works fine. But inside the appended div I have a select box , that has to be dynamically populated. After getting the Json results I tried to append the option values, but it failed. When I alert, I am getting the exact results.
Here is my controller
public function getTypes(){
$types = AnsTypes::get();
return response()->json($types);
}
My Ajax
$.ajax({
url: site_base_url+ '/surveys/getquestiontypes',
type: "get",
contentType: "application/json",dataType: "json",
success: function(data){ // What to do if we succeed
if(data){
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
$.each(data, function(key, value){
'<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
}) +
'</select>'+
'</div>');
});
My response payload is:
JSON
0 {…}
answer_datatype_id 1
type_name Text
1 {…}
answer_datatype_id 2
type_name RadioButton
2 {…}
answer_datatype_id 3
type_name CheckBox
3 {…}
answer_datatype_id 4
type_name ListSingleSelection
4 {…}
answer_datatype_id 5
type_name ListMultiSelection
Response payload
[{"answer_datatype_id":1,"type_name":"Text"},{"answer_datatype_id":2,"type_name":"RadioButton"},{"answer_datatype_id":3,"type_name":"CheckBox"},{"answer_datatype_id":4,"type_name":"ListSingleSelection"},{"answer_datatype_id":5,"type_name":"ListMultiSelection"}]
My Result
this look like your $.each not return the <option> to your DOM. You can try to add the <option> to a variable called options :
let options = "";
$.each(data, function(key, value){
options +='<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
})
then you add your options to your DOM like this:
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
options
+
'</select>'+
'</div>');
this should work.
For the record I already tried this code and it works well, please let me know if you need something else.

Passing value from for loop in ajax, into form field

I have some javascript that takes user input, queries an endpoint with that input via ajax, and returns a field from the results as an appended <option> to a datalist. This is working properly and I see exactly what I need in the options list.
The next portion I've worked on is that when I click the option, I want other fields related to it in the object to populate the value of a form input. I've got this all structured but when I click an item it says result is not defined
in this line:
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
So my options are correct, and when I click an option it reflects the clicked option in the console. The issue is that I'm not passing the result into my else if correctly, apparently.
The heirarchy of my _source is correct but I just don't know how I need to change my .val argument in order to pull the right value.
Any ideas?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
console.log(optSelector); //this prints the option[value] of the clicked value as it should
$("#groupName").val(result[$(foundOption).attr('srindex')]._source.name);
$("#groupNum").val(result[$(foundOption).attr('srindex')]._source.code);
} else {
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
console.log(searchResult);
$("#returnedProducts").empty();
let result = response.hits.hits;
console.log(result);
for(let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i]._source.name + ">" + result[i]._source.name + "</option>");
}
}
});
}
});
Update:
my object looks like this
hits
hits
_source
name
code
fiddle http://jsfiddle.net/qhbt569o/8/
Working example.
You've just to change _source by source inside the loop like :
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append("<option srindex=" + [i] + " value=" + result[i].source.name + ">" + result[i].source.name + "</option>");
}

Duplication in HTML datalist using JQuery with more than one clicks

I design a datalist on web page. And I want to fill this datalist using JQuery. Controller execute a query and get a list of facilities. Then pass this list to client side. This datalist can show all the facilities. When user click this textbox, the facilities will be listed in drop down list. But when user click more than once, there will be duplicates in datalist. That means, if you click twice, the result will be shown twice in datalist.
Here is code in MVC view
datalist:
<input type="text" list="facility" autocomplete="on" name="Facility" id="facilities" />
<datalist id="facility"></datalist>
JQuery Code:
$(document).ready(function () {
$('#facilities').click(function () {
//alert("Clicked");
var postData = $('#clientTxt').val();
$.ajax({
type: "POST",
url: '#Url.Action("FacilityCheck", "PCA")',
data: { clientTxt: postData },
success: function (result) {
//successful
for (var i = 0; i < result.facilities.length; i++) {
//alert(JSON.stringify(result.facilities[i]));
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
//I want to add an if judgement to avoid duplicates here
//Like contains() method in JAVA.
$('#facility').append(option);
}
},
error: function (result) {
alert('Oh no :(');
}
});
});
});
The duplicates image after clicking many times:
So please give me some advice. Thanks a lot!
It is because you are using the jQuery append() method and not replacing the HTML. Right now, you're just adding (appending) to it every time you iterate through your loop of result.facilities[i] instead of replacing the content.
Your best bet would be to add all of that source to a string and replace the $('#facility')'s innerHTML with the new content. You can use $('#facility').html(yourContentString); to do so.
Hope this helps!
For example...
success: function (result) {
var options = "";
//successful
for (var i = 0; i < result.facilities.length; i++) {
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
options = options + option;
} //end of loop
$('#facility').html(options); // replace the innerHTML of #facility with your new options string
},
Simply modify your success like this :
$('#facility').html('');
$('#facility').append(option);
Remove the items before appending them.
You can also use empty :
$('#facility').empty();

can not get the changed attribute using jquery

I fetched the data from remote sever, and appended different rows to the table, now, I want to get all the checked box data and do further treatment, like when tick the box, then the data will be pushed to an array, and remove the element from that array when tick off the check box. so now, the question is, i can not select the checked box which the attribute was changed after appending work, the core code part is:
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked'); // it works here
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
// it can not get the ischecked="checked"
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
and the full code here:
$(function(){
var url = some url;
var tickedArray = [];
$.ajax({
url: url,
type:'GET',
xhrFields: {
withCredentials: true,
},
success:function(data){
$.each(data.stories, function(index, value){
var $row = $("<tr>" +
"<td><input type='checkbox' value="+ value.id +" ischecked='unchecked'></td>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"</tr>");
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked');
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
$('#stories_list_table > tbody:last').
append($row);
});
}
});
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
This selector won't find any checkbox because there aren't any at that moment. Instead of creating 2 click events you should only create 1 change event and check the ischecked attribute for it's value.
Also, why do you create your own ischecked attribute instead of using the standard checked property?
I think you can try using event delegation, like this :
$row.on('click', 'input[ischecked="checked"]', function(){
console.log('unchecked');
});

jQuery getJSON not populating HTML select properly

I have an HTML <select>:
<div id="content">
<input type="button" id="get-btn" onclick="getData();"/>
<select id="attrib-type-sel"></select>
</div>
When the user clicks the following button, I want to use jQuery's getJSON method to hit my server, pull back data, and populate the <select> with options:
$(document).ready(function() {
$.getJSON(
"some/url/on/my/server",
function(data) {
var optionsHTML = "";
var len = data.length;
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i] + '">'
+ data[i] + '</option>';
}
$('#attrib-type-sel').html(optionsHTML);
});
});
When I run this code, in Firebug, I see that the AJAX call is successful and returns the following JSON:
[
{
"id":1,
"name":"Snoopy",
"tag":"SNOOPY",
"allowsAll":false
}
]
(Only returns 1 record).
However, when back in the UI, when this code fires it creates a <select> that has 1 options whose inner HTML reads [object Object].
Can anyone spot what is going on here? It looks like my getJSON is OK, but the code to extract the JSON from the results and use it to populate my select is buggy. Thanks in advance!
it's because that data[i] is an object. Try using console.log(data[i]) to check out what it's looking like.
data[i].id and data[i].name are likely what you are looking for.
you need data[i].id & data[i].name to construct your options.
for(var i = 0; i < len; i++) {
optionsHTML += '<option value="' + data[i].id + '">'
+ data[i].name + '</option>';
}

Categories

Resources