Jquery assign value to select2 dropdown - javascript

I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?
Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??
1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
b. $row.find('select .row-item').val(item.itemID).trigger('change');
$(function() {
var data = data1
var html = '';
html += '<thead><tr>';
html += '<th>Item</th>';
html += '<th>Description</th>';
html += '<th>Qty</th>';
html += '<th>Total</th>';
html += '</tr></thead>';
html += '<tbody class="acc_table">';
data.forEach((item, index) => {
html += '<tr class="acc-row">';
html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
html += '</tr>';
//at here I assign the data to select2
$('select.row-item').eq(index).val(item.itemID);
});
html += '</tbody>';
$('.item tbody').empty();
$('.item').append(html);
$('.row-item:last').select2();
$('.item').DataTable({
"paging": false,
"ordering": false,
"info": false,
"searching": false,
});
})
const data1 = [{
"itemID": "10",
"itemName": "Item 1",
"itemQty": "1",
"totalAmount": "50.00"
},
{
"itemID": "20",
"itemName": "Item 2",
"itemQty": "5",
"totalAmount": "150.00"
}
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>
<table class="item">

On closer look, your line:
var $row = $(html);
$row is not used later on, so $row...whatever has no effect. You keep building the html and later do $('.item').append(html);.
So changing the select value within $row has no effect because $row is not appended, only the unchanged html variable.
As you're building HTML, you can add selected directly to the html:
html += '<option value="10"' + (item.itemID == 10 ? "selected" : "") + '>ITEM 1</option>'
html += '<option value="20"' + (item.itemID == 20 ? "selected" : "") + '>ITEM 2</option>'
Alternatively, if the html build can't be changed (or prefer not to, to keep it cleaner), add the itemID has a data-value and then use code later
html += '<select class="row-item" data-itemid="' + item.itemID + '">'
and then use jquery to set the .val(value) based on .data(itemid"):
$('.item').append(html);
$('select.row-item').each(function() {
$(this).val($(this).data("itemid"));
$(this).select2();
});
Note: you only need .trigger("change") after you've converted the select to a select2 - if it's not a select2 yet, then no need to call .trigger("change") (unless, of course, you have some other code that relies on this change and needs to run during initialisation, but would be better to explicitly call that rather than raise an event).

Related

Trouble trying to use JSON and JS with jQuery

I'm trying to get the field 'sigla' from a JSON file and put it on a HTML 'option object', but it's refusing to work as it should.. hope some of you out there can help me with that!
This is a sample of the JSON file:
{
"estados": [
{
"sigla": "AC",
"nome": "Acre",
"cidades": [
"Acrelândia",
"Assis Brasil"
]
},
{
"sigla": "AL",
"nome": "Alagoas",
"cidades": [
"Água Branca",
"Anadia"
]
}, ...
]
}
Script:
<script>
$.getJSON("json/estados.json", function (data){
$.each(data.estados, function (keyEstados, valEstados){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(valEstados.sigla, function (keySigla, valSigla){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
});
</script>
Where it should fit in:
<div class="col-sm-6">
<div class="inputBox">
<div class="inputText">Selecione seu estado*
<select id="selection" name="estado_php" required>
<option value="" disabled="disabled" selected>UF</option>
</select>
</div>
</div>
</div>
It seems to me that you are fetching the valEstados.sigla as it was an object or an array ($.each(valEstados.sigla) and it has the value you need to set the options.
Besides that, you are setting a disabled option and the html of the select one time for each data.estados instead of just once.
This should work:
$.getJSON("json/estados.json", function (data) {
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(data.estados, function (keyEstados, valEstados) {
output += '<option value="' + valEstados.sigla + '">' + valEstados.sigla + '</option>';
});
$('#selection').html(output);
});
Have you tried using the "developer" mode in your browser to set breakpoints in your code to debug it? E.g. on Firefox, the menu has a top level entry to "Web Developer"->"Debugger".
If you do, I think you will find have mixed up your loops. The first loop looks OK in that
$.each(data.estados, function (keyEstados, valEstados){...
should match the list starting
"estados": [...]
However, I don't think the second loop starting
$.each(valEstados.sigla, function (keySigla, valSigla){
is needed. I think your code needs to look more like this:
$.getJSON("json/estados.json", function (data){
var output = '';
output += '<option value="" disabled="disabled" selected>UF</option>';
$.each(data.estados, function (keyEstados, valEstados){
output += '<option value="' + valSigla + '">' + valSigla + '</option>';
});
$('#selection').html(output);
});
(not tested, but it basically gets rid of the inner loop).

How to insert option values in select using Prototype JS?

This is my js code:
html = "";
Object.keys(obj).forEach(function(key) {
html += "<option value='" + obj[key].entity_id + "'>" + obj[key].name + "</option>";
});
$('_accountmedical_location').insert({ 'after' : html });
I wonder if there is a function from prototype which insert some html code inside an element, like:
$('_accountmedical_location').insert({ 'inside' : html });
I already have the option html code, I just simply want to put it inside my select. How can I do that ? thx

Add Checkbox validation

Currently the date and year is being verified but I would like to add a checkbox to the list.
Form code:
var html = '';
html += '<div class="ac-overlay"></div>';
html += '<div class="ac-container">';
html += '<h2>' + settings.title + '</h2>';
html += '<p>' + copy.replace('[21]','<strong>'+settings.minAge+'</strong>'); + '</p>';
html += '<div class="errors"></div>';
html += '<div class="fields"><select class="month">';for(var i=0;i<months.length;i++){
html += '<option value="'+i+'">'+months[i]+'</option>'}
html += '</select>';
html += '<input class="day" maxlength="2" placeholder="01" />';
html += '<input class="year" maxlength="4" placeholder="2016"/>';
html +="<br><br>";
html +='<p><input class="smoker" type="checkbox"/>Please verify that you are a smoker.</p>';
html +="<br>";
html += '<button>Submit</button></div></div>';
Validation script:
validate : function(){
_this.errors = [];
if (/^([0-9]|[12]\d|3[0-1])$/.test(_this.day) === false) {
_this.errors.push('Day is invalid or empty');
};
if (/^(19|20)\d{2}$/.test(_this.year) === false) {
_this.errors.push('Year is invalid or empty');
};
_this.clearErrors();
_this.displayErrors();
return _this.errors.length < 1;
},
I played around a bit with the following code but something is missing:
if ("Not sure what to enter here to validate the checkbox.".test(_this.smoker) === false) {
_this.errors.push('You have not selected if you are a smoker');
};
Was a bit of a work around but ended up changing the Checkbox to enable and disable the verify button.
$(document).ready(function(){
$('#isAgeSelected').change(function(){
if(this.checked)
$('#autoUpdate').fadeIn('slow');
else
$('#autoUpdate').fadeOut('slow');
});
});
html +="<br><br>";
html += '<p><input type="checkbox" id="isAgeSelected"/> Please verify the date above is correct.';
html += '<div id="autoUpdate" class="autoUpdate" style="display:none"><button>Submit</button></div>';
html += '</div></div>';
See how it works here: http://jsfiddle.net/3WEVr/1135/

DOM manipulation when the value of trigger change

What's the best way to do this kind of manipulation case :
When the trigger using the combo box is change, I want to change the type of the textField that has previously been added to the form.
My sample data collection :
function DataProvide(){
selectValues = {
"choose" : "-Choose-",
"id" : "ID",
"emp_name" : "Employee Name",
"photo_path" : "Photo Path",
"emp_id" : "Employee ID",
"start_date" : "Start Date",
"birth_date" : "Birth Date"
};
$.each(selectValues, function(key, value) {
$('#data1_1')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
$(document).ready(function() {
DataProvide();
});
Data has been displayed in the combobox.
Then I add a field to a form using the $.append()
var count = 1;
$(".addCF").click(function(){
count += 1;
var $row = $('<tr>'
+ '<td>' + '</td>'
+ '<td>' + '<input id="data2_' + count + '" type="text" name="data2[]" class="data2" value="" placeholder=""/>' + '</td>'
+ '<td>' + '<input id="data3_' + count + '" type="text" name="data3[]" class="data3" value="" placeholder=""/>' + '</td>'
+ '<td>' + 'Remove' + '</td>'
+ '</tr>').appendTo("#customFields");
$row.find('td:first').append($('#data1_1').clone())
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
count -= 1;
});
Until this point I've been as successful as I want.
But I want to make a small change to 3rd column. How best way to manipulate this form when trigger (combo box) that I select for example "start_date" then the field will be changed to use the class "onlyDate" that I add jQuery UI to display the date options.
I added :
$(".onlyDate").datepicker({
dateFormat: "dd-mm-yy"
});
Then to check the value of the combo
$("#customFields").on('change', '.tabelBaru', function() {
if(nilai=='gender'){
$this.closest("tr").find(".data3").replaceWith(
'<select name="data3[]" class="data3">'
+ '<option value="man" selected >Man</option>'
+ '<option value="woman">Woman</option>'
+ '</select>'
)
}else if(nilai=='start_date'){
$this.closest("tr").find(".data3").replaceWith(
'<input type="text" name="data3[]" value="" class="onlyDate"/>'
)
}
};
But jQueryUI datepicker does not appear as usual. But if the normal form (without using $.append) all running normally.
How do I fix it?
$(".onlyDate").datepicker({
dateFormat: "dd-mm-yy"
});
When this code execute, it will only find out that current statement's object whit class name onlyDate.
After that any object with class name onlyDate append on the page won't execute the datepick code.
Maybe you should try out jquery function "delegate" or execute the datepicker code after each append.

Javascript selected item value not pulling correctly

I'm doing a select box with a list of items(dynamically created from an XML created by a webservice), and I'm unable to pull the selected value correctly. Here is what is happening.
What I'm sending:
onchange="changeFunction(this.options[this.selectedIndex].value)"
What I'm receiving:
function (a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!=
I'm the only thing I'm using is some self built functions and jQuery.
Any help would be superb.
Edit: here is the change function. All it is intended to do is build a form populated with values for given selected item.
function changeFunction(selection) {
console.log(selection);
$('#right').empty();
var addNewFields = 'these will be the fields';
$('#right').append(addNewFields);
}
Here is the select in question:
<select class="userSelection" id="userSelection" size="10" style="width:150px;" onchange="changeFunction(this.options[this.selectedIndex].value)"></select>
This is literally all the code in the html part of it. It's being populated via ajax, and there are 2 divs, one for left, containing the select, and one for right, containing the content for the user.
Just for giggles, here is the code creating the options:
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
$('#userSelection').append(optionTag);
var optionTag = '<option value="' + $(this).find('optionID').text + '" >' + $(this).find('optionName').text() + '</option>';
should be:
var optionTag = '<option value="' + $(this).find('optionID').text() + '" >' + $(this).find('optionName').text() + '</option>';
Notice that $(this).find('optionID').text should be $(this).find('optionID').text().
or even better, to avoid this soup:
var optionTag = $('<option/>', {
value: $(this).find('optionID').text(),
html: $(this).find('optionName').text()
});
When you set the event handler of a DOM object to a function it get passed an event object as it's argument.
selectBox.onchange = function(event) {
changeFn(this.options[this.selectedIndex].value);
};

Categories

Resources