addEvent doesn't work with chrome 25 and OSX - google-chrome

I've a problem only with chrome 25 and osx.
I get results with this line
console.log($$('.sort-box-slt-pl-opt'));
But with this lines
$$('.sort-box-slt-pl-opt').addEvent('click', function(event){
console.log('test');
});
the code inside the addEvent handler is never reached.
Did anyone have the same problem ?
I'm working with mootools 1.4, but the same problem happen when i try to use document.getElementsByClassName
thanks.
thank you for your comment but i still have the same trouble.
this is my html structure:
<span id="ead-sort-box-select-bloc">
<select id="ead-sort-box-select" class="divid-slt___cdc_" name="sort-box-ead">
<option class="sort-box-slt-pl-opt sort-box-slt-pl-opt-asc" value="functions/ead/mosaic-results.ajax-html?base=ead&champ1=fulltext&op1=AND&search_type=simple&query1=sdxall%3A1&ssearch-submit-npt.x=0&ssearch-submit-npt.y=0&form-display-only-media=&docs=true&&skippage=here&sf=&so=asc">pertinence</option>
<option class="sort-box-slt-pl-opt sort-box-slt-pl-opt-asc" value="functions/ead/mosaic-results.ajax-html?base=ead&champ1=fulltext&op1=AND&search_type=simple&query1=sdxall%3A1&ssearch-submit-npt.x=0&ssearch-submit-npt.y=0&form-display-only-media=&docs=true&&skippage=here&sf=fucomptitle&so=asc">titre croissant</option>
<option class="sort-box-slt-pl-opt sort-box-slt-pl-opt-desc" value="functions/ead/mosaic-results.ajax-html?base=ead&champ1=fulltext&op1=AND&search_type=simple&query1=sdxall%3A1&ssearch-submit-npt.x=0&ssearch-submit-npt.y=0&form-display-only-media=&docs=true&&skippage=here&sf=fucomptitle&so=desc">titre décroissant</option>
<option> .... </option>
</select>
<span>
I want to execute an ajax function when the user select an option but, the code inside the addEvent is never reached. This is the JS code:
...
if(Browser.chrome && Browser.Platform.mac){
if($('ead-sort-box-select') != null){
var elements = $$('.sort-box-slt-pl-opt');
elements.each( function( element ) {
element.addEvent('click', function(){
console.log('test');
});
});
}
}
...

Related

Alert on change of select option using jQuery in console [duplicate]

is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.
I was trying to output something like this
<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>
$(function(){
$('.check').trigger('change'); //This event will fire the change event.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
});
http://jsfiddle.net/v7QWd/1/
Use val() to change to the value (not the text) and trigger() to manually fire the event.
The change event handler must be declared before the trigger.
Here's a sample
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
To select an option, use .val('value-of-the-option') on the select element. To trigger the change element, use .change() or .trigger('change').
The problems in your code are the comma instead of the dot in $('.check'),trigger('change'); and the fact that you call it before binding the event handler.
Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :
var sortBySelect = document.querySelector("select.your-class");
sortBySelect.value = "new value";
sortBySelect.dispatchEvent(new Event("change"));
$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details".
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>
Based on Mohamed23gharbi's answer:
function change(selector, value) {
var sortBySelect = document.querySelector(selector);
sortBySelect.value = value;
sortBySelect.dispatchEvent(new Event("change"));
}
function click(selector) {
var sortBySelect = document.querySelector(selector);
sortBySelect.dispatchEvent(new Event("click"));
}
function test() {
change("select#MySelect", 19);
click("button#MyButton");
click("a#MyLink");
}
In my case, where the elements were created by vue, this is the only way that works.
You can try below code to solve your problem.
By default, first option select:
jQuery('.select').find('option')[0].selected=true;

All Browsers except Firefox don't react to jQuery .click()

I have the following HTML/Twig structure
<select name="herstellerSelect" class="categoryElement" id="herstellerDropdown" style="display: block;">
<option class="preselect" value="" style="display: block;">Hersteller wählen</option>
{{ _self.cpitems0(categories.categories, categories.categories_info, parts, oop_display, oop_opened) }}
</select>
The Twig macro "cpitems0" generates elements for the
This is the jQuery Code that should, amongst other things, output a text to the console once children (<option> elements of the <select>) are clicked.
$(document).ready(function() {
console.log('CATEGORY SELECTOR TEST');
$("#herstellerDropdown").children().click(function(e) {
e.preventDefault();
console.log('CATEGORY SELECTOR TEST 2');
...
I have also tried
$(document).ready(function() {
console.log('CATEGORY SELECTOR TEST');
$("#herstellerDropdown").on('click', '> *', function(e) {
e.preventDefault();
console.log('CATEGORY SELECTOR TEST 2');
...
Only Firefox (private mode and cleared browser cache) displays the second console.log output, all the other tested Browsers (Brave, Chromium, Opera Developer in private mode with cleared Browser cache on Ubuntu 20.4) only display the first console.log output
Does anyone know why this happens?
Upate 14.10.2021 14:20 -> I have to use $("#herstellerDropdown").on("change" ... ) instead of .$("#herstellerDropdown").click because it's a element.
Generally, I have to use "AJAX Cascading Dropdowns" for what should be realized. I thought I could avoid AJAX and load the server generated content into the DOM and copy the respective elements with $("selectElement").html( elements) but I guess that results in poor performance and bad design so I have to go with the Cascading Dropdowns!
Use on("change" instead of click
Options do not need ID
Why display:block?
Why preventDefault() ?
This works in Chrom(e/ium) and Fx
$(function() {
$("#herstellerDropdown").on("change", function(e) {
console.log(this.value)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="herstellerSelect" class="categoryElement" id="herstellerDropdown">
<option class="preselect" value="" style="display: block;">Hersteller wählen</option>
<option data-val-one="Key0" data-val-two="" data-val-three="" value="entry0">categories_info[keyZero].elementid 0</option>
<option data-val-one="Key1" data-val-two="" data-val-three="" value="entry1">categories_info[keyZero].elementid 1</option>
<option data-val-one="Key2" data-val-two="" data-val-three="" value="entry2">categories_info[keyZero].elementid 2</option>
</select>

protractor testing on multi select giving 'Element not visible' error

I have the following html code with a multiselect element. On running tests with protractor to select the options, I get the error as 'Element not visible'.
<div id="one" class="class1">
<select id="select1" style="width: 70%;" class="multiselect" multiple="multiple" ng-model="formData.abcqw">
<option value="abc">ABC</option>
<option value="xyz">XYZ</option>
<option value="pqr">PQR</option>
</select>
</div>
protractor code :
browser.actions().
mouseMove(element(by.className("multiselect"))).click().perform();
element(by.model("formData.abcqw")).sendKeys("abc");
Any help is appreciated.
It's pretty much evident from the HTML which you have shared that the <select> tag is an AngularJS element, so we have to induce wait i.e. WebDriverWait as follows for the element to be selectable:
var EC = protractor.ExpectedConditions;
// Waits for the element with id 'select1' to be selected.
browser.wait(EC.elementToBeSelected($('#select1')), 5000);
I also think that it is a wait issue.
Whenever you see this "element not visible error" you can add
browser.sleep(5000);
before the click statement and try again
if that doesn't work try below.
This when we intentionally want to click an hidden element. So this should work
var elm = element(by.className("multiselect "));
browser.executeScript("arguments[0].click();", elm.getWebElement());
browser.sleep(2000);
element(by.model("formData.abcqw")).sendKeys("abc");
Try the following code, I replicated the same in my local and verified the below code it works fine:
var EC = protractor.ExpectedConditions;
var multiSelectElement = element(by.model('formData.abcqw');
browser.wait(EC.visibilityOf(multiSelectElement))).then(function() {
browser.wait(EC.elementToBeClickable(multiSelectElement.element(by.cssContainingText('option', 'ABC'))))).then(function() {
multiSelectElement.element(by.cssContainingText('option', 'ABC')).click();
});
});

Auto-selecting an <option> via JQuery in a dynamically-loaded <select>

Based on cool StackOverflow code, I successfully created a series of dynamically-loaded <SELECT> drop-downs. However, when processing the form (e.g., if there's an error in the submitted information) I need to automatically select the appropriate <OPTION> in the dynamically loaded <SELECT> blocks. I tried a solution that works with static <SELECT> blocks, but it didn't work on my dynamically-loaded block. (I'm hiding/showing <SELECT> blocks as they are needed.) Here's the code:
<?php do things at the beginning of the page ?>
<script>
$(function() {
$('#container_A1').hide();
$"#category_A0").change(function() {
$("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());
$("#container_A1").show();
});
});
</script>
<?php create the HTML page... ?>
<script><?php
if( isset($_POST['category_A0']) && $_POST['category_A0'] != '' &&
isset($_POST['category_A1']) && $_POST['category_A1'] != ''){ ?>
$(function() {
$("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());
$("#container_A1").show();
$("#category_A1").val("<?php echo $_POST['category_A1']; ?>"); // NOT WORKING
});
<?php
}
?>
</script>
Everything works fine except the last JQuery line that tries to set the value of the category_A1 <SELECT> block to the option defined in $_POST['category_A1']. That doesn't work. Is the .load() function not complete when the subsequent .val() function is called?
Thanks!
.load is an asynchronous function. jQuery will continue on to the lines while .load is running, so the second $("#category_A1").val("<?php echo $_POST['category_A1']; ?>"); will always be overriden by the result of $("#category_A1").load("http://domain.com/loader/"+$("#category_A0").val());

HTML Select with disabled Option returns wrong selectedIndex in FireFox

I have a Select with a disabled Option wich is the default selected one:
<select name="select" size="1">
<option>0</option>
<option selected disabled>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
If I get the selected, it returns 1. Everything OK.
But if I open the popup and hover with the cursor over another Option (for Example '4') and Cancel it via ESC or by clicking anywhere else.
The Select input shows the old value 1 but returns on get selected 4.
Example with jsfiddle
It doesn't happen with Chrome only FireFox (4/5)
It appears that the display is not changed when you exit your select this way however firefox is looking for a different selectedValue because it finds the currently selected option as disabled, which in firefox' eyes should be impossible.
The onChange event was not triggered until the onBlur event (which is when the selectedValue would get changed, but this is not what the display is changed to). If we were to reset our value in the onChange event this event might get called again. So by utilising the onBlur event we can provide the following workaround:
onBlur="javascript:document.getElementsByName('select')[0].selectedIndex = document.getElementsByName('select')[0].selectedIndex;"
http://jsfiddle.net/aRMpt/22/
I hope I'm making sense here.
The following code is ugly, but it does exactly what you want (I think). Basically, I am intercepting all onChange events, and only processing them if there is a corresponding onClick event that results in a changed value. ALso note that change events are processed before click events. EDIT: Just relaized this does not work in chrome, so i added some browser detection code so that it only executes in firefox.
NOTE: The current code would not work if the user had tabbed into the select box and made his changes with the error keys, but the method below can be easily adapted to handle that case as well. You'd simply need to process key events like arrow up or arrow down or TAB or ENTER in the same way clicks are processed below, but only when the select box had focus.
NOTE 2: Playing with this more, the behavior is very strange. If you escape out of the select, the onChange event is not triggered, but it is saved up. If at any later time you click anywhere on the screen the onChange event will be triggered for the value you were hovering over when you escaped, even though that value was actually changed as soon as you escaped. So this is getting tricky. I think you may have to handle the 2 cases separately. One case to handle click aways, and one to handle escape outs (which patrick answered).
It's getting hairy and I see no elegant way to code this. How about a note to the user next to the text box saying "Your currently selected option, 1, is no longer available." Then you could have a select box with only the avalable options.
<select name="select" size="1" onChange="handleChange()" onClick="handleClick()" >
<option>0</option>
<option selected disabled>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br />
<script>
var initialValue = document.getElementsByName('select')[0].selectedIndex;
var potentialChange;
var processClick;
function handleClick() {
//ignore this code if not firefox
if (navigator.userAgent.indexOf("Firefox") === -1)
return;
var curVal = document.getElementsByName('select')[0].selectedIndex;
if (!processClick)
return;
// a value change click occured, now we actually process it.
document.getElementsByName('select')[0].value = potentialChange;
}
function handleChange() {
// save the potential change, which will be used if a real click was detected
potentialChange = document.getElementsByName('select')[0].selectedIndex;
processClick = (potentialChange !== initialValue);
// undo the attempted change, in case of an escape or page click
// but only on firefox
if (navigator.userAgent.indexOf("Firefox")!=-1)
document.getElementsByName('select')[0].value = initialValue;
document.getElementsByName('select')[0].value = initialValue;
}
</script>
getSelected
Detect the esc key and reset it, here is an example using jQuery (and a dash of your code)
$('select').keyup(function(e) {
if (e.keyCode == 27) {
document.getElementsByName('select')[0].selectedIndex = 1;
}
});
UPDATE No jQuery Solution
UPDATE 2 Abstracted out finding event and keycode for re-usability.
DEMO: http://wecodesign.com/demos/stackoverflow-6923135.htm
<script type="text/javascript">
function getEvent( event ) {
if ( window.event ) return window.event;
return event;
}
function getKeycode ( event ) {
if ( event.which ) return event.which;
else return event.keyCode;
}
changeToDefaultListener = function( event ) {
theEvent = getEvent( event );
theKeyCode = getKeycode( theEvent );
if( theKeyCode == 27 ) {
document.getElementsByName( 'select' )[0].selectedIndex = 1;
}
};
</script>
<select name="select" size="1">
<option>0</option>
<option selected disabled>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
getSelected
<script type="text/javascript">
document.getElementsByName('select')[0].onkeyup=changeToDefaultListener;
</script>
The work around I had to use for this is was putting an event listener on the click event of the not selected options in drop down. In the event listener's function I set a global boolean.
var selectChanged = false;
$('#select option:not(:selected)').click(function () {
selectChanged = true;
});
Then in the area of the code where I need the selected value of the drop down, I check the boolean:
if the boolean is true I can then use it's new value
if the boolean is false I can get the value from the Html property (which contains the initial value of the dropdown).
var selectValue = selectChanged ? $('#select').val() : $($('#select').outerHtml()).find('option:selected').val()
This is ugly I know, but this is the only work around I could find.