jQuery tabs and validate - javascript

I am using jQuery tabs and validating all fields are filled in prior to allow the user to move to the next tab. On a few of the tabs there are options where the user can choose from multiple options and, sometimes, the user will click option 1 and mean option 2 but when they try and click the previous button this validates the fields and won't let them until they have filled in all the fields which is a rubbish UX.
I would like to only validate on clicking a next button but not on clicking a previous button.
<a class="btn nexttab navbutton" href="#step1">Previous</a>
<a class="btn nexttab navbutton" href="#step3">Next</a>
Here is the code I am using currently:
var validator = $("#start").validate();
var tabs = $("#tabs").tabs({
select: function(event, ui) {
var valid = true;
var current = $(this).tabs("option", "selected");
var panelId = $("#tabs ul a").eq(current).attr("href");
$(panelId).find(":input").each(function() {
console.log(valid);
if (!validator.element(this) && valid) {
valid = false;
}
});
return valid;
}
});
To try and overcome this I added a class called next button to the next buttons only and then tried to change this line which I assume checks any input:
$(panelId).find(":input").each(function() {
to:
$(".nextbutton").click(function() {
but it allows the user to move to the next screen without having to fill in all the fields.
How can I make it so only forward movement is validated?
http://jsfiddle.net/553xmzh3/1/

I would like to only validate on clicking a next button but not on clicking a previous button. .... How can I make it so only forward movement is validated?
Simply put a cancel class on your "previous" button. All validation rules will automatically be ignored when a submit button contains a cancel class. However, the submitHandler will fire as if the form is valid.
<input type="submit" value="PREVIOUS" class="cancel" /><!--// This submit will not trigger validation //-->
<input type="submit" value="NEXT" /><!--// This submit will trigger validation //-->
Working DEMO: http://jsfiddle.net/4zdL8ha3/
EDIT:
Although it still works, using class="cancel" has been officially deprecated and replaced with formnovalidate="formnovalidate"
<input type="submit" value="PREVIOUS" formnovalidate="formnovalidate" />
Working DEMO: http://jsfiddle.net/4zdL8ha3/1/
Since you're using anchor tags instead of type="submit" elements, this solution will not work for you. It would be best to replace your anchor tags with a button element. That way, using CSS, you can style the button to look exactly the same as an anchor.
<button type="submit" class="btn nexttab navbutton" formnovalidate="formnovalidate">Previous</button>
<button type="submit" class="btn nexttab navbutton">Next</button>
Working DEMO: http://jsfiddle.net/4zdL8ha3/2/
EDIT:
If you must have anchor tags in place of type="submit" buttons, then you need to write the appropriate click handlers and check the form's validity only on the "next" button handlers. Using the .valid() method also simplifies your code by removing your custom validation tester from the tab switcher function.
$(".nexttab").click(function () { // NEXT BUTTON
if ($("#start").valid()) { // TEST VALIDATION
$("#tabs").tabs("select", this.hash);
}
});
$(".cancel").click(function () { // PREVIOUS BUTTON - NO VALIDATION TEST
$("#tabs").tabs("select", this.hash);
});
Initializations:
var validator = $("#start").validate();
var tabs = $("#tabs").tabs({
select: function (event, ui) {
var current = $(this).tabs("option", "selected");
var panelId = $("#tabs ul a").eq(current).attr("href");
return true;
}
});
DEMO: http://jsfiddle.net/553xmzh3/3/

Related

Click but stay on anchor

I have a navabar that uses anchors instead of links. I am making a chat feature and every time the user enters something into the chat, followed by enter, they are redirected to the first anchor. I know I need to probably use AJAX but I can't seem to figure it out. Here is the code.
<div id="tab3">
<h2>Chat Room</h2>
<div id="chatboxlog">
<div id="chatlog">
Loading chat please wait...
</div>
</div>
<div id="chatinput">
<form name="chatbox" class="userchat">
<input class="userchat" name="message" type="text" onkeydown="if (event.keyCode == 13) document.getElementById('chatbutton').click()"/><br>
<input class="userchat" id="chatbutton" name="submitmsg" type="button" onclick="submitChat()" value="Send" />
</form>
</div>
</div>
<script>
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
</script>
It seems to me you simply have an issue with your form being submitted (typically happens when user hits "Enter" while focus is on a form child element, other than a textarea) and it automatically reloads your page.
This happens for example when no action is specified on your form: the latter tries reloading what is currently in the browser navigation bar ("location"). In your case, if the location has a fragment (hash) to another anchor, the page will simply scroll to that anchor.
You can prevent the form submit action by using event.preventDefault(), either in your text input, or better on the form itself, by attaching a callback on the submit event.
// NOTE: try using id's rather than names.
// Select the appropriate form.
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
// Prevent the form from reloading the page.
event.preventDefault();
});
Demo: http://jsfiddle.net/8odryt5p/1/
Use preventDefault() to prevent form or page from reloading.
See Examples below
Click on Specific ID
$('#myId').click(function(e){
event.preventDefault();
});
For click on any class
$('.myClass').click(function(e){
event.preventDefault();
});
For click on Any Anchor inside page
$('a').click(function(e){
event.preventDefault();
});
To Prevent Page reload after click on any anchor inside a div or section
$('.myClass a').click(function(e){
event.preventDefault();
});

PHP - reload first page from anywhere on button click

I have the below javascript function which displays updated values after a UI slider selection on the click of a button. I have disabled the button across pages so that the button will not be clicked again.
$(function () {
var disabled = localStorage.getItem("updateDisabled");
if (disabled) $('#update').attr('disabled', disabled);
});
$("#update").click(function (){
this.disabled = true;
localStorage.setItem("updateDisabled", true);
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
In my page, I am trying to include another button like "Back" which when clicked on, will reload the initial page itself.
<form method="post" action"willdoit.php">
<input type = "button" value = "Back"></input>
</form>
However if I click on the button nothing happens.
<input type ="submit" value ="Back" />
This will submit your form. Your button you have will only be a button and do nothing.
Change the type to input type ="submit"

jQuery - Hide show not working properly in Chrome (Works only once)

Just wrote a jquery to show a comment button, when click on the textarea. Hide comment button clicking on somewhere else in the screen. Its working fine in Firefox. But in Chrome it working only once. When I click on textarea again the submit button is not showing, its still hidden.
$(document).on('click', ".comment_txt, .comment_btn", function() {
var post_id = $(this).attr("post-id");
$("#comment_btn_div_"+post_id).show();
});
$('body').click(function() {
$(".comment_btn").hide()
});
<form class="comment_submit" action="http://localhost:3000/api/v2/posts/48774/comment" data-post-id="48774" id="comment_form_48774">
<textarea post-id="48774" id="comment_txt_48774" placeholder="Comment" cols="40" rows="1" class="width100 comment_txt"></textarea>
<div id="comment_btn_div_48774" class="right comment_btn" post-id="48774" style="display:none">
<button onclick="$(this).text('commenting...')" class="btn btn-small btn-info right" id="comment_btn_48774" type="submit">Comment</button>
</div>
</form>
Not sure why this is not working in Chrome. There are many form in my page. So I have did $(".comment_btn").hide() on body click. In order to show a particular comment button i'm using this code $("#comment_btn_div_"+post_id).show();
Update:
After the comment button is hidden, Even when i do a $("#comment_btn_div_23232").show() from firebug console. Its not showing the div.
Update 2 (testing with alert):
$(document).on('click', ".comment_txt, .comment_btn", function() {
alert("commenttext area clicked");
$(".comment_btn").show()
});
$('body').click(function() {
alert("body clicked");
$(".comment_btn").hide()
});
Clicked textarea, got alert a. body clicked b. commenttext area clicked. Now comment button is shown
Clicked body got alert a. body clicked. Now Comment button is hidden
Clicked textarea, got alert a. body clicked b. commenttext area clicked. Now comment button is not shown.
Thanks!
Try it with blur
$(document).on('click', ".comment_txt, .comment_btn", function () {
var post_id = $(this).attr("post-id");
$("#comment_btn_div_" + post_id).show();
});
$('.comment_txt').blur(function () {
$(".comment_btn").hide()
});
FIDDLE
I run into this every once in a while. Have yet to figure out why it happens; it befuddles me. I solve it by using one of the other ways of "showing" divs. Most recently, I changed the css display property:
$("#comment_btn_div_"+post_id).css('display','block');
var post_id=null;
$(document).on('click', ".comment_txt, .comment_btn", function(event) {
post_id = $(this).attr("post-id");
$("#comment_btn_div_"+post_id).show();
event.stopPropagation();
$('body').bind("click",function() {
$("#comment_btn_div_"+post_id).hide()
$(this).unbind();
});
});
I hope it will work for you

JavaScript button function swap

What I am trying to do is following:
I have an input type button and I want to replace it's function on first click.
<input type="submit" class="submit-button" value="Submit" name="boom" />
So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).
So on first click it will be
alert('Something');
And on second click it will be default function (submit).
How can I achieve something like this?
Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.
Use one().
Attach a handler to an event for the elements. The handler is executed at most once per element.
Example:
$(".submit-button").one("click", function(e) {
// will only run on first click of element
e.preventDefault();
alert("Something");
});
Try this:
<script type="text/javascript">
var clicked = false;
function btnClick(e) {
if(clicked === false) {
alert('Something');
clicked = true;
e.preventDefault();
return true;
} else {
return false;
}
}
</script>
<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />

click the button then pop up a dialogthen submit the button

<button onclick="productAddToCartForm.submit(this)" class="button btn-cart" title="Add to Cart" type="button"><span><span>Add to Cart</span></span></button>
js codeļ¼š
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(){
if (this.validator.validate()) {
this.form.submit();
}
}.bind(productAddToCartForm);
The above is the normal step. click the button, then submit the form. now, i want to add one step before the form is submitted. the step is. when click the button, it will pop up a dialog. when close the dialog.there are some content on it. then submit the form.
1, i want to use jquery in productAddToCartForm.submit = function(){....} .if the page have loaded the jquery library.but i don't know how to add jquery code in the function. thank you
You can use jQuery show() and hide().
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(){
if (this.validator.validate()) {
$("#YourPopUp").show('slow', function() {
$('#YourPopUp').hide(1000,'slow', function() {
productAddToCartForm.form.submit();
});
});
}
}
}.bind(productAddToCartForm);
Edit: Here is a jsfiddle example of my answer -> jsfiddle
If your popup window will be an HTML page, you could bind to the click event on your button, display / close the popup and then call form.submit();
Give your button and form an id:
<form id="myForm" action="/formsubmit.html" method="post"></form>
<button id="submitButton" class="button btn-cart" title="Add to Cart" type="button"><span><span>Add to Cart</span></span></button>
Then do something like this with jQuery
$(document).ready(function () {
$('#submitButton').click(function (e) {
e.preventDefault(); //prevent the default action
//show your popup
//hide your popup
$('#myForm').submit(); //submit the form
});
});
If there is a button on the popup that the user will click to close it, you could call the submit function by binding to the click event of whatever element is used to close the popup.

Categories