button causing page to reload - javascript

I am using html and jquery on my page.
In my html i have one button which when clicked will fire one function.
When page loads i call main function in document ready. Here is my code
<script>
$(document).ready(function () {
main();
});
function main(){
//some code goes here
}
function search(){
//some logic
}
</script>
<div>
<button id="btnSearch" onclick="search()" >Search</button>
</div>
But when i click on button then it goes inside main function and executes code inside it. Why? It should only call function search and nothing else. What am i doing wrong?

by default BUTTONS are of type SUBMIT, try this instead
<button type="button" id="btnSearch" onclick="search()" >Search</button>

This is working fine for me. See demo
$(document).ready(function () {
main();
});
function main(){
//some code goes here
alert('main');
}
function search(){
//some logic
alert('search');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="btnSearch" onclick="search()" >Search</button>
</div>

Related

Button inside a form is not accessible

I'm trying to trigger the click event of a button inside a form using jQuery.
$(".switchLang").on("click", function(e) {
console.log("Clicked!")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-inline" action="">
<button type="button" class="btn mr-3 btn-link transparent switchLang">${{index.keys.lng}}$</button>
<button type="button" class="btn mr-3 btn-outline-light">${{index.keys.login}}$</button>
<button type="button" class="btn btn-primary">${{index.keys.getStarted}}$</button>
</form>
The function above is not invoked!
After research, I tried many solution but nothing's work. Like adding e.preventDefault(); inside the function also remove .click and replaced with .on and so on, but nothing works!
I have referred to this question: here.
Thanks.
Solved
I double checked my code. the html is written inside script of type text/template and this template is rendered before the jquery code. Thanks.
You could try
$(document).on("click",".switchLang",function (e) {
console.log("Clicked!")
});
Try this might help
$(document).on('click', '.switchLang', function (e) {
console.log("Clicked!")
});
You need to wait for the document to be ready before adding the click handler, like so:
$(document).ready(function () {
$('.switchLang').on('click', function (e) {
console.log("Clicked!")
});
});

Call Javascript function within Bootstrap button

I have a javascript code which I would like to put it in a function called SleepTime so I can pass in value and then call this function when I click on a button in an html page. Here's my code.
<script>
function SleepTime(value) {
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
});
});
}
</script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit" onclick="SleepTime(2000);" > Execute Script</button>
I get an error when I ran the above code. It said the function is undefined but I did define it?? How do I call this function so I can pass in the value??
tks
try this , the correct way of doing this , hope this helps:-
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
var sleepTime =$(this).attr('sleepTime');
setTimeout(function() {
//$('#progressBarCenter').modal('toggle');
console.log('will get printed after 2 seconds')
}, sleepTime);
});
});
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit" sleepTime=2000 > Execute Script</button>
There are two things you miss-used here:
Please do not use $(document).ready() inside another function,
SleepTime(), as $(document).ready() is supposed to be executed
after DOM elements already loaded.
You call function SleepTime() one in you attribute onclick(), and you defined click() event listener inside function SleepTime(), this as far as I concern, it never be executed.
The correct way is as below:
$(document).ready(function() {
function SleepTime(value) {
alert(value);
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
}
$('#ajaxSubmit').click(function() {
SleepTime(2000);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<div class="container">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit"> Execute Script</button>
</div>
you can do one of these solutions
First One, using a java script function
-remove data-toggle="modal" data-target="#progressBarCenter"
-remove document ready, and click event listener from the function
-then call function on onclick
<script>
function SleepTime(value) {
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
}
</script>
<button type="button" class="btn btn-primary" id="ajaxSubmit" onclick="SleepTime(2000);" > Execute Script</button>
Second One, Using a JQuery event
-remove data-toggle="modal" data-target="#progressBarCenter"
-remove the function and put the code inside jQuery event listener
-remove onclick attribute from html
<script>
var value = 2000;
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
});
});
</script>
<button type="button" class="btn btn-primary" id="ajaxSubmit" > Execute Script</button>

Trying to make a button in JavaScript but it's not working

I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>

Fire button click event when there are multiple classes on an element

How would I fire a button click event when a particular button is pressed (in this case the accept button).
I've tried the following but with little success:
Javascript
$('.notification-expand .Request .active-item > .accept-button').click(function () {
alert("hello");
});
HTML
<div class="notification-expand Request active-item" style="display: block;">
<div class="notification-body"></div>
<br>
<p>
<button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
</p>
<div class="row">
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
</div>
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
</div>
</div>
</div>
Fiddle here
You have error in your selector , it should look like this:
$('.notification-expand.Request.active-item .accept-button').click(function () {
alert("hello");
});
You need to concatenate all classes without spaces to catch your target button
$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
alert("hello");
});
See the updated snippet
Notice the syntax of ".className1.className2" instead of ".className1 .className2"
should be something like:
$('button.accept-button').click(function(){ ... });
there is really no need to go down the whole list if this is the whole code
----edit----
so when there are more items but only 1 active(i guess) then just target the active-item class:
$('div.active-item button.accept-button').click(function(){ ... });
try
$('.accept-button', $('.notification-expand.active-item')).click(function () {
alert("hello");
});
or
$('.notification-expand.active-item')).find('.accept-button').click(function () {
alert("hello");
});
Just give the button an id and reference back to that.
HTML
<button id="btnSubmitData"> Ok Button </button>
JQuery Code
$('#btnSubmitData').click(function(){ ... });
You can also have multiple button Ids bind to the same event:
$('#btnAccept, #btnReject, #btnWarning').click(function () {
alert("hello");
});
Take a look at the updated Working Fiddle.

jquery code for getting the href of 'a' tag near the button that is being clicked

Good day.
I just want to get the href of a link once the button near the link is being clicked by the end user. But the problem is there are lots of buttons and links. So, if the end user will click the first button, it should display the "www.a.com". If the 3rd button is being clicked, it should display "www.c.com". Can any one help on how to get it done perfectly? Thanks...
<div>
<a href='www.a.com'>a</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.b.com'>b</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.c.com'>c</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.d.com'>d</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<script type="text/javascript">
function validate()
{
alert($('div a').closest('a').attr('href'));
}
</script>
Try with parent and child like
function validate()
{
alert($(this).parent('div').child('a').attr('href'));
}
Or even you can get it with prev like
alert($(this).prev('a').attr('href'));
I should do it linke this:
$(document).on("click",".btn",function(){
alert($(this).prev('a').attr('href'));
});
With this code the onclick is not needed
use:
function validate()
{
alert($(this).siblings('a').attr('href'));
}
try
$(document).ready(function () {
$(".btn").click(function () {
alert($(this).parent().children("a").attr("href"));
});
});
remove onClick='validate()' from all buttons
and try following code
$('.btn').click(function () {
alert($(this).prev().attr("href"));
});
Use need prev() with source of event, also pass the source object to function
Live Demo
Html
onClick='validate(this)'
Javascript
function validate(obj)
{
alert($(obj).prev('a').attr('href'));
}

Categories