How to add onclick to an element using Javascript - javascript

I have an HTML button like so:
<div class="row text-center">
<button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>
I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:
$("#button1").addEventListener("click", showAlert());
However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

With jQuery you can use .on():
$("#button1").on("click", showAlert);
or
$("#button1").click(showAlert);
addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:
$("#button1").get(0).addEventListener("click", showAlert);
or
$("#button1")[0].addEventListener("click", showAlert);
but there's really no reason.

try jquery function:
$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;

You could try the following:
$( "#button1" ).bind( "click", showAlert);

Related

javascript add onclick to html string

I got the following html string
<span class="text">North-West</span>
I need to add an onClick to this string in order to make it look like the following:
<span class="text" onClick="mySomeFunction()">North-West</span>
I tried to convert this string to jQuery element back and forth, or to use attr() or setAttribute() functions but it did not work. Any ideas how to do that would be welcome. Thank you.
If you are using jQuery, maybe you could put the event in your script file?
$('.text').on('click', mySomeFunction);
This way, you have your code organised in a file and it's a better practice. Inline JS is not very clean.
Without Jquery, using pure javascript:
Select your element
var t = document.querySelector('span');
Add your EventListener to detect the click
t.addEventListener('click', function(){
console.log('test');
someFunction();
})
var t = document.querySelector('span');
t.addEventListener('click', function(){
console.log('test');
alert('function');
})
<span class="text">North-West</span>
Here's an example:
html:
<button type="button" class="btn btn-primary" id="myConfirmButton">
Save changes
</button>
js:
var okbutton = document.getElementById("myConfirmButton");
okbutton.setAttribute("onclick", "deletedata('msgid',165);");

Javascript HtmlUnit

I have a submit button that I can't click on..
<div class="button_green">
<span>Send SMS</span>
</div>
I have tried this:
page = (HtmlPage) form.getInputByValue("Send SMS").click();
but that won't work.
Is there a way to click on this or run the Javascript with Java and HtmlUnit?
And it is not my site, so can't do anything with the html-code..
You can use XPath:
page = htmlPage.<HtmlDivision>getFirstByXPath("//div[#class='button_green'").click();
Which means: search for the first div with a class attribute of button_green, and click it.
W3schools has a good XPath tutorial.
This should work.
<script>
function sendSMS(){
alert('your sms function work here~~');
}
</script>
<span>Send SMS</span>
You will need to use the button tag like this:
<button type="button">Send SMS</button>
If you cannot edit HTML then you can do this using jquery. Try following code.
$( ".button_green" ).click(function() {
alert( "Handler for .click() called." );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="button_green">
<span>Send SMS</span>
</div>
To enable jquery first add a script line in the HTML page.

How to reach this element?

<div class="ptp-item-container">
<div class="plan">Text I want!</div>
<div class="price">200</div>
<div class="bullet-item">some other text</div>
<div class="cta"> <a class="button" href="javascript:getText()">Go!</a>
</div>
</div>
From the button I tried this:
function getText(){
alert($(this).parent().parent().children().text() );
}
This doesnt really work, I know there is a way! It's important to use $(this) for this time.
Edit: This is the whole Javascript:
<script>
jQuery(document).ready(function($) {
$(".ptp-button").attr("href", "javascript:getText()");
});
function getText(){
alert($(this).closest('.ptp-item-container').find('.plan').text());
}
</script>
But the console says "Uncaught TypeError: undefined is not a function VM4092:1(anonymous function)"
Dont I have to give $(this) as an argument on javascript:getText($(this)) or something like this?
You shouldn't be targeting it with javascript: href. Instead, use an .on() handler, that is the correct way to handle the click event on JQuery. Then you'll be able to use the this reference:
Then, as already answered, instead of navigation through the parents, use the .closest() function:
$('.ptp-item-container').on('click', '.button', function() {
alert($(this).closest(".ptp-item-container").find(".plan").text());
});
You can use a combination of .closest() and .find():
alert($(this).closest(".ptp-item-container").find(".plan").text());
It pays to spend some time browsing the jQuery API documentation.

Issue on Selecting Inputs inside a Div

Can you please take a look at following code and let me know why i am not able to get the ID of selected radios by using the this.id?
<div id="pay" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input type="radio" name="mode" id="option1"> Cash
</label>
<label class="btn btn-primary">
<input type="radio" name="mode" id="option2"> Cheque
</label>
</div>
<script>
$("#pay input:radio").on('click',function(){
alert(this.id);
});
</script>
Thanks
If that posted code is, in fact, the entirety of your jQuery you've simply forgotten to use the document ready handler:
$(document).ready(function(){
// your code should be in here
});
Or you could ensure that your <script> is placed before the closing </body> tag, both of which approaches ensure the content of the page is loaded and present in the page before you try binding event-handlers.
Try to use
$(this).attr("id") instead of this.id
this will work;
$(function(){
$(document).on('click', '#pay input:radio', function(){
alert($(this).prop('id'))
});
})
Make sure your jQuery code is executed once the DOM is ready:
$(document).ready(function () {
// All your function calls, self-invoked functions, etc
// Also you define your event handlers here
});
From the docs about the .ready( handler ):
Specify a function to execute when the DOM is fully
loaded
Then you need to transform this into a jQuery object to access its methods, e.g. .attr() like so: $(this)
Since jQuery version 1.7 you may use event delegation by using the .on() function.
Again the docs:
Attach an event handler function for one or more events to the
selected elements.
<script>
$(document).ready(function () {
$(document).on('click', '#pay input:radio', function() {
// Instead of using alert(), use the console for debugging
window.console.log($(this).attr('id'));
});
});
</script>

How to select a button id when the button in clicked injavascript/jquery

I am new to javascript/jquery .
I have a small question.
I have some thing like the following in the java script file.
<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />
so the click function looks like the follwoing
click(id){
/do some thing
}
so my question is when ever the button is clicked how can we pass the button id to the function.
<button id="button1" onclick=click("how to pass the button id value to this function") />
how can we pass the button id like "button1" to the click function when ever the button is clicked..
I would really appreciate if some one can answer to my question..
Thanks,
Swati
I advise the use of unobtrusive script as always, but if you have to have it inline use this, for example:
<button id="button1" onclick="click(this.id)" />
The unobtrusive way would look like this:
$("button").click(function() {
click(this.id);
});
You don't need to.
function handleClick(){
//use $(this).attr("id");
//or $(this) to refer to the object being clicked
}
$(document).ready(function(){
$('#myButton').click(handleClick);
});
That not very jQuery-ish. You should rather use event listeners:
$(function() {
$('#button1,#button2,#button3').click(clicked);
function clicked() {
// "this" will refer to the clicked button inside the function
alert($(this).attr('id'));
}
});
For starters: Don't use onclick(). This is the way to do it properly.
When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.
Doing the same in jquery is simple.

Categories