I'm having an issue using jQuery autocomplete with dynamically created inputs (again created with jQuery). I can't get autocomplete to bind to the new inputs.
Autocomplete
$("#description").autocomplete({
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
});
New table row with inputs
var i = 1;
var $table = $("#works");
var $tableBody = $("tbody",$table);
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" id="description" name="item[' + i + '][works_description]" /></td></tr>');
$tableBody.append(newtr);
i++;
});
I'm aware that the problem is due to the content being created after the page has been loaded but I can't figure out how to get around it. I've read several related questions and come across the jQuery live method but I'm still in a jam!
Any advice?
First you'll want to store the options for .autocomplete() like :
var autocomp_opt={
source: function(request, response) {
$.ajax({
url: "../../works_search",
dataType: "json",
type: "post",
data: {
maxRows: 15,
term: request.term
},
success: function(data) {
response($.map(data.works, function(item) {
return {
label: item.description,
value: item.description
}
}))
}
})
},
minLength: 2,
};
It's more neat to use the class attribute for marking the input, like:
<input type="text" class="description" name="item[' + i + '][works_description]" />
Last, when you create a new table row apply the .autocomplete() with the options already stored in autocomp_opt:
$('a#add').click(function() {
var newtr = $('<tr class="jobs"><td><input type="text" name="item[' + i + '][quantity]" /></td><td><input type="text" class="description" name="item[' + i + '][works_description]" /></td></tr>');
$('.description', newtr).autocomplete(autocomp_opt);
$tableBody.append(newtr);
i++;
});
I found that I needed to put teh autocomplete after the append so:
$tableBody.append(newtr);
$('.description', newtr).autocomplete(autocomp_opt);
Related
I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})
I have a form with dynamic rows, after fetching record I want to update status of selected rows by checkbox.
I'm successfully getting each row checkbox values and dynamic row id in console but when trying to update values, it's updating first row only.
HTML:
<button type="button" class="btn btn-info" id="update_status_btn">Update Status</button>
Fetched record:
success: function(data){
var trHTMLr = '';
$.each(data,function(i,row){
trHTMLr += '<tr>' +
'<td><input type="text" name="first_name" class="form-control text-center" value="' + row.first_name + '" /></td>' +
'<td><input type="checkbox" name="status" class="form-control text-center updatestatusclass" data-id="' + row.id + '" value="' + 'YES' + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);
}
Update status:
$("#update_status_btn").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var eachrow_value=[];
$('.updatestatusclass').each(function(){
if($(this).is(":checked"))
{
eachrow_value.push($(this).val());
}
});
eachrow_value=eachrow_value.toString();
var row_id = $('.updatestatusclass').attr('data-id');
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {id: row_id, status: eachrow_value},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
});
Controller:
if ($request->ajax()) {
$stat = Services::where('id', $request->get('id'))
->update(array(
'status' => $request->get('status')
));
return Response::json($stat);
}
I want to update status of selected row by checkbox with it's respective row ID.
What you are looking for is to update multiple checkboxes in one go. So, you need to store both selected & unselected checkboxes.
Your jQuery
let checkedIds = [];
let unCheckedIds = [];
$('.updatestatusclass').each(function () {
if ($(this).is(":checked")) {
checkedIds.push($(this).attr('data-id'));
} else {
unCheckedIds.push($(this).attr('data-id'));
}
});
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {
checkedIds: checkedIds,
checkedIdStatus: 'active', //do your thing
unCheckedIds: unCheckedIds,
unCheckedIdStatus: 'inactive', //do your thing
},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
In your Controller
if ($request->ajax()) {
Services::whereIn('id', $request->get('checkedIds'))
->update(array(
'status' => $request->get('checkedIdStatus')
));
Services::whereIn('id', $request->get('unCheckedIds'))
->update(array(
'status' => $request->get('unCheckedIdStatus')
));
}
Hope this helps. Cheers!
This is my coding
$("#txtBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: '#Url.Action("Get", "Ctrl")',
dataType: 'json',
data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",
contentType: "application/json;charset=utf-8",
success: function (data) {
var transformed = $.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
});
response(transformed);
},
error: function() {
alert('error');
},
});
},
minLength: 3,
select: function (event, ui) {
console.log('ui.item.label', ui.item.label);
$('#txtBox').val(ui.item.label);
},
focus: function (event, ui) {
console.log('ui.item.label - focus', ui.item.label);
$('#txtBox').val(ui.item.label);
}
});
});
I am getting Name and Id from c# controller as Json. I want to the auto complete textbox to display Name and while sending it back to backend while saving, I wanted to send the Id of the Name. But now when I type the name and select the name from the list of suggestions. The Id gets displayed in the text box instead of name.Where am i making the mistake. Can some one guide me on this.
I would suggest you to keep two <input /> one type=text and other type=hidden. You can initialize autocomplete on the type=text, and set the value in type=hidden and in server you can access the value of type hidden.
e.g.
<input type="text" id="txtBox" name="label" />
<input type="hidden" id="valBox" name="value" />
$("#txtBox").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: '#Url.Action("Get", "Ctrl")',
dataType: 'json',
data: "{ 'mode': 'associate','prefix': '" + request.term + "' }",
contentType: "application/json;charset=utf-8",
success: function (data) {
var transformed = $.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
});
response(transformed);
},
error: function() {
alert('error');
},
});
},
minLength: 3,
select: function (event, ui) {
console.log('ui.item.label', ui.item.label);
$('#txtBox').val(ui.item.label);
$('#valBox').val(ui.item.value);
},
focus: function (event, ui) {
console.log('ui.item.label - focus', ui.item.label);
$('#txtBox').val(ui.item.label);
}
});
});
In your controller, you can access both values Request["label"], Request["value"]
using this plugin
https://github.com/aehlke/tag-it
its very cool by the way.
problem:
<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true">
Tags:<br>
<ul id="mytags"></ul>
<script type="text/javascript">
$(document).ready(function () {
$("#mytags").tagit({
singleField: true,
singleFieldNode: $('#mySingleField'),
allowSpaces: true,
minLength: 2,
removeConfirmation: true,
tagSource: function (request, response) {
//console.log("1");
$.ajax({
url: "../City/GetList",
data: { term: request.term },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label + " (" + item.id + ")",
value: item.value
}
}));
}
});
}
});
});
</script>
When tag it selects the values it adds values to the hidden field in CSV format in value attr. i want it to do ID instead anyone know how to ?
A couple of things here. You can set the delimeter instead of a CSV to anything by setting the parameter as such say to an underscore:
$("#mytags").tagit({
...
singleFieldDelimiter: '_',
...
Then you can modify the tag-it.js file on line 197 to say use the ID attribute.
Change:
var tags = node.val().split(this.options.singleFieldDelimiter);
To be
var tags = node.attr("id").split(this.options.singleFieldDelimiter);
So let's say that you modified the hidden field to be:
<input type="hidden" name="tags" class="mySingleField" id="Apple_Orange_Banana" value="Apple_Orange" disabled="true">
You would modify the javascript as such to get the desired output:
$(document).ready(function () {
$("#mytags").tagit({
singleField: true,
singleFieldNode: $('.mySingleField'),
singleFieldDelimiter: '_',
allowSpaces: true,
minLength: 2,
removeConfirmation: true,
tagSource: function (request, response) {
//console.log("1");
$.ajax({
url: "../City/GetList",
data: { term: request.term },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label + " (" + item.id + ")",
value: item.value
}
}));
}
});
}
});
});
Change the tag-it.js file
Comment from line 264
// that.createTag(that._cleanedInput());
// The autocomplete doesn't close automatically when TAB is pressed.
// So let's ensure that it closes.
// that.tagInput.autocomplete('close');
around line 285
var autocompleteOptions = {
select: function(event, ui) {
that.createTag(ui.item);
Create a new function
assignedTagsData: function(){
// Only to be used when singleField option is not seleted
var tags = [];
this.tagList.children('.tagit-choice').each(function() {
tags.push($(this).data('tag_item_data') );
});
return tags;
}
that.createTag(ui.item);
Create tag
var tag = $('<li></li>')
.data('tag_item_data',item) //add this line
.addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all')
.addClass(additionalClass)
.append(label);
Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.