This question already has answers here:
onClick to get the ID of the clicked button
(18 answers)
Closed 6 years ago.
I have a chunk of HTML code generated with PHP.
HTML looks like this:
<input type="text" id="10"><button onclick="process()">send</button>
<input type="text" id="11"><button onclick="process()">send</button> <!-- and so on until id=N -->
PHP code is like:
<?php while ($row = $result->fetch_assoc()) { ?>
<input type="text" id="<?=$row['id']?>">
<button onclick="process()">send</button>
<br>
<?php } ?>
It is supposed that if a user clicks the SEND button, the value of input tag is passed to process() function.
And here is where I'm getting stuck: I don't know which exactly ID of input should I specify in getElementById within process() fucntion - because I don't know which button is pressed.
Would be greateful for any help.
Although it is not prefered way, if you want to stick with inline event handlers, you can do something like this:
function process(elem){
alert(elem.previousSibling.value);
}
<input type="text" id="10"><button onclick="process(this)">send</button>
<input type="text" id="11"><button onclick="process(this)">send</button>
Note this
Gecko-based browsers insert text nodes into a document to represent
whitespace in the source markup. Therefore a node obtained, for
example, using Node.firstChild or Node.previousSibling may refer to a
whitespace text node rather than the actual element the author
intended to get.
previousSibling
Like previous answers, you should ideally stay away from binding the events inline. But the solution if you have to do is two, By default an event object is passed to the event handler method if it is not overridden by any one.
such a method will give you enough information about the target element of the event. (The behaviour may vary depending on the browsers so may need to test it thoroughly..)
function EventHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
now you can call the get the id by just doing target.id or you can basically get any attribute value.
Related
I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = "<a href="+intoLink+"</a>;
intoLink.value = hLink;
}
window.onload = linkIt();
<td><div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/></td></tr>
In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link
function linkIt() {
let intoLink = __C_cb_file_link.value;
let parent = __C_cb_file_link.parentNode;
__C_cb_file_link.remove();
btn.remove();
parent.innerHTML += `${intoLink}`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>
There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"</a>" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.
A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = document.createElement("a");
hLink.setAttribute("href", intoLink.value);
hLink.innerHTML = "Click here";
intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);
<td>
<div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" /></td>
</tr>
P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.
[UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with, is it what you want, right?
function linkIt() {
let fileLink = document.getElementById("__C_cb_file_link");
let hLink = fileLink.textContent;
fileLink.innerHTML = ""+hLink+"";
}
linkIt();
<div>
<p id="__C_cb_file_link">http://myLink.com</p>
</div>
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.
Its probably something basic but wanted explanation of the use cases. Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work. I'm concerned about "Gotchas" that I would have overlooked. Like maybe it works in Firefox but not in Chrome for example.
I saw the following 2 ways, both are ways to input data into a form element.
First way
JavaScript
var $body = $(e.target).find('[name=body]'); //defines the content
var comment = { body: $body.val() };
HTML
<form class="form-send-message" id="addcomment" data-keyboard-attach>
<textarea id="body" name="body"></textarea>
</form>
Second way
JavaScript
var message = template.find('input').value;
HTML
<form class="message" data-keyboard-attach>
<input type="text" name="body" id="body">
<button class="icon" type="submit"></button>
</form>
Here you can see two ways to find the value of an input/textarea with an explanation:
'submit .new-post': function(event){
//returns name="postBody" content from the form you're submitting
var postBody = event.target.postBody.value;
//returns the value of an html element that exists in DOM, even if its inside a different template or form.
var postBody = $('.someClass').val()
}
Your first code Is jQuery, while your second code is Meteor. They both can accomplish the same thing under the right circumstances. Also, according to this answer, meteor's template.find is an alias for jQuery's $, meaning they are the exact same.
But, the codes don't do the same thing in this case.
Your first code finds the value an element with a name of "body" inside e.target. I am assuming e is an Event, but there is no way to tell with the current amount of code you gave.
The second code just gets the value of the first INPUT element it finds.
Okay so, I want to make an OnClick function in JavaScript that makes it so when a user clicks on it, it will change the word. Is there a replaceword() function or something that which will let me do so? I know this is not real code, but for example:
<p>Quickly <span onclick="replaceword('Surf');">Search</span> The Web!</p>
If there is, then can someone tell me also how to reverse the code maybe? So when they click on it the second time, it will change back to "Search"?
If you want to jump between multiple words, you'll need to store them someplace. You could have two words in the sentence, and toggle the visibility of one or the other (which doesn't scale well), or you could even store them as values on an attribute placed on the element itself.
<p>Hello, <span data-values="World,People,Stack Overflow">World</span>.</p>
I have placed all possible values within the data-values attribute. Each distinct value is separated from the other values by a comma. We'll use this for creating an array of values next:
// Leverage event-delegation via bubbling
document.addEventListener( "click", function toggleWords ( event ) {
// A few variables to help us track important values/references
var target = event.target, values = [], placed;
// If the clicked element has multiple values
if ( target.hasAttribute( "data-values" ) ) {
// Split those values out into an array
values = target.getAttribute( "data-values" ).split( "," );
// Find the location of its current value in the array
// IE9+ (Older versions supported by polyfill: http://goo.gl/uZslmo)
placed = values.indexOf( target.textContent );
// Set its text to be the next value in the array
target.textContent = values[ ++placed % values.length ];
}
});
The results:
The above listens for clicks on the document. There are numerous reasons why this is a good option:
You don't need to wait for the document to finish loading to run this code
This code will work for any elements added asynchronously later in the page life
Rather than setting up one handler for each element, we have one handler for all.
There are some caveats; you may run into a case where the click is prevented from propagating up past a particular parent element. In that case, you would want to add the eventListener closer to your target region, so the likeliness that bubbling will be prevented is less.
There are other benefits to this code as well:
Logic is separated from markup
Scale to any number of values without adjusting your JavaScript
A demo is available for your review online: http://jsfiddle.net/7N5K5/2/
No, there isn't any native function, but you can create on your own.
function replaceword(that, word, oword) {
that.textContent = that.textContent == oword ? word : oword;
}
You can call it like this:
<p>Quickly<span onclick="replaceword(this,'Surf','Search');">Search</span>The Web!</p>
Live Demo: http://jsfiddle.net/t6bvA/6
<p id="abc">Hello</p>
<input type="submit" name="Change" onclick="change()">
function change(){
var ab=document.getElementById('abc').value;
ab.innerHTML="Hi, Bye";
}
I think so this should help you, you should go to site such as w3schools.com, its basic and it will answer your doubt
You can try something like this if you wanna use jQuery
http://jsfiddle.net/R3Ume/2/
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<body>
<p>Hello <a id='name'>John<a></p>
<input id="clickMe" type="button" value="replace" onclick="onClick();" />
<script>
function onClick() {
$('#name').text('world');
}
</script>
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.