Jquery one issue - javascript

My mark up
<form action="blah/foo" method="POST" id="frm1">
<input type="hidden" id="v" />
</form>
......
......
<!--after some code-->
<button id="btn1">test</button>
<input type="text" id="somevalue" />
My purpose is when i click the button btn1,Grab the value of somevalue and give it to the hidden value v and submit the form ,the form needs to submit (ONLY ONCE) so i used the jquery one method and thats working fine
Second thing is if somevalue is empty i dont want to submit
THE PROBLEM scenario
<script>
$('#btn1').one('click',function(){
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
$('#frm1').submit();
});
</script>
IF user first makes an empty input and try to submit the error msg will show..but after that even with a valid input the click event wont trigger(I know thats because of the one function)
Im looking for some alternative that the form will submit only once

var form_sent = false;
$('#btn1').click(function(){
if(form_sent == true){ return; }
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
form_sent = true;
$('#frm1').submit();
});

Instead of using 'one' so that the your handler is called only once, declare your handler as a named function and use jQuery's bind / unbind to remove the click handler if (and only if) the field has a valid value when the form is submitted. Otherwise keep listening on the click event. As such:
function onFormSubmitted (e) {
if($("#somevalue").val === "") { // If the field's value is invalid...
$('p#msg').html('Empty value'); // ... then show error message...
return; // ...and do nothing else - just keep on listening
}
// Ok, we have valid input so...
$('#btn1').unbind("click", onFormSubmitted); // ...stop listening...
$("#frm1").submit(); // ...and submit the form
}
// Start listening for the click event
$('#btn1').bind("click", onFormSubmitted);
Or, if you still want to use 'one' you can tweak the previous example, as such:
function onFormSubmitted (e) {
if($("#somevalue").val === "") { // If the field's value is invalid...
$('p#msg').html('Empty value'); // ... then show error message...
$('#btn1').one("click", onFormSubmitted); // ...re-attach one-time listener...
return; // ...and wait
}
// Ok, we have valid input so don't re-attach one-time listener...
$("#frm1").submit(); // ...just submit the form
}
// Add one-time listener for the click event
$('#btn1').one("click", onFormSubmitted);

try:
$('#btn1').one('click',function(){
callFunc();
});
function callFunc(){
if($('#somevalue').val() == ""){
$('p#msg').html('Empty value');
$('#btn1').one('click',function(){ callFunc(); });
return false;
}
$('#frm1').submit();
}

First off why not have your input in the form? Is there a specific reason to do it this way?
Also to do this in straight javascript rather than using jquery I would be doing something as follows:
<form action="blah/foo" method="POST" id="frm1" onsubmit="return validateForm();">
The validateForm just checks to see if the input is empty, if it is then it returns false, otherwise it returns true. Returning false to onsubmit will stop the form submitting.

Try bind event,
$('#btn1').bind('click',function(){
if(!$('#somevalue').val()){
$('p#msg').html('Empty value');
return false;
}
$('#frm1').submit();
});​

Related

javascript event handlers list

I am trying to prioritize click event in case two events click and change are fired.
I have a global function similar to "ValidateOnChange" and "ValidateOnClick" to validate input of text box on change and on click event.
Enter some text, it shows up error message. Then try to input correct value and click the Submit button, the error vanishes and this makes user to click the button twice. Here I am trying to fix this double click.
Here is mock up code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<div>Enter any string:</div>
<div><input type="text" id="txtInput" ></input></div>
<div id="divError" style="color: red; display: none;">Please enter 0</div>
<input type="button" value="Submit" id="btnSubmit" ></input>
<script type="text/javascript">
var mouseevent_var = null;
function ValidateOnChange(e) {
var input = $('#txtInput').val();
if (input == '0') {
$('#divError').hide();
} else {
$('#divError').show();
}
}
function ValidateOnClick(e){
alert("Hurray!!! You got it right!");
}
$('#txtInput').mousedown(function (e) {
mouseevent_var = e;
});
jQuery(document).ready(function(){
$('#btnSubmit').click(function(e){
ValidateOnClick(e);
});
$('#txtInput').change(function(e){
ValidateOnChange(e);
});
//User don't want error when they are typing in.
//$('#txtInput').keyup(function() {
//$('#txtInput').trigger("change");
//});
});
</script>
</body>
</html>
The keyup event seemed to be solution but users don't want the error to popup when they are typing in.
Is there any way to list all the triggered events so that I could filter "mousedown" and "mouseup" events for submit button? Or is there any alternative way to prioritize click event ?
There can be many alternatives depending on the situations. I have made few minor changes to avoid the double click issue (comments amended). Basically we need to bind the mousedown event on the button object. There we will set a temporary flag variable to true. In the same time if input's change event gets fired then you can skip the checking if the temporary flag variable is true. Reason behind the double click for triggering the button's click event is better explained here: How to get jQuery click event after append in change event handler
Your updated js code below:
var mouseevent_var = false;
function ValidateOnChange(e) {
// Skip validation if the change event is fired due to user's click on submit button
if(mouseevent_var){ return false; }
var input = $('#txtInput').val();
if (input == 0) {
$('#divError').hide();
} else {
$('#divError').show();
}
}
function ValidateOnClick(e){
mouseevent_var = false; // Reset mouseevent_var to false
alert("Hurray!!! You got it right!");
}
$('#btnSubmit').mousedown(function (e) {
mouseevent_var = true;
});
jQuery(document).ready(function(){
$('#btnSubmit').click(function(e){
ValidateOnClick(e);
});
$('#txtInput').change(function(e){
ValidateOnChange(e);
});
//User don't want error when they are typing in.
//$('#txtInput').keyup(function() {
//$('#txtInput').trigger("change");
//});
});
The above code is just a fix as per your need. But there are other better alternatives too. Ideally you should not have two different validation functions for validating same fields on different events. You must think of managing it with a single function.

how to add event handler for input text box

My program should contain both name search and ID search functionality, when user clicks the name search button, a name search validation is triggered to make sure that the required text field is not empty, on the other hand, when user clicks the id search button, an id search validation is triggered to make sure that a different required text field is not empty. So on the HTML file, I have the following jQuery and HTML codes.
$(document).ready(function() {
$('#submitIDSearch').bind('click', validateIDSearch);
$('#submitNameSearch').bind('click', validateNameSearch);
$('#searchLastName').bind('click', validateNameSearch);
$('#searchFirstName').bind('click', validateNameSearch);
$('#searchID').bind('click', validateIDSearch);
});
var validateNameSearch = function(event) {
var btnSrchLastName = getRef('searchLastName');
if (null != btnSrchLastName) {
var len = btnSrchLastName.value.length;
if (0 == len) {
alert('Last Name is a required field, please input Last Name.');
$('#searchLastName').focus();
return false;
}
}
return true;
}
var validateIDSearch = function(event) {
var btnSrchID = getRef('searchID');
if (null != btnSrchID) {
var len = btnSrchID.value.length;
if (0 == len) {
alert('ID is a required field, please input ID.');
$('#searchID').focus();
return false;
}
}
return true;
}
And I have the following HTML code:
<form id="infoForm" name="checkAbsenceForm" method="post" action="absenceReport.htm">
<label class="q">ID * <input id="searchID" name="searchID" maxlength="9" /></label>
<input id="submitIDSearch" type="submit" value="Search ID"/>
<hr />
<label class="q">First Name <input id="searchFirstName" name="searchFirstName" maxlength="23"></label>
<br />
<label class="q">Last Name * <input id="searchLastName" name="searchLastName" maxlength="23" /></label>
<input id="submitNameSearch" type="submit" value="Search Name"/>
<hr />
</form>
The code behaves correctly except for one problem, when ever the user clicks on the textbox, a click event is fired, which cause a pre-generation of the alert message box.
I observed that when the user types 'enter' key from a text field, a click event is triggered, instead of 'submit', so I guess my listener can only be bind to the click event.
May I ask if there's a workaround method to avoid event triggering from mouse clicking on the textbox?
Thanks a lot!
In case you still need help... http://jsfiddle.net/jaxkodex/Cphqf/
$(document).ready(function() {
$('#submitNameSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchLastName'), 'Last name field is required.')) {
$('#infoForm').submit();
}
});
$('#submitIDSearch').click(function(event) {
event.preventDefault();
if (validate($('#searchID'), 'ID field is required.')) {
$('#infoForm').submit();
}
});
});
function validate(input, errorMsg) {
if (input.val() == null || input.val().length == 0) {
alert(errorMsg);
return false;
}
return true;
}
Since you are using jQuery, You can submit the form whenever a button is clicked with $('#infoForm').submit(); If you check you'd need to use button inputs and no submit inputs any more, since they will trigger the submit event. This is just one approach. If you are looking for live validation, you could use the blur events instead of click but in the text inbut and the click event to the buttons to make sure it works. I guess that overwritting the submit function would work when you have to do some ajax. Hope it helps.
[Edit] If you want to keep the buttons as submit you can do some thing like: http://jsfiddle.net/jaxkodex/S5HBx/1/
You can use the submit event from the form, so it will check every time someone submits the form. jQuery - Submit
$('#infoForm').submit(function (event){
if (!validateIDSearch() && !validateNameSearch()){
event.preventDefault(); // Prevent the submit event, since didn't validate
}
// Will continue to the dafault action of the form (submit it)
});
You just need to set what button the user has selected and do validation based on that during form submit.
searchLastName searchFirstName submitNameSearch are calling validateNameSearch, and submitIDSearch searchRUID are calling validateIDSearch
$(function () {
var validateFx = null; //none selected;
$('#submitNameSearch, #searchLastName, #searchFirstName')
.bind('click', function () {
validateFx = validateIDSearch;
});
$('#searchIDSearch, #searchRUID')
.bind('click', function () {
validateFx = validateNameSearch;
});
$('#infoForm').submit(function (event){
event.preventDefault();
if (validateFx != null && validateFx ()) {
$(this).submit();
}
});
});

How to get jQuery event handler return value

I have a link with id="something":
html
<a id="something" onclick="getReturnValue()"> Something </a>
javascript
function getReturnValue(){
//some validation
if(validation fails){
return false;
}else{
return true;
}
}
I need to get the return value when I use:
$("#something").click();
How can I get the return value for the event ?
Already onclick function is mentioned in the html tag. I wanted to use:
$("#something").click();
and from that I wanted to get return value.
As I have to use it in multiple place, I dont want to write getReturnValue() method again and again like:
click(function(){ getReturnValue() })
I need to do this
if($("#something").click() == true){
form.submit();
}
click() will call getReturnValue() which will do some validation. If the validation fails, it return false and I need not submit the form. If validation is true, I need to submit the form
To do some form validation, you can do something like that:
$('#myForm').submit(function(e) {
if () {//Validation rules failed
e.preventDefault(); //Prevent browsers from submitting
}
//Form is valid do nothing and let the form submit
});
Now on your button:
$("#something").click(function() {$('#myForm').submit();//Calls function from above});
What you can do is create a jQuery event object and pass that to the click handler.
var e = jQuery.Event('click');
$('#something').click(e)
if (e.validResult) {
//action
}
You'll have to modify the click handler somewhat to take an event object and set a validResult property if the validation is successful.
function getReturnValue(e) {
//some validation
if (valid) {
e.validResult= true;
}
}
Here is an example on how you can access return data from event handler.
var a;
$(document).on('a', function(e){
$(document).trigger(a = $.Event('sum', {datas: e.datas}));
});
$(document).on('sum', function(e){
return e.datas;
});
$(document).trigger($.Event('a', {datas: [1,2,3]}));
console.log(a.result);//[1,2,3]
You change it with your purpose. check here https://api.jquery.com/event.result/ for more details.
$("#something").click(function() {
var x = getReturnValue();
});
this is what you want?
LE: and this means your a changes to
<a id="something"> Something </a>
you're trying to run two different functions on a click event,
maybe you need remove the inline code (onclick="func()") and put this in your script
$("#something").click(
function(){
var returnValue = getReturnValue();
}
);
I don't really understand your question though...

Why I have to return the return of my function when calling OnSubmit?

I have this JSP, look for the last line there is the main part of main question:
<script type="text/javascript">
function validate() {
if( $('#title_post').val() == "" || $('#content_post').val() == "" ){
alert('Por favor preencha todos os campos da mensagem.');
return false;
}
else
return true;
}
</script>
<script>
$(document).ready(function(){
$("#xdef").tagcloud({colormin:"d88",colormax:"0a0",height:300});
});
function seta_type(obj){
document.getElementById('topicType').value = obj;
}
</script>
<div id="wrapper">
<div id="col-left">
<c:url value="/${company}/produto/${product}/topico/addtopic.html" var="linkPost"/>
<form:form action="${linkPost}" modelAttribute="topic"
method="post" onsubmit="return validate();">
That last line has a return validate() if I keep it that way, my form gives me an alert if the fields are not filled, ok that's what I want.
My question is I tried to remove the return from that and if I do that I get the alert but when I press ok, the servlet continues to its regular actions instead of staying in the same page...
Why is that?
BTW I am a new to JavaScript to explain it in detail please.
When you return false from your function validate(), that false value is not actually passed to the event handler. You need to return the result of the function straight to the onsubmit attribute. This could also be a good time to suggest attaching event handlers in your JavaScript code itself.
Think of it as kind of like this...
form.addEventListener('submit', function() {
validate();
}, false);
Would that call to validate() pass its false to the event handler by magic? Nope!
In order to get the form submission to cancel, you need to return false from the onsubmit handler. By removing the return statement, you remove that behavior.
onsubmit="return validate();"
This actually returns the result of validate
Removing the return statement
onsubmit="validate();"
just calls validate, but doesn't return its result.
The onsubmit handler must itself return false to cancel the form submission
when the validation is failing, you have to return false to the form element to cancel the form submission request. If you return true to form, it continues with form submission request.

Is there a way to check if a postback is in progress?

In the case that a button is clicked multiple times on a page - Is there a way to figure out using javascript/jquery that a postback is already in progress and cancels the new attempt to submit the page?
Thanks
You can avoid users from double clicking by disabling whatever form elements can cause a form submit.
Checkout http://greatwebguy.com/programming/dom/prevent-double-submit-with-jquery/ for an example.
You can disable the button on first click, so that you could not click it when the post is in progress, and re enable it when the post-back has finished.
<script type="text/javascript" language="JavaScript">
var submitted = false;
function SubmitTheForm() {
if(submitted == true) { return; }
document.myform.submit();
document.myform.mybutton.value = 'Thank You!';
document.myform.mybutton.disabled = true;
submitted = true;
}
</script>
<form method="post" action="#">
<input type="submit" onclick=return SubmitTheForm()>
</form>
you could always just disable the button in the onclick handler.
$('input[type="submit"]').click(function(e) {
e.preventDefault();
var self = this;
$(self).attr('disabled', 'disabled');
$.post('url',$(self).closest('form').serialize(), function() {
$(self).removeAttr('disabled'); // re-enable after request complete.
});
});
You could have your click event set a variable in your click handler to true and only allow the handler to proceed when the value is false. Of course you will have to set it to false again when your callback finishes.
if (!processInProgress) {
processInProgress = 1
// start the process
}

Categories

Resources