How to fetch values of a drop down box with CasperJS - javascript

I was looking in several threads about retrieving values from a drop down box to use the values for a later time in the casperjs script.
So my issue is that I can't fetch the values from my drop down box and actually use it in my next step, for now just to echo it out.
This is how my drop down box looks in my web page:
I did tried some examples but it just doesn't work, what am I doing wrong?
casper.then(function() {
var options = this.evaluate(function() {
var options = document.getElementById('selectedNetworkElementOrGroup_TD').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));
});
One problem could be that the drop down box has no id!

You need a basic CSS selector like this one: #selectedNetworkElementOrGroup_TR select:
var options = this.evaluate(function() {
var options = document.querySelector('#selectedNetworkElementOrGroup_TR select').children;
return [].map.call(options, function(opt) {
return { val: opt.value, text: opt.textContent };
});
});
this.echo(JSON.stringify(options));

Related

How to solved always looping select option value from ajax

I have a data, when I update the data (using modal), select option work correctly
When I close the modal, and I click the edit button again, something wrong with select option:
This is my edit modal ajax:
// Function for edit modal plan schedule
$('body').on('click', '.editPlanSchedule', function() {
var Item_id = $(this).data('id');
$.get("/quotation/getEditPlanSchedule" + '/' + Item_id, function(data) {
console.log(data['product_plan']);
$('.modal-title-edit').html("Edit Plan Schedule Item");
$('#saveBtn').val("Update");
$('#updatePlanSchedule').modal('show');
$('#id').val(data['data'].id);
$('#qno').val(data['data'].qno);
$('#b_amount').val(data['data'].b_amount);
// $('#product_plan_edit').val(data.product_plan);
data['product_plan'].forEach(function(item, index) {
$('#product_plan_edit').append($('<option>', {
id: item.id,
value: item.productplanID,
text: item.productplanID
}));
if(data['data'].product_plan == item.productplanID){
$('#'+item.id).attr('selected',true);
}
});
})
});
This is the method from controller:
public function getEditPlanSchedule($id)
{
$item['data'] = QuotationPlanSchedule::find($id);
$item['product_plan'] = ProductPlan::orderby('id', 'asc')->get();
return response()->json($item);
}
You have to clear all options before adding again:
$("#product_plan_edit").empty();
Either .empty the container or don't use append (better for the DOM update)
I am a little confused about your use of data['data'].product_plan to test the ID. In any case you can see the principle
$('#product_plan_edit').html(
data['product_plan'].map(item => `<option value="${item.productplanID}">${item.productplanID}</option>`).join('')
);
$('#product_plan_edit').val(data['data'].product_plan); // select item.productplanID === data['data'].product_plan

Obtain all items in a select2 dropdown list using javascript where data is loaded from ajax call

The example I would like to replicate is this: https://jsfiddle.net/bindrid/hpkqxto6/ . I need to load data from the server, form a grouping of them and when selecting one item from one group all other items inside this particular group would become disabled. The difference is that I must load data from the server using an ajax call inside select2, instead of listing the < option > elements inside the select element and form a grouping this way. I have trouble selecting all available items in the dropdown list during the javascript manipulation in order to disable items from the same group (line 29 in the above example fails due to there being no < option > elements in html, instead I think they are loaded later and javascript is not able to find them).
The html part looks as follows:
<select class="form-control attributoSelect2" name="attributiSelezionati" id="attributoSelect2" value="#Model.AttributiSelezionati"></select>
There are no < option > items inside < select > because the ajax call takes care of populating the list, like this:
$('.attributoSelect2').select2({
placeholder: "Cerca Attributo",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.CercaAttributi())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Descrizione,
children: item.Children.map(function (itemC) {
return {
id: itemC.Id,
groupid: itemC.GroupId,
text: itemC.Descrizione,
};
})
};
})
};
}
}
});
Finally my javascript looks as follows:
$('.attributoSelect2').on("select2:selecting", function (evt, f, g) {
disableSel2Group(evt, this, true);
});
$('.attributoSelect2').on("select2:unselecting", function (evt) {
disableSel2Group(evt, this, false);
});
function disableSel2Group(evt, target, disabled) {
var selId = evt.params.args.data.id;
var group = evt.params.args.data.groupid;
var aaList = $(".attributoSelect2 option");
$.each(aaList, function (idx, item) {
var data = $(item).data("data");
var itemGroupId = data.groupid;
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The problem is that this line:
var aaList = $(".attributoSelect2 option");
does not load all the option elements because they are not loaded yet. They would be loaded later on using the ajax call. Does anyone have an idea of how to resolve this problem?

Autocomplete: how to get automatically value on focus if no values selected

From the comment in this question, I've seen how to set an autocomplete field to empty if no element from the list has been selected.
What I am trying to implement is that when a user does not select any element from the autocomplete list and switches to the next field, one of the following should happen:
If there was at least on element displayed in the autocomplete list, take automatically the first element of that list. In the screenshot below, Mannheim should be automatically selected if the user goes to another field without selecting any element.
If no element was displayed, make the field empty again.
If tried the suggestions from here and here, but without success.
This is my code:
var cities = //function that provides a list of cities depending on the input string (edited to clarify)
$('.autocomplete-city').autocomplete({
source: function (request, response) {
response($.map(cities( request.term ), function (value, key) {
return {
label: value.label,
value: value.value
}
}));
},
// manage what happens if user does not click any option from autocomplete
change: function(event, ui){
if (ui.item == null){
if ( list_from_autocomplete == null ){ // I tried here several possibilities but none seem to work
$(this).val('');
$(this).focus();
} else {
$(this).val( first_item_in_list ); // Despite the existing questions, I could not make it work...
}
}
},
minLength: 2,
autoFocus: true,
});
How could this be done?
You could search all the cities that contains the user input and if you get only one result, put it in the autocomplete.
1) So, in the change event you could check if user selected an item:
change: function(event, ui){
if(ui.item){
//user select an item
}
else{
//here let's try to set the autocomplete
}
2) Search the cities that contains the user's input:
var result = cities.filter(function( obj ) {
return obj.label.indexOf(searched);
});
3) Finally, if you get just one result, set the autocomplete with that value:
if(result.length==1){
$(this).val(result[0].label);
}
Please see following snippet:
var cities = [
{"label":"Alessandria","id":"AL"},
{"label":"Milano","id":"MI"},
{"label":"Pisa","id":"PI"},
{"label":"Pistoia","id":"PT"}
];
$(".autocomplete-city").autocomplete({
source: cities,
select: function(event, ui){
if(ui.item){
console.log('select', ui.item.label);
return ui.item.label;
}
else{
console.log('select with null value');
}
},
change: function(event, ui){
var searched = this.value;
console.log("Searched: " + searched);
if(ui.item){
console.log('change', ui.item.id);
}
else{
console.log('change with null value');
var result = cities.filter(function( obj ) {
return obj.label.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
});
if(result.length>0){
$(this).val(result[0].label);
}
else{
//clear the autocomplete
$(this).val("");
}
}
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input class="autocomplete-city"/>
In the above example there are following cities: Alessandria, Milano, Pisa, Pistoia.
If you digit in textbox "Mil" or "Ale" and just press the tab, the autocomplete will be filled with the single result starting with "Mil" or "Ale".
Instead, when you digit "Pis" the autocomplete will be cleared.
I hope it was clear, bye.
Updated:
In order to get the first result when user leaves the autocomplete without selecting any city, you could check result.length>0 and set the first value from result in to the autocomplete:
var result = cities.filter(function( obj ) {
return obj.label.toLowerCase().indexOf(searched.toLowerCase()) !== -1;
});
if(result.length>0){
$(this).val(result[0].label);
}
else{
//clear the autocomplete
$(this).val("");
}

Fill select on click with Knockout

I'm having a trouble when I'm trying to load the data of select.
Once the page is loaded, when I do my first click on the select it doesn´t show nothing, any data.
I close it and when I click again on the select it shows me the data.
http://jsfiddle.net/r3AA9/19/
Any suggestion?
HTML
<div>
<select data-bind="options: values, value: option, optionsCaption: 'Selecione...', event: { click: onClickSelect }" ></select>
<label data-bind="text: option"></label>
JS
var ViewModel = {
option : ko.observable(),
values : ko.observableArray()
};
ViewModel.onClickSelect = (function() {
//Simulate server side
setTimeout(function()
{
ViewModel.values(["one", "two", "three"]);
}, 2000);
});
ko.applyBindings(ViewModel);
Any suggestion?
there is a way to do this.
try this code
ViewModel.onClickSelect = function (v, e) {
var sel = e.target;
if (sel.childNodes.length === 1) {
sel.childNodes[0].innerText = 'Loading...'
setTimeout(function () {
sel.childNodes[0].innerText = 'Selecione...'
ViewModel.values(["one", "two", "three"]);
sel.blur();
v.openSelect(sel);
}, 2000);
}
};
//to open 'select' programmatically
ViewModel.openSelect = function (element) {
if (document.createEvent) {
var e = document.createEvent("MouseEvents");
e.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(e);
}
else if (element.fireEvent) element.fireEvent("onmousedown");
};
ko.applyBindings(ViewModel);
Demo JSFiddle
It's natural.
When you load the page for the first time, the values array is empty, so there are nothing to show in the dropdown. Then when you click on the drop down, you trigger the select, which invokes this code:
setTimeout(function()
{
ViewModel.values(["one", "two", "three"]);
}, 2000);
What this code does is, after waiting two seconds, it loads the 3 values in the drop down list. So, if you close the drop down list, and click on it again at least 2 seconds later, the options are there. If you do it quickly enough you'll realize that clicking again in the drop down before the 2 seconds go by, the select is already empty.
So the code is working perfectly, as expected. For your question it's impossible to know what you was trying to do.

Selectize.js manually add some items

I want add some items to a selectized input after user clicks on a button. The input data are loaded via Ajax. When I call addItem(value) no thing happens. But if I try to type some string in the input it loads data and after this addItem(value) will works.
https://github.com/brianreavis/selectize.js/blob/master/docs/api.md
This plugin does not attempt to load an item metadata from the server. You need to first add an option using addOption() method. Next, you can use addItem().
v.selectize.addOption({value:13,text:'foo'}); //option can be created manually or loaded using Ajax
v.selectize.addItem(13);
You can add options like this:
var $select = $(document.getElementById('mySelect')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value: 1, text: 'whatever'});
selectize.refreshOptions();
This only adds the option as possible selection. Now you can use addItem to add the new option to the list:
selectize.addItem(1);
This does not need a refresh function. You do not need to use "refreshOptions" if you add the new option immediately.
Try this.
$('.select-ajax-city').each(function() {
if (this.selectize) {
for(x=0; x < 10; ++x){
this.selectize.addOption({value:x, text: x});
}
}
});
Try This
var $select = $(document.getElementById('Your-element-id'));
var selectize = $select[0].selectize;
selectize.addOption({value: '2', text: 'test'});
selectize.addItem('2');
If you want to be more flexible then you can use the length like this.
var $select = $(document.getElementById('Your-ID'));
var selectize = $select[0].selectize;
var count = selectize.items.length + 1;
selectize.addOption({ value: count, text: 'value-here' });
selectize.addItem(count);
$('#id').selectize({
create: function(input,callback){
$.ajax({
url: "",
type: "POST",
data: {value : input},
success: function(res) {
callback({value: res, text: input});
}
});
}
});
For adding new options dynamically is neccesary to call clearOptions for clean the options, adding the new list options using addOption and call refreshState function after all.
var listItems = [{id: 1, value: 'Element1'},{id: 2, value: 'Element2'}]
/* Initialize select*/
var $select = $('#element').selectize();
var control = $select[0].selectize;
control.clear()
control.clearOptions();
/* Fill options and item list*/
var optionsList = [];
var itemsList = [];
$.each(listItems, function() {
optionsList.push( {
value: this.id,
text: this.value
});
itemsList.push({
value: this.id,
text: this.value
});
});
/* Add options and item and then refresh state*/
control.addOption(optionsList)
control.addItems(itemsList);
control.refreshState();
/* Add element 1 selected*/
$.each(result, function() {
if (this.id == 1) {
control.addItem(this.Tax.id,this.Tax.title);
}
});
This is another way you can add items manually if you have set other values to your select:
$('select').selectize({
create: true,
sortField: "text",
hideSelected: false,
closeAfterSelect: false,
options:[
{
text:'<text goes here>',
value:'<value goes here>',
}
]
});

Categories