let's suppose the browser rendered following page
<html>
...
<body>
<div id="partialContainer">
<script>
function saveItems(){
/* do somthing*/
}
</script>
<input type="button" id="btnTest" name="btnTest" value="Test" onclick="saveItems()"/>
</div>
</body>
</html>
after an AJAX call and change the "partialContainer" content using
$("#partialContainer").html(returnedMarkup)
saveItems function still remains in page and can get executed
how can remove this function when markup get replaced to avoid name colissioning
var saveItems = function () {}
After your Ajax, assign some other value to it, preferably the one above.
Try setting saveItems to undefined
$("#partialContainer").html(returnedMarkup);
if (!!saveItems && $.isFunction(saveItems)) saveItems = void 0;
You could put your function in an object literal:
var obj = { saveItems: function() { } }
and delete it after the ajax
delete obj.saveItems
On your ajax success callback function, just do:
$("#btnTest").prop( "onclick", null );
Be aware that $.removeAttr('onclick') will fail in ie 6-8, so .prop() is better.
Related
My jquery is not alerting anything when I click the button with the id decrease. This is my code. I am using external js file.
$(document).ready(
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
}))
I tried doing this and it is working fine.
$(document).ready(function(){
alert("Ready");
})
This is the html code:
<div class="row justify-content-center d-flex">
<button id="decrease" class="btn btn-warning">-</button>
<input type="number" id="amt" value="1"/>
<button id="increase" class="btn btn-warning">+</button>
</div>
what's wrong with my first code snippet?
The value you pass to ready() needs to be a function.
In your first example, you are passing the return value of $('#decrease').click(...).
This means that $('#decrease').click(...) has to be evaluated immediately, so it is looking for #decrease before the DOM is ready and the element doesn't exist yet.
ready() then ignores the value you pass to it because it isn't a function.
Wrap the call to $('#decrease').click(...) in a function, just as you did for alert(...) in the second example.
You also have a missing ); at the end but I'm guessing that just got cut off when you transcribed your code to the question.
Try using this:
$('#decrease').on('click', function(){
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
})
if you have the right html syntax, the right syntax for your js script is:
(you have to use a function for document.ready):
$( document ).ready(function() {
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
});
});
you could use the shorthand syntax:
$(function() {
$('#decrease').click(function() {
var beforeIncrement = $('#amt').val();
alert(beforeIncrement);
});
});
I've created the function below to identify an onclick event which is dynamically generated with each page load. I'm able to get the onclick event into a variable (developer console output shown below). I want to execute that onclick event but can't find a good way of doing that. Any assistance is appreciated.
"ƒ onclick(event) {
mstrmojo.dom.captureDomEvent('*lK1129*kWA92AF1C396244F28902B3171F9642E57*x1*t1530820506700','click', self, event)
}"
function applyAll() {
//Get the self Link to click it
var linkBys = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode");
// loop through each result
for(y = 0;y < linkBys.length;y++){
// retrieve the current result from the variable
var linkBy = linkBys[y];
// check the condition that tells me this is the one I'm looking for
if(linkBy.innerText.indexOf("link") !== -1){
// Find the right class
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].onclick;
console.log(idy);
}
}
}
If the property 'onclick' is defined as a function, you can just run it as a function.
var idy = document.getElementsByClassName("")[y].onclick();
You could also handle it another way:
var idy = document.getElementsByClassName("")[y].onclick;
idy();
onclick is not an event, it's a function which gets executed when element is clicked. If you want to simulate click you can do element.click()
If you used:
element.addEventListener('click',()=>...);
instead of:
element.onclick=()=>...
then all you have to do is:
document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].dispatchEvent(new Event('click'));
You can call the function returned , adding parens:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function foo() {
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[0].onclick;
console.log(idy);
idy();//like so
}
function alertMe() {
alert('Hello');
}
</script>
</head>
<body>
<button id="btn" class="mstrmojo-DocTextfield-valueNode" onclick="alertMe();">No click</button>
<button id="btn2" onclick="foo()">Click me</button>
</body>
</html>
I need to be able to change the onclick event of an id so that once it has been clicked once it executes a function which changes the onclick event
Here is my code:
Javascript:
function showSearchBar()
{
document.getElementById('search_form').style.display="inline";
document.getElementById('searchForm_arrow').onclick='hideSearchBar()';
}
function hideSearchBar()
{
document.getElementById('search_form').style.display="none";
document.getElementById('searchForm_arrow').onclick='showSearchBar()';
}
and here is the HTML:
<!-- Search bar -->
<div class='search_bar'>
<img id='searchForm_arrow' src="images/icon_arrow_right.png" alt=">" title="Expand" width="10px" height="10px" onclick='showSearchBar()' />
<form id='search_form' method='POST' action='search.php'>
<input type="text" name='search_query' placeholder="Search" required>
<input type='image' src='images/icon_search.png' style='width:20px; height:20px;' alt='S' >
</form>
</div>
Thanks
Change your code in two places to reference the new functions directly, like:
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
Can you try this,
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
You were nearly right. You are settingthe onclick to a string rather than a function. Try:
in showSearchBar()
document.getElementById('searchForm_arrow').onclick=hideSearchBar;
in hideSearchBar()
document.getElementById('searchForm_arrow').onclick=showSearchBar;
You do not need to create two function.
Just create one function and using if condition you can show and hide the form tag..
function showSearchBar()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display=''; // no need to set inline
}else{
document.getElementById('search_form').style.display='none';
}
}
function searchBar(){
var x = document.getElementById('search_form').style.display;
x = (x == 'inline') ? 'none' : 'inline';
}
You can wrap up both functions into one by adding a check to the current condition of the element and applying your style based on that condition. Doesn't actually change the function but doesn't need to as there is now only one functon performing both actions.
With javascript you can check and perform opration
function SearchBarevent()
{
if(document.getElementById('search_form').style.display=='none'){
document.getElementById('search_form').style.display="inline";
}else{
document.getElementById('search_form').style.display="none";
}
}
or if you may go for jquery there is better solution toogle
Like:
$("#button_id").click(function(){
$( "#search_form" ).toggle( showOrHide );
});
Fiddle is example
Here is an option that uses jQuery:
$('#searchForm_arrow').click(function() {
$('#search_form').slideToggle();
});
http://jsfiddle.net/PuTq9/
Here is my issue:
I am creating dynamically a button with an onclick function like this:
$("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');
The parameters are well read but the function is not trigger, and I've got this error message:
"bob is not defined" when bob is the string value of the param1.
Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.
Thanks much for your help!
That's because this string right here:
'onclick="remove('+param1+','+param2+');"'
Will look like this in the end:
'onclick="remove(foo, bar);"'
You probably want it to look like this:
'onclick="remove(\'foo\', \'bar\');"'
So change it to this:
'onclick="remove(\''+param1+'\', \''+param2+'\');"'
You could also do this:
$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
remove(param1, param2);
});
Edit: I also noticed that you were missing one " from your $()-call: $("#test) should be $("#test").
I can suggest you this
<script type="text/javascript">
//<![CDATA[
var i = 0;
$(function () {
$("#lnkAdder").click(function () {
// appending new item
$("#Container").append(
$("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
var data = ++i;
alert("I'm clicked, I'm number " + data);
})
);
});
});
//]]>
</script>
Add item
<div id="Container"></div>
The key here is the javascript closure.
As you can see there a link called lnkAdder. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.
I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.