I am working on automating a site and in console. When I am using
jQuery methods to change value of dropdown (hidden/generated values) it works perfectly fine, correctly mimics human behavior.
But when I am using JavaScript it's changing the value, but the next dropdown doesn't get activated.
The code I am using:
jQuery
$("#carMakeInput").val("BMW").change()
JavaScript
document.getElementById("carMakeInput").value = "BMW";
document.getElementById("carMakeInput").dispatchEvent(new Event("change"));
Does jQuery do something extra?
I made a little snippet to test what you were saying. In my snippet, JS is activating and jquery not (I confirmed by commenting out the lines that fire the change event). So I think it's a question of how you add the listener
document.getElementById("carMakeInput").addEventListener("change", function() {console.log("changed");});
$("#carMakeInput").val("BMW").change()
document.getElementById("carMakeInput").value = "BMW";
document.getElementById("carMakeInput").dispatchEvent(new Event("change"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="carMakeInput" />
Related
So I have a very simple JS function written that works like the following.
There is a button that has the following code:
<button type="submit" class="large button" onclick="addCart(76,95,73,96);">
<i class="icon-shopping-cart"></i> Add to Cart
</button>
Now when that is clicked there is a very simple function added to the page below that looks like the following:
<script type="text/javascript">
function addCart(pid, pattr, pval, pscent = 0) {
...
}
</script>
This works perfectly in Chrome, Firefox, Chrome for Mobile, Safari for Mobile.
But this does not seem to work on Safari on Mac. Instead I get the following error:
ReferenceError: Can't find variable: addCart
I cannot figure out why. It's hard for me to add a listener because there are 7 buttons and a wide arrange of variables that are being sent, and I'd rather send that like I'm currently doing.
I finally found the issue.
The function was creating an error in Safari so it was never being defined. I changed the function to the following:
function addCart(pid, pattr, pval, pscent) {
pscent = (typeof pscent !== 'undefined') ? pscent : 0;
...
}
Notice the big difference is that I was no longer using the Function to declare a default value for 'pscent' and instead I do it the old school method. Not sure if this is being caused by an older version of Safari or what.
If you are here because of a similar error, look for some potential JS error in the function which will prevent the function from being declared.
Looks like you are submitting a form since the input type is "submit". Have you tried testing it with the input type set to "button"?
if you are using jquery try to use document ready function
$(document).ready(function() {
// code here
});
or use plain javascript self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
})();
the possible reason is your function is not available at the time of click
Here is a sample (using jquery) https://jsfiddle.net/baphmoLt/
I'm trying to do some simple jQuery stuff 'dynamically' from within a MediaWiki content page. Its really just to 'beauty up' some different features.
I've done the following:
http://www.mediawiki.org/wiki/JQuery
http://www.mediawiki.org/wiki/Manual:$wgRawHtml (mainly for Paypal buttons initially)
The below code does not work. This is put in a blank content page.
<html>
<script>
$j(document).ready(function(){
$j('#test').hover(
function(){
$j('#test').attr('background-color','red');
},
function(){
$j('#test').removeAttr('background-color');
}
);
});
</script>
<div id="test">Howdy</div>
</html>
Nothing happens...
Any ideas?
Update:
I have attempted this simple solution with no result.
example.com/wiki/index.php?title=MediaWiki:Common.js
$j('#jTest-Howdy').hover(
function(){
$j('#jTest-Howdy').addClass('jTest-red');
},
function(){
$j('#jTest-Howdy').removeClass('jTest-red');
}
);
example.com/wiki/index.php?title=MediaWiki:Common.css
.jTest-red { background-color: red; }
example.com/wiki/index.php?title=jQueryTest
<html>
<div id="jTest-Howdy">Howdy</div>
</html>
as you can see here, this code should work IF jQuery was being loaded properly...
http://jsfiddle.net/5qFhv/
but it is not working for me... any help?
If you're using the jQuery that's loaded by MediaWiki 1.17, be aware that most JavaScript is loaded after page content. An inline <script> element is executed immediately when it's reached, so $j would not be defined at this time -- you'll probably see some errors in your JavaScript error console to this effect.
(Offhand I'm not sure about the jQuery that's included with 1.16; versions of MediaWiki prior to that as far as I know did not include jQuery.)
Generally what you want to do here is to either put JavaScript code modules into the 'MediaWiki:Common.js' page and let that hook up to your HTML markup, or create a MediaWiki extension -- which you can then invoke from your pages, and which will let you create any fun HTML and JavaScript output you like.
http://www.mediawiki.org/wiki/Manual:Interface/JavaScript
http://www.mediawiki.org/wiki/Manual:Developing_extensions
Code you put in your 'MediaWiki:Common.js' page will be loaded after other UI initialization, ensuring that code and variables are present so you can call into jQuery etc.
I don't know much about MediaWiki, but to me it looks like some simple javascript mistakes.
In the first sample you are trying to set an attribute on the element,
when you need to set the css or style attribute.
$j('#test').css('background-color', 'red');
In both samples you are binding an event to an element that doesn't exist yet in the DOM, so it will fail. You could use the live method, which will work for existing and future elements introduced in the DOM.
$j.('#test').live('mouseover', function(){
$j(this).addClass('hover-class');
}).live('mouseout', function(){
$j(this).removeClass('hover-class');
});
Hope that helps.
Try putting all your custom jQuery code in its own file, then load it as a module with ResourceLoader, after jQuery.
http://www.mediawiki.org/wiki/ResourceLoader/Migration_guide_for_extension_developers
Also, as a debugging method: completely load your site in Firefox, then enter your custom jQuery code in the console. If it works, your problem is a race condition. If it doesn't, jQuery isn't loading for some reason.
I'm using the cluetip jQuery plugin.
I'm trying to add my own close button. The the jquery I'm trying to call is:
$(document).bind('hideCluetip', function(e) {
cluetipClose();
});
There are many references to cluetipClose() through the code and the button that the jquery inserts uses it and works so that function as far as I'm aware works fine.
I'm trying to trigger that using
$('a.close-cluetip').trigger('hideCluetip');
I've created my link:
Close
But it isn't doing anything.
Am I calling it incorrectly?
The problem here is that in the cluetip plugin, the function clueTipClose() is inside a closure, so you have no access to it unless you're inside the closure (i.e. inside the plugin's code). Now I've gotta admit, this plugin doesn't seem to be set up to be all that extensible. If they made this function accessible via a "clueTip" object that was set up for each element that uses it, you'd be able to add another jQuery method to the end of the closure like this:
$.fn.cluetipClose = function() {
return this.each(function() {
var thisCluetip = findCluetipObj(this);
if (thisCluetip)
thisCluetip.cluetipClose();
});
};
But you have the unfortunate luck of not being able to do this easily. It looks like this guy wrote his jQuery plugin with non-OO code inside of a closure. Poor you.
Now on the plus side, it seems this plugin is already running this code directly after it instantiates the cluetipClose() function. Have you tried just doing this from your code:
$('a.close-cluetip').trigger('hideCluetip');
Without redeclaring the document hideCluetip bind? I think that should probably work.
I am developing webapp using jQuery.
I have functionality that adds new row of 3 input fields. After creating these DOM elements I want to focus one of input fields. I am doing it with calling jQuery focus() function on necessary input field.
Problem is that calling focus() works fine in IE6 and FF3.5, but not working in IE8.
I was trying to make simple working example of this problem for showing it here, but with stripped version of code focus() is working fine. So my guess was that DOM is not ready yet when I call focus() in IE8. For this I tried calling setTimeout('myFocus()',400). I had success and in some of cases focus was really working but still not always. Randomly it does not focus my input field.
Question is: Has anybody faced similar problems and does anybody have any idea how to workaround it? Using setTimeout feels like very ugly workaround.
Tnx in advance
Edited : 26.08.2009
Succeeded to reproduce on simple example. Here is HTML+JS code that reproduces this bug on IE8.
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function performChanged() {
formChanged = true;
}
function handleChange() {
var parentDiv = $('#container');
newValue = $(html).html();
parentDiv.html(newValue);
$(".sel1",parentDiv).bind('change',handleChange);
//alert('Uncomment this and after alert focus will be on input');
$("input.cv_values",parentDiv).focus();
}
$(document).ready(function() {
$('.trackChange').bind('change', handleChange);
});
var html = '<div class=\"div1\">\n<select class=\"sel1\" id=\"sel1\" name=\"sel1\"><option value=\"\"><\/option>\n<option value=\"11\">Select me to see problem<\/option>\n<\/select>\n\n\n<input class=\"cv_values\" id=\"sel3\" name=\"sel3\" size=\"30\" type=\"text\" value=\"\" /><br/>Focus should in input field. With alert it is but without alert focus is not there</div>';
</script>
</head>
<body>
<select class="trackChange" onchange='performChanged();'>
<option value=""></option>
<option value="1" >Select me to generate new inputs</option>
</select>
<div id="container"></div>
</body>
To reproduce:
1) select value from first dropdown. You will see that first time input is working
2) select value from second dropdown. You will see that bug is reproduced.
Then in code you can comment out line where it shows JS alert(). Strange thing is that if there is this alert() then after it focus is working fine.
Hope this helps to understand where my problem is.
P.S. I need my app to work this way - it is regenerating those inputs after selecting value from dropdown. This is simplified example of my app ;).
I had a similar problem with my app, but I can't reproduce the focus problem with your code. My problem was slightly different in that my page had a link hash that made IE not give my element focus.
Anyway, to get around the problem I added a timeout:
setTimeout(function () {
$('.my-thing').focus();
}, 100);
Not noticeable by a user but it gives IE a moment to breathe.
In conjunction with Kazys's solution, I found this to fix all my problems (using IE8 & .HTA files):
$("elem").blur();
$("elem").focus().focus();
I have no idea why, but somehow calling focus twice helps IE along.
EDIT:
I have found that calling .show() and .select() can also help.
Strangely i had the same problem and resolved it using plain old javascript like so:
document.getElementById('friend_name').focus();
Using jQuery equivalent $('#friend_name').focus(); didn't work in IE8 :-/
Had similar problem with IE8. I wanted to focus input in dialog when it is opened. Used autoOpen = false. Noticed that focus doesn't work only for first focusable element in dialog. Tried setTimeout but it worked only sometimes. Blurring element before focusing helped me.
$('#dialog').find('#name').blur();
$('#dialog').find('#name').focus();
Since you have not posted any code are you using:
$(document).ready(function(){
//code here
});
This will make javascript run after the html is loaded.
And you should use live events also. When your adding inputs to the dom the will automatically have focus binded to them.
$("p").live("focus", function(){
alert( $(this).text() );
});
This means that every p that is created will have a focus binded to it.
This is the best solution for the moment to set focus:
$('.elt').fadeIn(200, function() {$('.elt').focus();});
This is an old question, but it is top in search, so wanted to update.
I don't know if there was ever a time that it was fixed, but I ran into this issue again today in IE11, using jquery-2.1.3. I found that wrapping the focus call in a setTimeout, as set out by Ponny above, worked best for me.
I did need to increase the timeout in some cases, to get it to work.
I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps