How to submit a form when tab is click - javascript

I would like to submit a form, when a tab is clicked. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit a Form on Tab Click</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style type="text/css">
</style>
<script>
$(function() {
$( "#Main" ).tabs();
});
</script>
<script>
$(document).ready(function(){
$('#Tab1').click(function(){
$('#Form_1').submit();
});
</script>
</head>
<body>
<div id="Main">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
<form id="Form_1" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="1">
</form>
<div id="Tab1">
<p>Tab1</p>
</div>
<div id="Tab2">
<p>Tab2</p>
</div>
<div id="Tab3">
<p>Tab3</p>
</div>
<div id="Tab4">
<p>Tab4</p>
</div>
<div id="Tab5">
<p>Tab5</p>
</div>
<div id="Tab6">
<p>Tab6</p>
</div>
</div>
</body>
</html>
Each tab will submit a different form. I hope this helps to identify what I am trying to
achieve. I am new to all this so please be specific.
Thank you.

You can use this jQuery:
jsFiddle here
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
var tabId = $(this).attr('id');
alert('Tab clicked: ' + tabId );
if (tabId == 'ui-id-1') {
$('#LoginForm').submit();
}else if (tabId == 'ui-id-2') {
$('#form2').submit();
}else if (tabId == 'ui-id-3') {
$('#form3').submit();
}
});
});
jQueryUI tabs all have IDs beginning with ui-id-#, where # is the tab number (for example, ui-id-3.
The selector $('[id^=ui-id-]') means: For any element whose ID attribute begins with ui-id-, trap the click event and do this...
Note that the <form> tag must have an ID attribute, as specified in the above code. For example, for the form on Tab 3:
<form id="form3" action="whatever.php" method="POST">
Suppose each tab has a form on it and, for example, the forms all have IDs that are sequentially numbered according to the tab they are on, such as Form-1, Form-2, Form-5, etc. Then you could use the line var tabId = $(this).attr('id') to do this:
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
var tabId = $(this).attr('id'); //ui-id-4
var tabNum = tabId.split('-')[2]; //4
$('#Form-' + tabNum).submit();
});
});
For example, suppose the tab's ID is ui-id-4, then you would want to give the <form> for tab 4 an ID: <form id="Form-4">. The above code would then submit that form when the tab was clicked.
Note that the above code expects that your form tags will have an ID, such as:
<form id="myFormId" action="somepage.php" method="POST" >

Assuming your form will have an id of 'myform', you can put a click event listener on the tabs.
Add a class to your tabs class='tab'
$('.tab').on('click', function(){
$('#myform').submit();
});

The tabs widget has some events you can use. For example, when a tab is activated, you can have a handler for the activate event. You can use standard jQuery event handling, and specify the tabsactivate event. Something like this:
$('#Main').on('tabsactivate', function (event, ui) {
// your logic here
$('#someForm').submit();
});
You can inspect the ui argument passed to that event handler for information about the tab. For example, the specific tab being moved from/to. Like:
if (ui.oldPanel.selector == '#Tab1') {
// The user just left Tab1
}
So within that handler you'd perform whatever task you need to perform when a tab changes.

First each tab could have a reference to each form that must be submitted on tab click.
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
Then bind a click event to each tab:
$("#Main").on("click", "a", function() {
var formId = $(this).data("form");
$(formId).submit();
});

The easy way, asign an id attribute to each <a> and <form> and then do this:
<script type="text/javascript">
$(document).ready(function(){
$('#tab1').click(function(){
$('#form1').submit();
});
$('#tab2').click(function(){
$('#form2').submit();
});
$('#tab3').click(function(){
$('#form3').submit();
});
});
</script>
A fiddle example here

Related

use Jquery to click hyperlink

I am trying to create a jquery to click a hyperlink but nothing seems to be working.
HTML
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
no avail
Show all
</div>
what I was trying
$(".warning a").click()
Any suggestions?
Note that jQuery-initiated "click" events will fire the event but will not cause navigation to occur.
Instead you can read the link's HREF attribute and directly set the window location:
// The click event:
$('a').on("click", function() {
console.log("Click event fired");
})
var demo1 = function() {
// This will trigger the click event, but will not navigate.
$(".warning a").click()
}
var demo2 = function() {
// This will navigate but will not trigger the click event. (If you need both to happen, trigger the click event first, and consider delaying the window location update if necessary.)
var url = $(".warning a").attr("href")
window.location = url;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main id="main" class="main-content">
<div class="container">
<div class="warning" role="alert">
Show all
</div>
</div>
</main>
<!-- for demo: -->
<button onclick="demo1()">Won't work</button>
<button onclick="demo2()">Will work</button>
jQuery's .click() (without arguments) is a shortcut for .trigger("click"):
function(a,c) {
return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b)
}
Therefore, it will not actually click the element, but just call the click event handlers attached to it, as you can see here:
const $link = $("a");
$link.on("click", () => {
console.log("Clicked? Not really...");
});
$link.click();
$link.trigger("click");
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to get a reference to the actual DOM element and then call HTMLElement.click() on that:
$("a")[0].click();
Show all
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can user the vanilla click method:
document.querySelector('.warning > a').click()
// equivalent jquery
//$('.warning > a')[0].click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="warning" role="alert">
no avail
Show all
</div>
Whenever you select div class with hyperlink there you get array because you can have multiple hyperlinks so you need to add somthing like below
Code
$('.warning a')[0].click();
For reference link
Get working example for click event
If I need to redirect, I typically use window.location.href
window.location.href=$(".warning a").attr('href');

How to incorporate Jquery UI sortable code?

I am trying to incorporate Jquery UI sortable into the the unordered list I have below. When I click on the button in the form below, it insets the text into #companyassessment_set1 and then submits the form.
When I try to include the javascript for the sortable part, nothing works (existing jquery code + sortable functionality). The code is here:
$(document).ready(function(){
$('#menu-pages').sortable();
});
rest of code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js"></script>
<script src="http://twitter.github.io/bootstrap/assets/js/jquery.js"></script>
<script src="http://twitter.github.io/bootstrap/assets/js/bootstrap-tab.js"></script>
<script>
jQuery(function () {
$('#test').click(function (e) {
e.preventDefault();
alert('test');
data = 'Benefits,Predictable hours,Up or out,Job for life,Great corporate strategic vision,Strong profitability,Performance-based,Strong alumni network,Effective managers,Fast growth,Salary and bonus,Little ranking between employees,No working on the weekends,Competitive environment,Great brand for the resume,International opportunities,Brand recognition,Smart people,Stock growth,Perks,No layoffs,Type-A employees,Fast advancement,Reasonable hours'
$("#companyassessment_set1").val(data);
$("form#new_companyassessment").submit();
});
});
</script>
<p>
<label for="companyassessment_Company Name">Company name</label><br />
<div class="field_with_errors"><input id="companyassessment_name" name="companyassessment[name]" size="30" type="text" value="" /></div>
</p>
<ul class="menu" id="menu-pages">
<li id="page_1">Home</li>
<li id="page_2">Blog</li>
<li id="page_3">About</li>
</ul>
<input id="companyassessment_set1" name="companyassessment[set1]" type="hidden" />
<input id="test" type="button" value="Set Value" />
Any advice on how to incorporate the Jquery UI code?
Your second jquery reference is overwriting the jqueryui reference and so your sortable method isn't recognized. Remove this and you should be okay:
<script src="http://twitter.github.io/bootstrap/assets/js/jquery.js"></script>
Also the line where you define the 'data' variable needs a semi-colon at the end.
<script>
$(function() {
$( "#menu-pages" ).sortable();
$( "#menu-pages" ).disableSelection();
});
</script>
http://jqueryui.com/sortable/
d di you look int o this view source

if jQuery element hasClass() change different element link text

I am using a jQuery function to add/remove a class to the clicked element, which works just fine. However when that element is clicked, I am trying to change the text of an HTML link and I cannot seem to get it working. The HTML link is located within the <span> element further down the page.
When <button id="people"> hasClass('user_view_active') the HTML link should display "People" when <button id="jobs"> hasClass('user_view_active') the HTML link should display "Jobs".
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function(){
$('button').each(function(){
$(this).removeClass('user_view_active');
});
$(this).addClass('user_view_active');
});
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").attr("href").text(text.replace('People'));
}else{
$('.title').find("a").attr("href").text(text.replace('Jobs'));
}
});
</script>
</head>
<body>
<div id="container">
<header>
<img src="images/header-name.png" width="200px" style="display: inline; margin-bottom: -10px;"/>
<button id="jobs" class="user_view">Jobs</button>
<button id="people" class="user_view_active user_view">People</button>
<div class="header_search_wrapper">
<form action="" method="POST">
<textarea class="header_search" name="app_search" placeholder="Search people, jobs, or companies" style="width: 430px;"></textarea>
<input type="submit" class="share_btn" value="Search">
</form>
</div>
</header>
<div id="main" role="main">
<!--! begin app content -->
<div class="right_sidebar">
<span class="right_title">Connection Suggestions</title>
</div>
<span class="title">Recent Updates >> People</span>
To replace the text within a link you can use the jQuery .text() function. This function can also get the text value and also set the text value - as is shown in the example below -
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
This code would have to be wrapped in the callback function of the click event to work -
$(document).ready(function() {
$('button').click(function(){
$('button').removeClass('user_view_active');
$(this).addClass('user_view_active');
if ($('#people').hasClass('user_view_active')){
$('.title').find("a").text('People');
}else{
$('.title').find("a").text('Jobs');
}
});
});
Now each time the button is clicked, you can check for the existence of the user_view_active class on the #people element.
Okeydokey ?
Are you sure those are the right tags ?
<span class="right_title">Connection Suggestions</title>
Are you sure an <a> element inside a <button> element is a good idea?
<button id="jobs" class="user_view">Jobs</button>
role="main" is'nt a valid attribute, but will probably work anyway.
This just seems easier:
$(document).ready(function() {
$('button').on('click', function(){
$('button').removeClass('user_view_active');;
$(this).addClass('user_view_active');
$("a", ".title").text(this.id);
});
});
FIDDLE
Try this way:
$('#people').toggleClass('user_view_active').html($('#people').hasClass('user_view_active')?'People':'Jobs');

How to trigger('click') on jquery tab's currently active tab

I have a tabed screen and want to trigger a click on the selected tab once the form is submitted and the return is valid. Here a part of the html:
<ul id="tabUL" class="tabs js-tabs same-height">
<li class="current">
<a class="tabLink" href="#tabProducts" data-url="/bla/bla">Products</a>
</li>
</ul>
My success command is :
success: function(data, textStatus, XMLHttpRequest) {
$('#tabUL').find('li.current a').trigger('click');
}
This seems not working... Any help is appreciated :) Regards Andrea
Try using the a[href=""] selector:
$('#tabUL a[href="#tabProducts"]').trigger('click');
I put together a jsfiddle demo to show it in action, and how to optionally hide the other tabs since often when I'm programmatically forcing tabs its to require missing mandatory information be entered on the initial tab before unlocking the other tabs...
Edit
Here is the contents of the jsfiddle:
HTML
<div id="tabs">
<ul>
<li>Address</li>
<li>Shipping</li>
<li>Parts</li>
<li>Datasheets</li>
</ul>
<div id="tab0">
<h1>This is the first tab (0)</h1>
</div>
<div id="tab1">
<h1>This is the second tab (1)</h1>
</div>
<div id="tab2">
<h1>This is the third tab (2)</h1>
</div>
<div id="tab3">
<h1>This is the fourth tab (3)</h1>
</div>
</div>
<br/>
Select the
<select id="tabSelect">
<option value="0">1st</option>
<option value="1">2nd</option>
<option value="2">3rd</option>
<option value="3">4th</option>
</select>Tab and
<input type="checkbox" id="tabHide" checked="checked" /> Lock the Others
jQuery
$(document).ready(function () {
$('#tabs').tabs();
$('#tabSelect').change(function () {
//pass empty array to unlock any locked tabs
$('#tabs').tabs({disabled: []}).find('a[href="#tab' + $(this).val() + '"]').trigger('click');
if ($('#tabHide').prop('checked')) {
//hide will be an array like [0,2,3]
var hide = Array();
$('#tabs li').not('.ui-tabs-active').each(function () {
hide.push($(this).index());
});
$('#tabs').tabs({disabled: hide});
}
});
});
If you want to reload the tab programmatically then i recommend use Jquery Tab API utility like below:
This makes first tab active and then activates second tab, quite simple and also raises the events that would be normally raised when you click directly.
$( "#myTabs" ).tabs( "option", "active", 0 );
$( "#myTabss" ).tabs( "option", "active", 1 );
Also you can catch tabs active event like below for performing any operations
$( "#myTabs" ).on( "tabsactivate", function( event, ui ) {
// your custom code on tab click
});
rather than trying to trigger the click event itself (which I believe is not possible to invoke a user event programatically in this context), I suggest that you trigger the function that has to be called on click event, you might want to look into triggerHandler

How to catch a state change event ONCE with history.js?

I have an example code below where if you click the links, then use back and forward, each state change will cause more and more hits on the statechange event. Instead of the one that I expect.
Links:
https://github.com/browserstate/history.js
http://docs.jquery.com/Downloading_jQuery
Code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>History start</title>
</head>
<body>
<h1>Headline</h1>
<hr>
<div id="menu">
<ul>
<li>
Page 1
<div style="display:none;">
<h2>Page 1</h2>
<p>Content 1</p>
</div>
</li>
<li>
Page 2
<div style="display:none;">
<h2>Page 2</h2>
<p>Content 2</p>
</div>
</li>
</ul>
</div>
<hr>
<div id="content">
<h2>Start page</h2>
<p>Paragraf</p>
</div>
<script src="external/jquery-1.6.2.min.js"></script>
<script>if ( typeof window.JSON === 'undefined' ) { console.log("Loaded json2"); document.write('<script src="external/json2.js"><\/script>'); }</script>
<script src="external/history.adapter.jquery.js"></script>
<script src="external/history.js"></script>
<script>
$(document).ready(function() {
History.enabled = true;
$('a').each(function() {
$(this).click(function(e) {
e.preventDefault();
var $link = $(e.target),
state = {'href': $link.attr('href'), 'title': $link.html()},
$div = $link.siblings('div'),
content = $div.html();
$('#content').html(content);
History.pushState(state, state.title, state.href);
return false;
});
});
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
// remove double hit on event
console.log(State);
});
});
</script>
</body>
</html>
It's because you're calling the pushState function when you load the page, which also causes a statechange. I was in a similar situation and used a but a boolean before my pushStates so I knew I was doing a pushState. It looks like this...
historyBool = true;
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
//don't run our function when we do a pushState
if(historyBool){
historyBool = false;
tempFunction = new Function(State.data.ajaxRunFunction);
tempFunction();
}
historyBool = true;
});
historyBool = false;
historySet = {ajaxRunFunction: "upc('" + pageID + "','')"};
History.pushState(historySet,"","");
While not relevant to your specific problem, I had a scenario where I needed to unbind the event handler from the History Adapter. To do so you can unbind the "statechange" event from window, which is what History.Adapter binds to when you call History.Adapter.bind() :
$(window).unbind('statechange.namespace');
You can added a namespace to the event to avoid unbinding other unrelated event handlers as above, or use a named function to unbind that function specifically.
To use the above namespace, you would need to bind the handler using the same namespace, ie
History.Adapter.bind(window,'statechange.namespace',function(){...}

Categories