Automatically fill function arguments - javascript

in java and in android studio when we write a function like this:
function test (View v) { ... }
and put it in xml layout
<TextView
android:onclick="test" />
v as an argument filled automatically by java and when we click at that TextView v filled with property of that TextView clicked on
how can I define this in javascript and html tags ?
Thanks.

You can do something like this
function myFunction(element) {
element.innerHTML = "hello";
}
<button onclick="myFunction(this)">Click me</button>
Pass the clicked element that is stored in this as a parameter to the click function.

All you need to do is to add the "this" keyword, "this" keyword automatically gets the action of the current element if it clicked, checked, etc in cases of buttons, check-boxes, respectively...
I totally agree with Costin here.
HTML :
<button id="btn" onclick="someFunction(this)">Tap It</button>
JS:
function someFunction(element) {
element.innerHTML = "hello";
}
which means the someFunction will automatically get that the element is "button" here and on its click, the action needs to be performed is to change its HTML and display "hello".

Related

Button event is only selecting the first class. (Jquery)

I am trying to select the saveBtn class on each button so that when I click it it saves it into local storage. However it is only saving the first instance of the selected class. Can anyone help?
html:
<div class="hour-container" id="8am">
<div class="hour"> 8 AM </div>
<textarea class="text-content"></textarea>
<button class="btn saveBtn"><i class="fas fa-save"></i></button>
</div>
js:
// Function to save the users input to the text area
function saveText() {
var textContent = $(".saveBtn").siblings(".text-content").val();
var hour = $(".saveBtn").parent().attr("id");
localStorage.setItem(hour, textContent);
console.log(textContent);
}
// Call saveText on save button click
$(".saveBtn").on("click", saveText);
In the event handler, the searching scope of $(".saveBtn") is the whole web page.
That means the reference point of all actions is referred to the beginning of the web page.
So, the function $(".saveBtn") always refer to the first element which has the saveBtn CSS class.
You may modify the saveText function as the following:
function saveText() {
var textContent = $(this).siblings(".text-content").val();
var hour = $(this).parent().attr("id");
localStorage.setItem(hour, textContent);
console.log(hour,textContent);
}
For my solution, the this refers to the element which has been clicked by a user, so the reference point of all actions is referred to the element which has been clicked, therefore it should be work fine.

Parameter passing in JavaScript onclick: this.id versus other attributes

I suspect there is something basic about JavaScript parameter passing that I do not understand.
If I click on this button, I get an 'undefined' message in the alert box.
<button onclick="play_audio(this.src)" src="foo.m4a">▶</button>
If I click on this button, the string value is passed properly:
<button id="foo.m4a" onclick="play_audio(this.id)">▶</button>
Codepen here:
https://codepen.io/anon/pen/JBpMYo
A button does not have a src attribute. However, you can use this.getAttribute('src').
<button src="foo.m4a" onclick="play_audio(this.getAttribute('src'))" >▶</button>
<script>
function play_audio(src){
console.log("Playing "+src);
}
</script>
It is recommended that you usedata-src (you can use any prefix after data-, not necessarily src) and this.dataset.src instead (you can use the data-* attribute to embed custom data) because it will ensure that your code will not clash with HTML Element attributes for future editions of HTML. See the documentation.
<button data-src="foo.m4a" onclick="play_audio(this.dataset.src)" >▶</button>
<script>
function play_audio(src){
console.log("Playing "+src);
}
</script>

Send onclick event of element without id

I'm trying to automate through my Swift3 app the click of an HTML element in line2 which lacks an 'id'.
HTML portion from website containing desired element(line2)
<div id="actionButtons" style>
<input class="pptbutton" onclick="return addSimResults();" title="SimulateRace" type="submit" value="Simulate">
Clear All = $0
<div class="holder" style="font-size:0.8em;">
<input class="pttbutton" id="graphButton" onclick="return addGraphResults();" style title="Graph your simulation" type="submit" value="Graph HvH">
...etc
I've successful automated line5's element.onclick event with the Swift code
webView.evaluateJavaScript("document.getElementById('graphButton').click();")
I've attempted to grab the element by Class name with Swift code
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0];") {
(result, error) -> Void in
print(result)
}
which returns nil. I've also tried without the "[0]".
Any suggestions how I can cause line2's Element onclick Event?
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0];")
this line of code evaluates the javascript, defined as the given string. The String is pure Javascript which selects the first element within the dom with the css class pptbutton.
You forgot to call the click method on this element, so no click is triggered by your code.
It should be:
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0].click();")
In this way the click event is triggered on the selected element.

If I hide a text input element with javascript can other javascript functions still access a value entered into it?

I am trying to use this function:
function storagecalc(){
var thediv=document.forms["boxes"];
var boxno=thediv.elements["numbofboxes"];
var howmany =0; //If the textbox is not blank */
if(boxno.value!="")
{
howmany=parseInt(quantity.value);
}
return howmany;
document.getElementById('numberprice').innerHTML = "£"+howmany;
}
To grab a value entered here:
<form action="" id="boxes">
<input type="text" id="numbofboxes" value="" name="boxnumber"/>
<button id="smtbxno" onclick="storagecalc">
<img src="images/tick.gif" alt="proceed"/>
</button>
</form>
and display it here:
<div id="grandtotal">
<p class="calctitles">
Grand Total
</p>
<p id="numberprice">
</p>
</div>
Nothing is happening when I enter a value into the textbox and click the button, is this because the button also has jQuery that hides itself and the text box upon clicking?
If not any suggestions for why it won't work?
If I hide a text input element with javascript, can other javascript functions still access a value entered into it?
Every piece of javascript that can obtain a reference to the input element (via a variable, with a DOM selector) can access its value. The visibility of that element has no effect on any of those actions. Only if you would detach it from the DOM, other functions could not select it with DOM methods.
OK, there are some errors in the document you gave us:
<button onclick="storagecalc"> does not execute anything, you will need to call the function: <button onclick="storagecalc();">. Only when assigning a listener to the onclick property with js, the function object needs to be used (document.getElementById("smtbxno").onclick = storagecalc;).
In the function itself, you use a variable quantity which is undefined (and throws an exception). I'm not sure how to fix that.
You are assigning the function but not calling it:
<button id="smtbxno" onclick="storagecalc()" ... >...</button>
------------------------------------------^
Also, members of the form's elements collection should be referenced by name, not by id.
var boxno=thediv.elements["boxnumber"];
I don't understand why you have a different name and ID, that will confuse IE which, in older versions at least, doesn't know the difference.

Why are only some attributes updated from my javascript function?

I have a button script to change the buttons in a frame based on the page loaded in the main frame. The problem I'm experiencing is that while the background images, tabindex and text on the button (innerHTML) all change as expected, the onclick doesn't. It appears to completely ignore it. Here's the script I'm using:
function createbutton(btn_N, btn_I, btn_L, btn_D) // (Div Name, Tab Index, Button Text, Page To Load){
var btnN = top.frames['buttonbar'].document.getElementById(btn_N);
btnN.style.cssText = "display:block; cursor:pointer; padding-left:16px; padding-top:5px;";
btnN.onmouseover = function() {this.style.backgroundImage = "url('./osdimages/navBG_roll.png')";};
btnN.onmouseout = function() {this.style.backgroundImage = '';};
btnN.tabindex = btn_I;
btnN.innerHTML = btn_L;
btnN.onclick = btn_D;
}
The button call looks like this:
createbutton("button01", 1, "New Order/Browse", "parent.frames['content'].location.href='createorder/createorder.asp';");
There is a difference between attributes and properties.
The best example of this is as follows:
HTML: <input type="text" value="hello" id="test" />
Type something in the text box
document.getElementById('test').value is whatever you typed
document.getElementById('test').getAttribute("value") is whatever was in the HTML
Some attributes are directly mapped to properties and vice versa, but this is not always the case.
For instance, the onClick attribute takes a string that is then eval'd, but the onclick property takes a function. This is why your code isn't working.
Either pass a valid function, or use setAttribute.
You are setting onclick with a string, it needs a function to execute.
createbutton("button01", 1, "New Order/Browse", function(){ parent.frames['content'].location.href='createorder/createorder.asp'; });

Categories