avoid auto-refresh on clicking button - javascript

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;
});

Related

On click bind to form child button

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>

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();
}

Meteor: form with two submit buttons (determine button clicked in event handler)

I have a simple form with two inputs: "title" and _"description", and two buttons: "save" (save for later) and "submit". For both I would want to get the values of my form fields and insert/update my collections accordingly.
<template name="NewScenarioForm">
<form id="newScenarioForm" >
<textarea type="text" id="title" name="title" rows="1" cols="75" placeholder="Type to add a title"></textarea><br/>
<textarea type="text" id="description" name="description" rows="4" cols="100" placeholder="Type to add a description" ></textarea><br/>
<input type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
</form>
</template>
Right now I'm detecting the event like this:
"click #saveScenarioButton": function(event, template) {
event.preventDefault();
var title = template.find("#title").value;
var description = template.find("#description").value;
...
//Do stuff with this information to persist information
Meteor.call("saveScenario", title, description);
....
}
And I need to repeat the whole function for the other button. I would would like to detect the event and determine which button was pressed instead.
I have been struggling with an event handler like:
"submit #newScenarioForm": function(event) {
But then I don't know how to determine the button clicked, since I can't figure out an event property. Is there a way to determine the button if I wanted to use the form ID in my event handler instead of the ID of each button (or a smarter way to approach this altogether?)?
You could make the event target inputs with type submit:
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
// Save the scenario
} else if ($(e.target).prop("id") == "submitScenarioButton") {
// Submit the scenario
}
}
});
You could also make it check the clicked button's value, and drop the ID field
Please note that this will not handle other ways of submitting the form, for example the user pressing Enter in an input field. An approach to handle this as well could be to define a few functions:
function scrapeForm() {
// Collects data from the form into an object
}
function saveData() {
var formData = scrapeForm();
// More logic to save the data
}
function submitData() {
var formData = scrapeForm();
// More logic to submit the data
}
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
saveData();
} else if ($(e.target).prop("id") == "submitScenarioButton") {
submitData();
}
},
"submit #NewScenarioForm":
// Default action on submit.
// Either save the data
saveData
// or submit the data
submitData
// or nothing, requiring the user to actually click one of the buttons
function(e) {e.preventDefault();}
});
Why not just give them both the same class like submitForm
<input class="submitForm"** type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input class="submitForm" type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
then have a onClick for .submitForm like so:
$('.submitForm').on('click', function () {...});
and inside the function get id by doing:
var id = $(this).attr('id');
full code:
$('.submitForm').on('click', function () {
var id = $(this).attr('id');
... the rest of your code ...
});
I do this to correctly identify buttons using class or id.
helloWorld.html
<head>
<title>helloWorld</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button class="plus5">+5</button>
<button class="minu5">-5</button>
<button id="plus1">+1</button>
<button id="minu1">-1</button>
<p>You've pressed the button {{counter}} times.</p>
</template>
helloWorld.js
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('counter', 0);
Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.hello.events({
'click button.plus5': function () {
Session.set('counter', Session.get('counter') + 5);
},
'click button.minu5': function () {
Session.set('counter', Session.get('counter') - 5);
},
'click button#plus1': function () {
Session.set('counter', Session.get('counter') + 1);
},
'click button#minu1': function () {
Session.set('counter', Session.get('counter') - 1);
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
click .plus5, click #plus1 also work.

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 :)

Disabling input tags and focusing on submit button

I have a code here for disabling the radio on a form and focusing on the submit button right after the timer expires. But this code seems not to work. Can you tell me what's wrong with my code or if you have any alternative with this? I'm using jquery timeTo plugin as my timer ..
<script type="text/javascript">
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus();
});
});
function disablefocus(){
$(document).ready(function() {
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
});
</script>
---->
<div id='countdown'></div>
<form>
<input type='radio' name='radio1' value='father'>
<input type = 'submit' id ='submitwidget' value='submit'/>
</form>
you add extra curly braces for timeTo function and miss the closed curly braces for disableFocus function.
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus);
function disablefocus(){
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
}
});
or another way
$('#countdown').timeTo(5000, function() { disablefocus(); });
$(document).ready(function() {
$('#countdown').timeTo(20, function() {
disablefocus();
});
function disablefocus(){
var message = $('#confirmMessage');
var goodColor = "#66cc66";
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
message.css("color" , goodColor);
message.html("Press me now!");
}
});

Categories