Jquery repeater with select2 not working properly - javascript

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) {
},
})

Related

Load dropdown list based on another dropdown selected item

Load dropdown list based on another dropdown selected item
Here my js :
$("#Ownerstate").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgency").html(procemessage).show();
var url = "/Index/GetAgencyState/";
// Get state code
var Ownerstate = $("#Ownerstate :selected").val();
$.ajax({
url: url,
data: { statecode: Ownerstate },
cache: false,
type: "POST",
success: function (carData) {
if (carData.length > 1) {
$("#OwnerAgency").prop("disabled", false);
}
var select = $("#OwnerAgency");
select.html('');
$.each(carData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Not getting load dropdownlist

Jquery UI auto complete (with custom listing) not working

I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?
Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});
Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.

How to populate data in autocomplete textbox when a button is clicked?

I have a textbox with jquery autocomplete feature.It populates data based on a condition if '/' is entered and then a character.But i want to populate all the data in the autocomplete list when a button is clicked inspite of what ever data is there in the textbox.
My button :
<asp:Button ID="Button2" runat="server" Text="Button" />
And my autocomplete function with condition to populate data is:
<script type="text/javascript">
function pageLoad(sender, args) {
$(function () {
$("#<%=txtCu.ClientID %>").autocomplete({
source: function (request, response) {
if(request.term.indexOf("/") == (request.term.length-1) && enterFlag)
{
var term = request.term.slice(0,-1)
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
},
error: function (response) {
},
failure: function (response) {
}
});
};
},
select: function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); })
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<div><table><tr><td width='200px'>" + item.label + "</td>" + "<td width='110px'>" + item.val.split('~')[6] + "</td>" + "<td>" + item.val.split('~')[4] + "</td></tr></table></div>").appendTo(ul);
};
});
}
Do this to get the expected result
ASP Button, add class property CssClass
<asp:Button ID="Button2" runat="server" Text="Button" CssClass="btn"/>
and jQuery Part
$(document).on("click","btn",function(e){
e.preventDefault();
$("#<%=txtCu.ClientID %>").autocomplete("search", "");
$("#<%=txtCu.ClientID %>").autocomplete("select",function (e, i) {
$("#<%=hdnCr.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnCr.ClientID %>").val(-1);
document.getElementById('<%=txtCu.ClientID%>').value = "";
return false;
}
checkddlcustomerinfo();
}
);
});
to close autocomplete on outside click
$(document).on('click', function(e){
var target = $(e.target);
if(target.attr("id") != "txtCu" && target.attr("class") != "btn")
{
$("#<%=txtCu.ClientID %>").autocomplete('close');
}
});
Note: You must set minLength: 0 in your autocomplete
Working DEMO
see this edit to your autocomplete code:
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetCus") %>',
data: "{ 'prefix': '" + term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('^')[0],
val: item.split('^')[1]
}
}))
$('.ui-autocomplete').hide(); // <-- this line
},
edit XHTML :
<asp:Button ID="Button2" runat="server" Text="Button" Class="myBtn"/>
ps. it might be CssClass="myBtn" haven't used web forms in a bit
then jQuery:
$(function(){
$(document).on('click', '.myBtn', function(e){
e.preventDefault();
//maybe a prevent propigation line too just for other browsers like IE
$('.ui-autocomplete').show();
});
});
});

Tag it submit id not value or label

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);

dynamically create radiobuttons and labels

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.

Categories