javascript function gets called twice - javascript

I am trying to call a javascript function on clicking a link. Actually i want to submit a form on clicking a link using post method so i am trying to do the below-
<a href="javascript:submitCategory(this)" >Handicrafts</a>
and in javascript
function submitCategory(varthis)
{
alert(varthis.value);
}
I have few important questions:
1>When i click on the link the function submitCategory gets called twice. After much analysis found that i had two js files included and removing one of them made the function getting called only once.
meaning
when i have included
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="cWed.js"></script>
submitCategory function gets called twice
and when i remove one of them and include
<script type ="text/javascript" src="jquery.js"></script>
submitCategory function gets called only once.
Why is it like this?
2> alert(thisvar.value) should return Handicrafts but it returns undefined. why could this be?
3>what exactly is the meaning of href="javascript:submitCategory(this)"? i have not come across this in any tutorial. and including this here should refer to the element "a" right?

1. You do not need to use the qualifier 'javascript:'
2. when you hook the event in html, always try to do it like event_handler(event). Note : event is the event object. and not some random variable here. You can read more about it in numerous places on the web. In your case varthis is the event object. to access this element use varthis.target and then to get its inner html you can use varthis.target.innerHTML
3. when the function is called you have to either explicitly get the html content of the calling element via the event tag, or just use jquery. You cannot pass variables in the way you think you are passing right now.
4. if you are actually trying to submit a form, I would recommend hooking the onSubmit event in script rather than HTML and put your custom form submit code there. If you do not need to do anything custom in form submission, you can just put the url of the target server function in the action attribute of the form.
Sample code :
<form>
Submit Category
</form>
<script type="text/javascript">
$('#submitCategoryLink').on('click', function (e) {
alert(e.target.innerHTML)
});
</script>

Since you haven't posted the contents of cWed.js it's difficult to know why you're getting a double submission, but my guess is that it contains a click handler of its own, which is duplicating the default handler.
The reason varthis.value doesn't work is because .value is only used for <input> and <select> elements, it contains the value that the user entered or selected from the menu. To get the text content of an element you should use .innerHTML.
A URI that begins with javascript: means that instead of fetching a page from a network location, the browser should execute the Javascript code after that prefix. It's not an officially recognized URI scheme (there was an Internet-Draft RFC, but it expired 2 years ago) , but all browsers support it.
When code is executing from a javascript: URI, this is the window, not the element that was clicked on. You need to use an onclick handler to get this set to the element.
The following works:
<a href="javascript:void(0)" onclick="submitCategory(this); return false;" >Handicrafts</a>
function submitCategory(varthis)
{
alert(varthis.innerHTML);
}
FIDDLE

Related

How can I grab osclass theme HTML from plugin using JavaScript?

I have a variable called btn that I assign to a document.querySelector() function. I know the query selection is right because it grabs the element I want when I run it through the browser console. Nonetheless, the assignment produces a null result. Is this because I cannot grab HTML in this way with osclass framework?
I'm developing a plugin. This plugin alters the registration form. I'm adding a text field wherein I've used an event listener to detect input. If there's input, I want the form to do something when the submit button is clicked. There's no problem detecting this form field, I suspect because I've just added it in the plugin folder. I cannot, however, grab HTML from the theme. I think part of this is because I'm trying to grab it before the HTML loads. Even so, I've tried deferring the script and using an inline script to run the code after the DOM content loads. No success.
Here's the bit of HTML I want to grab.
<div class="controls">
<button type="submit" class="ui-button ui-button-middle ui-button-main"><?php _e("Create", 'bender'); ?></button>
</div>
Here's the code I'm using to do that, and the code I want to execute:
var btn = document.querySelector("div.controls button");
btn.addEventListener("submit", function() {
console.log("Honey is sweet!");
});
Finally here's how I'm running the script:
<script type="text/javascript" async="" defer="" src="<?php echo osc_base_url().'oc-content/plugins/honeypot/fieldcheck.js';?>"></script>
I should mention I'm running this as a function with the osclass hook: osc_add_hook('user_register_form', 'twf_honeypot_form_field');
I expect the variable to grab the button, and the event listener to be added to to the button. Once the form is submitted, it should log the message in the console. What's happening instead is this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.
If you've used osclass, is this because the HTML lives elsewhere? I thought that, if I deferred the script, this code wouldn't execute until the page loaded, and I'd still be able to grab the HTML. If not, how can I grab this bit of HTML from a theme file?
Turns out this line was the problem: osc_add_hook('user_register_form', 'twf_honeypot_form_field'). The code wouldn't execute before the dom loaded, even if I specified for it to do so in the script itself because the script still executed only here. I put the script call in a function and added a new hook: osc_add_hook('after_html', 'twf_deny'); Should have guessed there was a hook for that use case.

Why do I need 'javascript:' in the call to my javascript function?

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).
I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.
It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.
Here is a simplified version of the code used:
#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
cmCreateElementTag(1 + ", " + 2,"TagName");
}
HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
onclick="javascript: createTagging('parameter1', 'parameter2');"
title="atitle" aria-label="alabel">
<img id="ThumbNailImage_59244" src="https://image.jpg"
alt="" border="0"/>
</a>
-Troy
Why do I need 'javascript:' in the call to my javascript function?
You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.
In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.
Without the javascript: portion in the onclick, my function was not being called upon.
With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.
onclick attribute is always calling javascript in HTML.
onclick="createTagging('parameter1', 'parameter2');"
It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

Execute a second function when a first function completes W/O a callback parameter

Background: I'm running A/B tests for a website via VWO. I can write a script that is run when the page loads, but I cannot access any of the website's preexisting scripts or alter their code in any way besides "overwriting" in JS (e.g. remove divs, change CSS properties, append divs) after their page loads.
Problem: When the page loads, there is an empty <div id="priceinfo"></div>. Elsewhere on the page, there is an <img ...>. Inside RequestPriceInfo(), the function outputs HTML to div#priceinfo based on certain form field values on the page. It also appends an "order" button (which is actually not a button at all, but an image nested in anchor tags). I'm trying to change the source for the "button" image using JQuery's attr() function.
Progress: None. I have tried using $('a#requestPrice').click(function() {...} ); but it is not working to change the source of the image, I presume because the content has not yet loaded onto the page immediately when a#requestPrice is clicked and my function runs. I need a way to tell when RequestPriceInfo() has been fired and completed, but there is no callback parameter on RequestPriceInfo() and I don't have access to the script to alter it and add one.
Potentially Useful Info: There is a variable, priceRequested, which is changed from false to true when RequestPriceInfo() runs. Though I realize nothing about this solution is going to be elegant, it seems unreasonable to use Object.prototype.watch() to monitor the variable, but I'm running out of ideas.
How can I detect when RequestPriceInfo() has completed to execute my function without editing the function to add a callback parameter?
What about using CSS... your script could add a class to <div id="priceinfo"></div>, like maybe <div id="priceinfo" class="newButton"></div>. Then, in the CSS, you'd hide the img for #priceInfo.newButton and insert your new image as a background image for the anchor.
Here's one way
var oldRequestPrice = RequestPriceInfo;
RequestPriceInfo = function(){
oldRequestPrice();
// Function completed, handle here
}
EDIT
As the question seems to imply that RequestPriceInfo is an asynchronous API call, have a look at this question: Add a "hook" to all AJAX requests on a page
This will keep track of all Ajax requests happening on the page. You can pick out the one you need and fire your function/code on its success.

Jsp with javascript parameter inside javascript onclick

I would like to insert a call to a function to get a parameter for my JavaScript onclick function. What I would like to do is something like:
<input class="refreshbutton"
type="button"
id="searchUfficiPopup"
onClick="javascript:postColorbox('/DeliDete/searchUfficiPopupBySettoreId', **'&settoreIdKey=${javascript:getSettoriId()}'**, 'tabUfficiForm', 'initScriptUffici')"
value="<fmt:message key="navigation.searchUffici"/>" />
This way Eclipse tells me the function javascript:getSettoriId() is undefined. I defined this function in an external .js file, loaded at runtime with jQuery's .getScript, so I would not like to insert it into the jsp (anyway I tried to insert it into the jsp but the IDE still says that the function is not defined).
The function postColorbox is defined as:
function postColorbox(url, parameters, formName, initScript)
The function getSettoriId() returns the value of a previously entered form element, Settori, which I need to perform a restricted query (I need to obtain all Uffici entities related to the selected Settori entity)
Told this, I would like to ask you experts:
Is it even possible to use a JavaScript function as a parameter of an onclick JavaScript function?
If I put this function to be called in an external .js file will the jsp be able to see it and call it?
Thank you all for your help!
Andrea
Remove the onClick on your <input> and do it with a jQuery event handler instead:
$('#searchUfficiPopup').click(function() {
var settoriId = getSettoriId();
postColorbox('/DeliDete/searchUfficiPopupBySettoreId',
'&settoreIdKey=' + settoriId,
'tabUfficiForm',
'initScriptUffici');
return false;
});
Calling functions from inside the HTML element is not a preferred way. If you can - just assign the element an id or class, and then add a listener to it using javascript on page load.
This way you don't have your data and operations mixed. It will be also easier to modify the code, as your code will be located in js files.

what are the "for" and "event" attributes of the script tag (Javascript,HTML)

In a web application I've inherited at work which was written about 10 years ago I've noticed the following code snippets repeatedly used:
<script language="JavaScript" for="FG1" event="Mousedown(Button, Shift, x, y)">
{
// some code here that uses the variables Button, Shift, x and y
}
</script>
I've never really seen anything like this before. FG1 is an active x object so are these some special things for it specifically or are they just another way of handling any regular javascript event...could the ID reference an input (e.g. a button) and the event be onclick?
ideally, i'd re write it as (if my thinking is correct...I'm not actually going to change the code in the web app as it works, i just want to understand what it means!)
<script type="text/javascript">
var fg1 = document.getElementById("FG1");
fg1.onMouseDown = function(Button, Shift, x, y) {
// do stuff here...
}
</script>
Those are Microsoft-specific (Internet Explorer-only) extensions to the script tag, and your impulse to rewrite the example without them is a good one.
According to MSDN, the:
for attribute:
Sets or retrieves the object that is bound to the event script.
event attribute:
Sets or retrieves the event for which the script is written.
Therefore, I presume as you have that you can drop the non-standard attributes and use the lines you added to get the element, and handle the mousedown event.
for attribute is for the element name in for attribute like for="element1" and event attribute is for event handling like even onclick, onmouseover etc for that elements.
For example if you add Onclick event then onclick event works on element which name you entered in for attribute.
I have seen this kind of code snippet in a classic ASP project, where it uses a simple vbscript form validation method. `
<input name="button1" type="button" id="button1" value="Submit">
<script language="VBScript" for="button1" event="onClick">
Menu_Validate()
</script>
This onclick event will call the Menu_Validate() method and do form validation.

Categories

Resources