$().trigger working from console but not in code - javascript

I've a html template that modifies the look and feel of a html select box.
<select id='floorinput' class='select multiple-as-single easy-multiple-selection check-list allow-empty' multiple style="width:100px"></select>
The template uses classes to beautify the select box.
The options of select box are being populated by the result of an ajax call, and is working correctly.
The select box finally renders on browser like this:
<span class="select multiple-as-single easy-multiple-selection check-list allow-empty replacement" style="width: 97px; " tabindex="0">
<span class="select-value alt">All</span>
<span class="select-arrow"></span>
<span class="drop-down custom-scroll" style="">
<span class="selected"><span class="check"></span>Floor-1</span>
<span class="selected"><span class="check"></span>Floor-2</span>
.....
<div class="custom-vscrollbar" style="display: none; ">
<div></div>
</div></span>
<select id="floorinput" class="" multiple="" style="width: 100px; display: none; " tabindex="-1">
<option value="Floor-1" selected="selected">Floor-1</option>
<option value="Floor-2" selected="selected">Floor-2</option>
</select>
</span>
The template works by hiding the actual select box and rendering a fancy selectbox instead.
I want to simulate mouse clicks on this select box. The purpose is to deselect the options that are already selected.
The template code cannot handle the programmatic clicks on options of #floorInput (the actual html input).
So I decided to click the spans like:
var j = 0;
//DEselect selected floors programtically
$("#floorinput option").each(function () {
if ($(this).attr("selected") == "selected") {
console.log('should deselect this:' + $(this).text());
$('.select-value.alt').click();//simulate click to open dropdown
$('.drop-down.custom-scroll span.check')[j].click();//perform click. ERROR here
}
else {
console.log('already selected :' + $(this).text());
}
j++;
});
I am using chrome Version 22.0.1229.94 m on Windows 7.
The code throws an error like :
Uncaught TypeError: Cannot call method 'click' of undefined
But it works as expected when I call the same methods through Chrome's console:
$('.select-value.alt').click();
$('.drop-down.custom-scroll span.check')[0].click();//select or deselect first option
Possible cause of the problem may be the markup of select box is not available immediately after the call of $('.select-value.alt').click();
But I've tried delaying the second method call by several methods and it doesnt work.
Any scenario where jquery methods are working through console but not during actual execution?
Please help.
PS:The spam prevention is not letting me upload the screenshot :(.

Related

The drop down element is not locating

Requirement : Click on the drop down and the drop down should open.
DOM:
<span class="select2 select2-container select2-container--default select2-container--below select2-container--open" dir="ltr" data-select2-id="3522" style="width: 208.328px;" xpath="1">
<span class="selection">
<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-disabled="false" aria-labelledby="select2-_ID-container" aria-owns="select2_ID-results" aria-activedescendant="select2_ID-result-pwlg-2">
<span class="select2-selection__rendered" id="select2_ID-container" role="textbox" aria-readonly="true" title="Choose Inco Term">Choose Inco Term</span>
<span class="select2-selection__arrow" role="presentation">
<b role="presentation"></b>
</span>
</span>
</span>
The element is located on the UI:
But when I use the same id on the code as below:
cy.get('#select2_ID-container').click({force:true})
Then I get the following error:
Timed out retrying: Expected to find element: #select2_ID-container, but never found it.
I also tried {force: true}:
cy.get('#select2_ID-container').click({force:true})
There is a different id shown above, perhaps you want
cy.get('[id="select2_ID-container"]').click()
Perhaps you are looking for role="combobox", since this is likely to be the dropdown.
cy.get('span[role="combobox"]').click({force:true})
#select2_ID-container is the selector for the first option in the dropdown list which is Choose Inco Term. You can use this to open the drop down.
cy.get('[aria-owns="select2_ID-results"]').click()
OR
cy.get('[aria-activedescendant="select2_ID-result-pwlg-2"]').click()
Or, You can also use the text to find and click.
cy.contains('Choose Customer').click()
The jQuery select2 has a visible textbox which can be clicked to show the options.
If you're having trouble with the ID, this is how I would approach the test
cy.get('.select2 [title="Choose Inco Term"]')
.as('select2') // alias the textbox
.click() // open the options list
// Options now open
cy.contains('li.select2-results__option', 'TextOfOption').click() // choose an option
// Verify
cy.get('#select2')
.find('li.select2-selection__choice') // choice is listed under textbox
.should('contain', 'TextOfOption') // check the text
// Remove
cy.get('#select2')
.find('.select2-selection__choice__remove') // remove button
.click()
cy.get('#select2')
.should('not.contain', 'TextOfOption') // check text has gone
Sometimes cypress requires a mouse move. Try this too:
cy.get('[id="select2_ID-container"]').trigger('mousemove').click()
Also make sure the element is present / not timedout by checking the command logs : https://docs.cypress.io/api/commands/click#Command-Log
Finally I found a solution to this. I tried all of the above solutions, but neither worked for me. This was due to the version issue. I simple updated the Cypress to the latest version 10.0.1 and ran the test and it worked. Also the dropdown is not located because the page was not loaded properly. The click action was performed on the automation before the page loads completely. So I added cy.wait(10000) before clicking the dropdown. I think the version is not the main problem. The main problem is the page load.
Thank you all for your time. :)

AngularJS: Dynamically change select item of a dropdown list control using

I want to dynamically change select item of a dropdown list control using Angular JS, but it does not change the view.
I tried this one but no result yet!
Controller:
$scope.dischargeType = {id:0,title:''};
$scope.setSelect = function() {
debugger;
$scope.dischargeType = $scope.dischargeTypes[1];
alert($scope.dischargeType.title);
// it shows that the $scope.operationType get the value,but no changes on html
}
View:
<label class="col-sm-3 control-label">Discharge Type</label>
<div class="col-sm-9">
<select ui-select2 data-ng-model="dischargeType" id="add-dischargeType" name="dischargeType">
<option data-ng-repeat="item in dischargeTypes" value="{{item.id}}">{{item.title}}</option>
</select>
</div>
Thank you indeed.
From the code you posted... It doesn't look like you're actually calling the setSelect function in your code.
So basically you have a function made to do something, but if you never call it, it won't actually execute. Also, you may want to mention whether or not you're getting errors in the console window of chrome when you're viewing the page.

How can I create this switch behaviour via Javascript?

First of all, I am really sorry that I could not give specific title about the issue. I have a .net 4.6.1 view page.
I want to create this feature.
Depending on the DepositType, the DefaultDeposit should display either a £ sign or %.
One of the logic, I already tried was to create another property called DefaultDepositPercent. Create a Input Box which is hidden underneath and use Jquery to display or hide this Input Box. Then in my service layer, pass the value inputted in the DefaultDepositPercent to DefaultDeposit.
However, there was an inconvenience that the mvc form also passes the DefaultDeposit value as 0. And there is also an issue of someone fiddling with the Javascript.
I have googled but could not find any answers. It is likely because I could describe the issue in few words.
Any direction would be helpful. Thanks
In bootstrap we just have to place the span tag above or below the input element to get the Prefix or Postfix effect. More Details Here
So the idea is first not to have this post / prefix span tag initially but add it either on DOM ready event or when the drop down selection changes using Jquery insertBefore and insertAfter. Here is a working sample. Hope this is helpful.
$(function() {
SetUpDepositTextBox(); // set up the input box once when DOM is ready
$('.DepositType').on('change', function() {
SetUpDepositTextBox(); // set up the text box when ever the dropdown changes
});
});
function SetUpDepositTextBox() {
$('#depositDefaultWrapper span').remove();
var $this = $('.DepositType');
if ($this.val() == "Amount") {
$('<span class="input-group-addon">£</span>').insertBefore('#depositDefaultWrapper input');
} else {
$('<span class="input-group-addon">%</span>').insertAfter('#depositDefaultWrapper input');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
Deposit Type
<select class="DepositType form-control">
<option value="Amount">Amount</option>
<option value="Percentage">Percentage</option>
</select>
Default Deposit
<div id="depositDefaultWrapper" class="input-group">
<input type="text" class="form-control" value="10">
</div>

Show/hide fields depending on select value parent/sub

So, I want to show some PvP/PK content based on server. I do not need help with the script - I have it. What I need help with is how to properly show the fields. If Custom is selected, it automatically shows the Custom - PvP field content, but you have the option to select the PK field content. When No Custom is selected, it automatically shows No Custom - PvP field content, but you have the option ot select the PK field content. I have a simple show/hide fields content that I found (on here, I think, when I was searching), but I don't know how to add parent/sub (what I need).
Example of what I want:
Current script: https://jsfiddle.net/Aiphira/f9q0qjdr/
$(document).ready(function() {
$.viewMap = {
'view1' : $('#view1'),
'view2' : $('#view2')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="viewSelector">
<option value="view1">No Custom</option>
<option value="view2">Custom</option>
</select>
<div id="view1">
asd
</div>
<div id="view2">
qwe
</div>

Populate a hidden form field using the div of a drop menu (drop down menu is created using divs not select, option etc)

I have a form.
Please note I must use divs for creating the form drop down and not the select option method etc. It just has to be done that way. The code is below.
<form action="url.asp" method="get">
<div class="search-button"><i class="fa fa-search"></i><input type="submit" /></div>
<div class="search-drop-down">
<div class="title"><span>Choose Category</span><i class="fa fa-angle-down"></i></div>
<div class="list">
<div class="overflow">
<div class="category-entry" id="Category1">Category One</div>
<div class="category-entry" id="Category2">Category Two</div>
</div>
</div>
</div>
<div class="search-field"><input type="text" name="search-for" id="search-for" value="" placeholder="Search for a product" /></div>
<input type="hidden" id="ChosenCategory" name="ChosenCategory" value="CATEGORY1 OR CATEGORY2 (WHICHEVER SELECTED)" />
</form>
As shown in the code above I need to populate the hidden field value as per the chosen option which the user selects in the drop down.
I have used about 20 different variations of getElementById or onFocus functions but cannot get it to work.
The only thing I can get to work is the following JavaScript and it just populates the hidden field value with the first id ignoring completely which one has actually been selected(clicked) by the user;
var div = document.getElementById('DivID');
var hidden = document.getElementById('ChosenCategory');
hidden.value = div.innerHTML;
I'm running classic asp so if there is a vbscript way then great, otherwise if I have to use JavaScript to do it then as long as it does the job I'll be happy still.
A click handler on the options could be used to update the value.
No jQuery or any other external library is needed. Below is a working example. Of course, in your case the input element could be of type hidden, but I made it text here for the sake of demonstration.
//Add the click handlers
var options = document.getElementsByClassName('option');
var i = 0;
for (i = 0; i < options.length; i++) {
options[i].addEventListener('click', selectOption);
}
function selectOption(e) {
console.log(e.target);
document.getElementById('output').value = e.target.id;
}
div {
padding: 10px;
}
div.option {
background-color: #CCC;
margin: 5px;
cursor: pointer;
}
<div>
<div class="option" id="Category1">Category One</div>
<div class="option" id="Category2">Category Two</div>
</div>
<input type="text" id="output" />
You should be able to achieve what you're after with a fairly simple setup involving listening for clicks on two separate <div> elements, and then updating an <input> based on those clicks.
TL;DR:
I've put together a jsfiddle here of what it sounds like you're trying to make work: https://jsfiddle.net/e479pcew/5/
Long version:
Imagine we have 2 basic elements:
A dropdown, containing two options
An input
Here's what it might look like in HTML:
<div class="dropdown">
<div id="option-one">Option 1</div>
<div id="option-two">Option 2</div>
</div>
<input type="text" id="hidden-input">
The JavaScript needed to wire these elements up should be fairly easy, but let me know if it doesn't make sense! I've renamed things throughout to make things as explicit as possible, but hopefully that doesn't throw you off.
One quick thing - this is an incredibly 'naive' implementation of this idea which has a lot of potential for refactoring! However I just wanted to show in the most basic terms how to use JavaScript to make this stuff happen.
So here we go - first things first, let's find all those elements we need. We need to assign variables for the two different dropdown options, and the hidden input:
var optionOne = document.getElementById("option-one");
var optionTwo = document.getElementById("option-two");
var hiddenInput = document.getElementById("hidden-input");
Cool. Next we need to make a function that will come in handy later. This function expects a click event as an argument. From that click event, it looks at the id of the element that was clicked, and assigns that id as a value to our hiddenInput:
function valueToInput(event) {
hiddenInput.value = event.target.id;
}
Great - last thing, let's start listening for the clicks on specific elements, and if we hear any, we'll fire the above valueToInput function:
optionOne.addEventListener("click", valueToInput, false);
optionTwo.addEventListener("click", valueToInput, false);
That should get you going! Have a look at the jsfiddle I already linked to and see if it makes sense - get in touch if not.
Are you allowed to use JQuery in this project? It would make your life a lot easier. You can detect when a div is clicked and populate the hidden field.
This could do it:
$(document).ready(function() {
$('.category-entry').click(function() {
$('#ChosenCategory').val($(this).text()); }); });

Categories