On click bind to form child button - javascript

I have a simple form and I am trying to apply my custom function it like this:
$(document).ready(function(){
$("#async_form").asyncpost(defaultAjaxCallback);
});
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(){
event.preventDefault();
$.post(url, data, callback);
});
}
I want to dynamically get the children.btn of form and detect on click on that. This is working but the problem is that where ever on form i click the click is fired. What am I missing here?

The immediate problem is that $.on takes a string in its selector parameter, not a jQuery object. You'll also need to pass event into your click handler, and get the serialized form data in the click handler instead of the ready handler.
$(document).ready(function () {
$("#async_form").asyncpost(null);
});
$.fn.asyncpost = function (callback) {
var url = $(this).attr('action');
$(this).on('click', 'input[type=submit]', event => {
event.preventDefault();
var data = $(this).serialize();
console.log(url, data, callback);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="async_form" action="post.php" method="POST">
<input name="text">
<input name="checkbox" type="checkbox">
<input type="submit">
</form>

Check for current target and target property of event.
e.currentTarget will return element on which you have clicked.
e.target will return element to which the event is attached.
The idea is to check that current target should not be equal to target of event.
Your code will be modified to :-
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(e){
if(e.currentTarget != e.target){
event.preventDefault();
$.post(url, data, callback);
}
});
}
You can also do this way :-
$(this).on('click', 'input[type=submit]', function(e){
event.preventDefault();
$.post(url, data, callback);
});
var btn = $("#frm").children('input[type=submit]');
$("#frm").on("click",btn,function(e){
if(e.currentTarget != e.target){
e.preventDefault();
console.log(e.target);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frm">
<input type="submit"/>
</form>

Related

How to call function inside Javascript

<script type="text/javascript>
function submitMe() {
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
}
</script>
<input type="hidden" name="jsfields" id="jsfields" value="">
I'm searching the way to get checked Ids of Jstree in form submit. So this is what I get. However, how I can call this function in my program?
Use a click/submit event
$(form).submit(submitMe);
or
$('[type="submit"]').click(submitMe);
Don't forget to prevent the default event and then trigger it after the code:
function submitMe(e) {
e.preventDefault();
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
window.location = $(this).closest('form').submit();
}

jQuery button click registering previous clicks

I have a form with multiple buttons that submit to it that differ by value. After I click a button, and then click a second button, the function operates on them both instead of just the second button. Is there a way to prevent this behavior?
This is somewhat related to a question I asked here: Why does function only work on second click? but the solution isn't valid if there a multiple buttons as it just registers the first button from the list of buttons.
JS:
$(document).ready(function () {
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').on('submit', function(event) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
});
function create_post(btnval) {
console.log("create post is working!");
$.ajax({
HTML:
<form action="/create_post/" method="POST" id="post-form">
<div class="col-sm-4" id="toprow">
<h4 style="font-family:verdana"> Models </h4>
<img src='{% static 'images/USAcomplete2.png' %}' class="img-responsive thumbnail" id='gbimg' >
<div class="btn-toolbar">
<button type="submit" name="model" value="test" class="btn btn-default">test</button>
<button type="submit" name="model" value="test2" class="btn btn-default">test2</button>
<button type="submit" name="model" value="test3" class="btn btn-default">test3</button>
</div>
</div>
</form>
You need to prevent the form from submitting before the user clicks the button.
$(document).ready(function () {
$('#post-form').on('submit', function(event, myval) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').trigger('submit', myval);
});
Update
Sorry, I think this code should work. The above code would run twice, since a button click would be considered a form submit as well.
$(document).ready(function () {
$('#post-form').on('submit', function(event) {
event.preventDefault();
});
$(':button').click(function (){
var myval = $(this).attr("value");
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
What is happening here is that you are binding the submit event to #post-form a second time when a second button is clicked, as the binding happens inside the button clicking event callback.
The best way to prevent this is to move this
$('#post-form').on('submit', function(event) {
...
});
outside of your button click event.

onclick radio button fadeout body and redirect

<div id="language-container">
<form id="language_radio">
<input type="radio" value="//domain.tld/page.php?lang=02" name="language" id="alb">
<label for="alb">Shqip</label>
<input type="radio" value="//domain.tld/page.php?lang=03" name="language" id="eng">
<label for="eng">English</label>
</form>
</div>
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("body").fadeOut(800, newpage);
});
</script>
What I'm trying to accomplish is, when a radio button is selected, I want to fade out the entire body, and then redirect to another page.
However, I can't seem to get it to do anything. It won't fade out or redirect.
How can do I fix it (newb to JS) :)?
You can use:
$("html").fadeOut();
as such:
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
// This variable is useless
// You can remove it if it's not
// being used
newLocation = $(this).val();
$("html").fadeOut(800, function() {
// Redirect to the newLocation here
// similar behavior as clicking on a link
window.location.href = newLocation;
});
});
</script>
try :
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("html").fadeOut(800, function() {
window.location.href = newLocation;
});
});
</script>
you can do this by
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
$("body").fadeOut(1000,function(){
window.location.href = $(this).val();
})
});
jsfiddle

avoid auto-refresh on clicking button

I have simple HTML code
<form class="searchbox" action="" >
<input type="search" placeholder="Search KB" id="SearchField"/>
<button value="search" id="SearchButton"> </button>
</form>
and simple event listener
$('#SearchButton').on("click",function(events) {
// your stuff
alert("work darn it!!!!!!!!!!!!!!!!!!!!!!!!!")
events.preventDefault();
var bla = $('#SearchField').val();
console.log("bla")
var jsonString = JSON.stringify(bla);
return false;
});
when i click button page keeps refreshing
when i put this
It doenst run my event listener when i do this
I am not getting where i am going wrong
Update your Jquery like this -
$(document).ready(function(){
$('#SearchButton').click(function() {
alert('working fine..');
return false;
});
});
Update like below,
$(function(){
$('#SearchButton').click(function() {
alert('working fine..');
var bla = $('#SearchField').val();
alert('Search field name :'+bla);
return false;
});
This should work now. You've to just disable the default function that submit button in a form has that is to self post.
$('#SearchButton').on("click",function(e) {
// Stop propagation & prevent Default action
e.stopPropagation();
e.preventDefault():
alert("work darn it!!!!!!!!!!!!!!!!!!!!!!!!!")
var bla = $('#SearchField').val();
console.log("bla")
var jsonString = JSON.stringify(bla);
return false;
});

JavaScript Prevent Form Submit

I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.
I have this code:
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var link = $(this).attr("href"); // "get" the intended link in a var
var result = confirm("Are you sure you want to log this fault?");
if (result) {
document.location.href = link; // if result, "set" the document location
}
});
});
The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.
My HTML code is:
<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">
<!-- other elements -->
....
....
....
<button type="submit" id="submit" class="btn btn-default">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
</form>
$(function() {
//this would do the same as button click as both submit the form
$(document).on("submit", "#myform", function (e) {
var result = confirm("Are you sure you want to log this fault?");
//if cancel is cliked
if (!result) {
return false;
}
//if ok is cliked, form will be submitted
});
});
the following like won't work since this reffers to the submit button which does not have an href attribute.
var link = $(this).attr("href"); // is invalid.
try
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var result = confirm("Are you sure you want to log this fault?");
if (result) {
$('#formId').submit(); // where formId is the id of your form
document.location.href = "url to which you want to redirect";
}
else
return false;
});
});
side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)

Categories