I am using the following jquery postcode lookup and I am trying to push values and hard code the process in javascript.
I am using the following to give the postcode textbox a valid postcode, and then forcing the button click to find the addresses.
document.getElementById("idpc_input").value = "LL17 0PN";
document.getElementById('idpc_button').click();
This so far works, after this a dropdownlist appears with the id of 'idpc_dropdown', I am trying to (in javascript or jquery) select an option
Here is what I have done but it does not work
var select = document.getElementById("idpc_dropdown");
document.getElementById("idpc_dropdown").text = '2 Elwy Cottages Heol Esgob';
And also:
var desiredValue = "2 Elwy Cottages Heol Esgob"
var el = document.getElementById("idpc_dropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
UPDATE:
Let me explain the process and order, 1- Type in postcode and press the button to find my address 2- a dropdownlist then renders and appears .. I Think this is why it is not working for my desired dropdownlist as its not loaded when the page is loaded, it is when the button has been pressed
Provided that i is the same as the index of the item you wish to select, I'd set the dropdown's value attribute to that index:
let el = document.getElementById("idpc_dropdown");
for(let i = 1; i <= el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.value = i; // here
break;
}
}
Related
How do I use Jquery to find the last checked/unchecked item and so that I can add or remove them from other two listboxs?
I am creating a dropdown listbox(excludedPeople) with multiselect checkbox with two other listboxs(PrimaryPerson,secondaryPerson) in same form. All three list box are having same set of data during form load. If any item in excludedPeople is selected(checked), I need to remove that item from PrimaryPerson and secondaryPerson and vise-versa.
ASP.Net MVC multiselect Dropdown Listbox code:
#Html.ListBoxFor(m => m.ExcludedPeople, Model.AllPeopleListViewModel,
new { #class = "chkDrpDnExPeople" , #multiple = "multiple"})
jQuery code:
$(".chkDrpDnExPln").change(function ()
{
console.log("Trigger" + $(this).val()); //this code gets the list of all items selected. What I need is to log only last selected/unselected item's val & text into the console.
});
Any help is appreciated. Ask questions if any.
Well, after waiting for 2 days I made a solution myself and posting it here so that others can make use of it.
I made this code for multiselect dropdown listbox with checkboxes in each list item. I expect this to work on similar controls like checked listbox but haven't tested it.
I followed register control and get notified by event so the usage can be made seamless without getting into details.
Usage:
1) include the "JQuery based Library" part into your project as shared or same js script file.
2) Use the below approach to consume the functionality. The event should get you the changed values when the control selection is changed.
RegisterSelectedItemChangeEvent("chkDrpDnctrl#1");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#2");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#3");
$(".chkDrpDnctrl").on("OnSelectionChange", function (e,eventData)
{
var evntArgs = {
IsDeleted: false,
IsAdded: false,
AddedValues: [], //null if no change/None. Else changed value.
DeletedValues: [] //null if no change/None. Else changed value.
};
var source = e;
evntArgs = eventData;
var elementnm = $(this).attr("id");
if (evntArgs !== "undefined" && elementnm != "")
{
if (evntArgs.IsAdded == true)
{
//if excluded checked then remove.
for (var i = 0; i < evntArgs.AddedValues.length; i++)
{
PerformAction (control#, evntArgs.AddedValues[i]);
}
}
if (evntArgs.IsDeleted == true)
{
//if excluded checked then remove.
for (var i = 0; i < evntArgs.DeletedValues.length; i++)
{
PerformAction (control#, evntArgs.AddedValues[i]);
}
}
}
});
JQuery based Library:
function RegisterSelectedItemChangeEvent(selector) {
var dropdownElementRef = selector;
//Intializes the first time data and stores the values back to control. So if any of the checkboxes in dropdown is selected then it will be processe and added to control.
$(dropdownElementRef).data('lastsel', $(dropdownElementRef).val());
var beforeval = $(dropdownElementRef).data('lastsel');
var afterval = $(dropdownElementRef).val();
//storing the last value for next time change.
$(dropdownElementRef).data('lastsel', afterval);
//get changes details
var delta = GetWhatChanged(beforeval, afterval);
//stores the change details back into same object so that it can be used from anywhere regarless of who is calling it.
$(dropdownElementRef).data('SelectionChangeEventArgs', delta);
//prepares the event so that the same operation can be done everytime the object is changed.
$(dropdownElementRef).change(function () {
var beforeval = $(dropdownElementRef).data('lastsel');
var afterval = $(dropdownElementRef).val();
//storing the last value for next time change.
$(dropdownElementRef).data('lastsel', afterval);
//get changes details
var delta = GetWhatChanged(beforeval, afterval);
//stores the change details into same object so that it can be used from anywhere regarless of who is calling it.
$(dropdownElementRef).data('OnSelectionChangeEventArgs', delta);
//fires the event
$(dropdownElementRef).trigger('OnSelectionChange', [delta]);
//$.event.trigger('OnSelectionChange', [delta]);
});
var initdummy = [];
var firstval = GetWhatChanged(initdummy, afterval);
//fires the event to enable or disable the control on load itself based on current selection
$(dropdownElementRef).trigger('OnSelectionChange', [firstval]);
}
//assume this will never be called with both added and removed at same time.
//console.log(GetWhatChanged("39,96,121,107", "39,96,106,107,109")); //This will not work correctly since there are values added and removed at same time.
function GetWhatChanged(lastVals, currentVals)
{
if (typeof lastVals === 'undefined')
lastVals = '' //for the first time the last val will be empty in that case make both same.
if (typeof currentVals === 'undefined')
currentVals = ''
var ret = {
IsDeleted: false,
IsAdded: false,
AddedValues: [], //null if no change/None. Else changed value.
DeletedValues: [] //null if no change/None. Else changed value.
};
var addedvals;
var delvals;
var lastValsArr, currentValsArr;
if (Array.isArray(lastVals))
lastValsArr = lastVals;
else
lastValsArr = lastVals.split(",");
if (Array.isArray(currentVals))
currentValsArr = currentVals;
else
currentValsArr = currentVals.split(",");
delvals = $(lastValsArr).not(currentValsArr).get();
if (delvals.length > 0)
{
//console.log("Deleted :" + delvals[0]);
for (var i = 0; i < delvals.length; i++)
{
ret.DeletedValues.push(delvals[i]);
}
ret.IsDeleted = true;
}
addedvals = $(currentValsArr).not(lastValsArr).get();
if (addedvals.length > 0)
{
//console.log("Added:" + addedvals[0]);
for (var i = 0; i < addedvals.length; i++)
{
ret.AddedValues.push(addedvals[i]);
}
ret.IsAdded = true;
}
return ret;
};
I am using jsTree. Its working fine but I want to get first node's data value in group of tree.
What I want to do?
When I click on any checkbox, then it will click automaticaly first checkbox
I am getting node id for first element but not getting original checkbox.
I have mention my code below.
.on("changed.jstree", function (event, data) {
if(data.action == 'deselect_node' || data.action == 'select_node'){
var parentId = $('#'+data.node.id).parent().parent().attr('id');
var childId = $('#'+parentId+' li:first-child').attr('id');
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
if(data.instance.get_node(data.selected[i]).original.permID){
r.push(data.instance.get_node(data.selected[i]).original.permID);
}
}
A checkbox in a jsTree node is not a checkbox control really, it is an image.
You can get it of course. Based on your script it would go like:
var checkBoxImageElement = $('#'+childId).find('.jstree-checkbox')[0];
Please check out demo: JS Fiddle
I would like to know what the best way would be to loop through a dropdown list in html to see if and item has been selected or not.
I know in C# it would be something along the lines of
int selected = cmbFamily.SelectedIndex;
for (int loop = 0; loop < cmbFamily.Items.Count; loop++)
{
if (selected == -1)
{
MessageBox.Show("please select an item", "Please", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
}
how would I go about in doing this with javascript?
<tr style="font-size:12pt; font-weight:bold; color:#FFFFFF; font-family:High Tower Text;">
<td>Family to join:</td>
<td><select name="drpFamily">
<option/>-select-
<option/>Gambino
<option/>Genovese
<option/>Lucchese
<option/>Colombo
<option/>Bonanno
</select><font color="red">*</font></td>
</tr>
Kind regards
Arian
First off you HTML code is totally wrong. It is not </option>text, it is <option>text</option>
To loop through the options it is as simple as
//var options = document.getElementById("selectId").options;
var options = document.formName.selectName.options;
for(var i=0;i<options.length;i++){
if(options[i].selected){
alert(options[i].value);
}
}
but there is no need to loop through a single select. The easiest way is just to use selected index for a single select.
//var sel = document.getElementById("selectId");
var sel = document.formName.selectName;
var opt = sel.options[sel.selectedIndex];
alert(opt.value);
First: your HTML is wrong.
It should be
<option>-select-
...
or
<option>-select-</option>
...
If you just want the selected value, you can get it via the value attribute of the select element:
var value = document.getElementsByName('drpFamily')[0].value
This only works if there is only one element with name drpFamily. If not, you have to find an appropriate way to select it.
You might want to compare it against the first value (which is selected by default)
if(value !== '-select-')
You could also add a change event listener to the select element:
document.getElementsByName('drpFamily')[0].onchange = function() {
if(this.value !== '-select-') {
//a value other '-select-' than was selected
}
}
I have an .aspx hidden control that stores a defaultId for this dropdown. However, the values in the dropdown can change and sometime the defaultId is listed as one of the selections, other times it isn't. When the drop down clears we run this to reset it:
Global.getComponent("ddlVehicleType").setValue(Global.getComponent("DefaultVehicleTypeId").getValue());
Now when it sets that, if the dropdown doesn't have a value associated with that Id, it displays the actual Id in the field. I have a check for isNumeric now to see when that happens, but how do I make the field display the first value in the list of Id's it DOES have:
var displayedValue = Global.getComponent("ddlVehicleType").getRawValue();
if (IsNumeric(displayedValue)) {
}
Put together a unique little way of doing it, by going through the current populated store of that dropdown on the page:
var newId = 0;
var firstId = 0;
var typeStore = Global.getComponent("ddlVehicleType").getStore();
firstId = typeStore.getAt(0).get('LookupID');
typeStore.each(function(rec) {
if (rec.get('LookupID') == Global.getComponent("DefaultVehicleTypeId").getValue())
{
newId = Global.getComponent("DefaultVehicleTypeId").getValue();
}
});
if (newId != 0) {
Global.getComponent("ddlVehicleType").setValue(newId);
} else {
Global.getComponent("ddlVehicleType").setValue(firstId);
}
I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?
This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.
You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}