I have a small code in JS for 3 tabs in my page. They are meant to help me switch between those tabs without reloading the page. However, the tabs just show up one by one on top of each other and stay there. Could anyone please take a look and tell me what the problem is?
Also, if it's possible - after I've chosen a tab and tried to submit data from one of the tabs using a form and PHP and the validation did not pass, can I add something here so that the same tab stays active and is shown instead of the page just refreshing back to first tab? I would also like the same form stay there even if the form was submited successfully.
This is the JS part:
function onTabClick(event) {
let activeTabs = document.querySelectorAll('.active');
console.log(activeTabs);
// deactivate existing active tab and panel
for (let i = 0; i < activeTabs.length; i++) {
activeTabs[i].className = activeTabs[i].className.replace('active', '');
}
// activate new tab and panel
event.target.parentElement.className += 'active';
document.getElementById(event.target.href.split('#')[1]).className += 'active';
}
const elements = document.getElementsByClassName('nav-tab-element');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', onTabClick, false);
}
This is the HTML part. The tabs in UL element and one of the 3 forms. I didn't include all of them just so there isnt too much code here, but they got the right IDs.
<ul id="nav-tab" class="nav">
<li class="active">
<a class="nav-tab-element" href="#books">Books</a>
</li>
<li>
<a class="nav-tab-element" href="#dvds">DVD's</a>
</li>
<li>
<a class="nav-tab-element" href="#furniture">Furniture</a>
</li>
</ul>
<!-- Tabs -->
<form action="" method="POST">
<!-- Books Tab -->
<div class="tab-content active" id="books">
<div class="book-tab">
<input type="text" name="sku" placeholder="SKU" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="name" placeholder="Name of the product" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="price" placeholder="Product price" autocomplete="off">
</div>
<div class="book-tab">
<input type="text" name="size" placeholder="Weight in KG" autocomplete="off">
</div>
<!-- Submit Buttons -->
<div class="btn">
<input type="submit" value="Submit">
<input type="reset" value="Clear">
<input type="hidden" name="type" value="book">
</div>
</div>
</form>
And lastly, this is the CSS part:
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
Im very new to JS, therefore any help will be apreciated. Thank you.
Check your CSS. The CSS displays how the element looks and to some extent how it reacts to user input. JS will add to CSS to make the interactivity of the website
i would suggest using frameworks as they simplify A LOT of functionality. As such, you do not need to recreate the wheel.
my favorite right now is vuejs but i started with jQuery. Both these frameworks are based on javascript.
Another good framework is bootstrap which uses CSS and jQuery among a few others to streamline client side.
Check out tabs in bootstrap which handles all this functionality for you
If you want a tutorial using a similar approach of your check this out w3schools
Form posting
You can use AJAX to post the form to where ever and the form will look as though it was not posted. Therefore the tabs wouldnt need to be changed.
If you do not want to use ajax
Using your loop to attach the eventlister add check to see if the window url property is set. this article covers this
Related
i am loading handlebar templates in the two div locations(like add and edit tabs both are jsps) from the same page. so i have duplicate elements in the DOM object, since it is a template which is coming from server location. you can see the sample code below
<div id="add">
<div id="exploding">
<input type="text" name="city" id="city"/>
<input type="text" name="state" id="state"/>
...
</div>
</div>
<div id="edit">
<div id="exploding">
<input type="text" name="city" id="city"/>
<input type="text" name="state" id="state"/>
...
</div>
</div>
I can't modify the div container ids i.e exploding since some javascript functions attached to it based on that id to explode address field.
here the problem is if i made any changes to the edit tab, address "exploding" div, it is effecting in add tab address "exploding" since ids are repeated. i have tried jquery detach method to remove the dom elements, but didn't get proper result. Its a web application based on spring boot.
is there any possibility to load jsps dynamically through jquery, i have tried load method as well, but the call is going through controller. I didn't feel it as better option.
Thanks & Regards
krishna K
I am completely new to Meteor and I'm trying to build a simple app. I currently have a form with 4 radio options and a submit button. When users click the submit button and I want to know which radio option they selected. I have no idea how to get started though. Can anyone help me? Below is my html and javascript code, respectively:
<form class="form-horizontal well mystery-form">
<fieldset class="col-md-offset-1">
<h2>{{question}}</h2>
<br>
<div class="form-group">
<div class="col-md-10 mystery-form">
{{#each answers}}
<div class="radio">
<label>
<input type="radio" name="mysteryForm" checked=""
style="margin-bottom: 0; margin-top: 0;">
{{answer}}
</label>
</div>
{{/each}}
<br>
<button type="reset" class="btn btn-default">Back</button>
<!-- Hide this when the answer is correct -->
<button type="submit" class="btn btn-primary">Check Answer</button>
<!-- Show only if the answer is correct -->
<button class="btn btn-primary">Next</button>
</div>
</div>
</fieldset>
</form>
JS:
Template.mystery.events({
"submit .mystery-form": function(event) {
// no idea what to do here
}
});
Semantics
You'll probably want to remove the whole wrapping .radio element. It's unnecessary. Try using as few elements as possible. It performs better and makes debugging easier.
Retrieving the checked input
The event object passed to an event-map callback has a property target. In your case that is .mystery-form. So you can use a simple jQuery selector to find the checked element:
$('input[name="mysteryForm"]:checked', event.target)
This will get you the checked value with the name mysteryForm. This was quiet straight forward. The problem is retrieving the value. Doing that would get sort of messy. So I'd just pass it to the element as a data- attribute:
<input type="radio" name="mysteryForm" checked="" style="margin-bottom: 0; margin-top: 0;" data-answer="{{ answer }}" >
Now you can simply do this:
$('input[name="mysteryForm"]:checked', event.target).data('answer')
First, you may want to prevent the normal form submission and avoid a page reload. As you are building a single page application you will want to do the form submission logic by yourself. Also, reloading the page by form submission does not make any sense in such application.
Secondly, you have to actually gather the data, and then do what you want with these data.
Put it all together and you get something like this:
Template.mystery.events({
"submit .mystery-form": function(event, template) {
//1. prevent default behavior (form submission)
event.preventDefault();
//2. get your data
//either by name (HTML name attribute)
var inputValue = template.mysteryForm.value;
//or by id (HTML id attribute)
var inputValue = template.find('#myId').value;
//3. Do whatever you want (method call for example?)
Meteor.call('myMethod', inputValue, function(error, result) {
//wait for the call result...
});
}
});
I've been trying for some time now (some time = whole day) to figure out why I have this strange problem with my form. I have a client who wants a stand-alone HTML page running locally which would display one form with couple of textbox and one button. After info is entered and user click that button, a second form should show up with new textboxes. Form can't have a redirection to another website or file. It all has to be in that (HTML) file.
I figured out this would be easiest to do with jQuery but loading whole library just to hide one form is plain stupid. So I take a look at other option and decided to use pure Javascript.
The problem is when I click "NEXT" first time the 1st form disappear but then apear a second later like some sort of request is sent. Bellow is the code I currently have. I tried making an JSFiddle but browser blocks every time I access it.
Javascript:
function hideAll() {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
showFirstForm();
}
function showFirstForm() {
if (document.getElementById('second').style.display == 'block') {
document.getElementById('first').style.display = 'block';
document.getElementById('second').style.display = 'none';
}
}
function showSecondForm() {
if (document.getElementById('first').style.display == 'block')
{
document.getElementById('second').style.display = 'block';
document.getElementById('first').style.display = 'none';
}
}
HTML:
<body class="if5" onload="hideAll()"> // I'm loading hideAll() on refresh to hide second form
....
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<filedset>
<label for="name"> Your name </label>
<input name="name" value="MyName" /></input>
<button onClick="showFirstForm()">Next</button>
</filedset>
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme" /></input>
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>
....
References:
getElementByID
Besides the fact that you have your form id's switched, <button> has a default type of submit. So when your button is clicked it is posting the form to #. So correct your form ids, and then change your button code type to button:
<button type="button" onClick="showSecondForm()">Next</button>
Here are some docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
Here is a working jsfiddle using the corrected code: http://jsfiddle.net/789SP/
First off, any button in a form that doesn't have a type attribute or has a type attribute of submit will by default submit the form on click.
Second, it looks like you are trying to implement some sort of wizard. If this is true you don't want each part to be it's own form because at the end you're going to want to send all of this data to the server which won't work if it's in two forms.
The entire thing needs to be in one form with sections inside that you show/hide. To navigate between the sections you'll want to use
<button type="button" onClick="showSecondForm()">Next</button>
To do wizards is always a pain in the butt. Once you start handling validation you need to figure out which step has an error in it and show that section, or if the user uses the back button they might expect the form to go back to step one. You might want to search for a third party solution that provides some of the boiler plate functionality. These might help
This should get you off to a good start though.
Edit
Don't attempt this from scratch. Use this
<!-- FORM 2 -->
<form id="first" action="#" class='tx_anmelden' method="post" autocomplete="off" >
<fieldset> **fieldset was misspelled as "filedset"**
<label for="name"> Your name </label>
<input name="name" value="MyName"></input> **your input had /> at it's end, which is unfortunately wrong**
<button onClick="showFirstForm()">Next</button>
</fieldset> **fieldset was misspelled as "filedset"**
</form>
<!-- FORM 1 -->
<form id="second" class='tx_anmelden'>
<fieldset>
<label for="name"> Your name </label>
<input name="name" value="MyNaffffffme"></input> **your input again had /> at it's end, which is unfortunately wrong**
<button onClick="showSecondForm()">Next</button>
</fieldset>
</form>
I've got a form that uses jQuery to set the value of a text field. The form doesn't work when the page is first loaded, but it does work after the refreshing the page To help, describe the problem, I recorded a ~30 second video (hosted on SwfCabin):
Any idea what might be causing this? I'm a jQuery newb and I've no clue!
Here's jQuery code
$(document).ready(function () {
$(".category").each(function () {
$(this).find("a").click(function (event) {
event.preventDefault();
var category = $(this).text();
$("#post_categories").val(category);
});
});
});
And here's the HTML form:
<form accept-charset="UTF-8" action="/posts" class="new_post" id="new_post"
method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="OCbmfFY1cNsaa5e+SbvcSrP0ubQTg432ECNGmvaU8bM="
/>
</div>
<p>
<label for="post_title">Title</label>
<input id="post_title" name="post[title]" type="text" />
</p>
<p>
<label for="post_url">Url</label>
<input id="post_url" name="post[url]" type="text" />
</p>
<p>
<label for="post_categories">Pick a category</label>
<input type="text" id="post_categories" />
</p>
<p>Available choices:</p>
<ul>
<li class="category"> programming
</li>
<li class="category"> cats
</li>
<li class="category"> batman
</li>
</ul>
<p>
<input name="commit" type="submit" value="Submit" />
</p>
</form>
Looks fine ,make sure you have included jQuery lib, also you can optimize the code a bit.
$(document).ready(function() {
$('.category a').click(function(event){
event.preventDefault();
var category = $(this).text();
$("#post_categories").val(category);
});
});
Fiddle: http://jsfiddle.net/DGW3Q/
I thought Arun P Johny and Farhan had provided the answer I was looking for, but it turns out I had a different problem. The app I'm writing is Ruby on Rails and I didn't get the memo about how Rails' Turbolinks overrides some jQuery functionality.
For example, by default in Rails 4.0.0, Turbolinks handles executing JavaScript on page load. This means I was trying to use $(document).ready(;, but Turbolinks had hijacked that functionality. For reasons I don't yet fully understand, refreshing re-enabled my jQuery script and then it started working. I guess Turbolinks' version of $(document).ready(; doesn't get reset when the page is refreshed?
As a short term hack, I ended up solving the problem by installing the RubyGem "jquery-turbolinks". At some point I'll need to learn how to use or disable Turbolinks. Maybe I should just learn to use Angular or Ember :) DOM shenanigans are a pain!
Ryan Bates discusses Turbolinks in Episode #290 of Railscases, including how code gets executed at page load.
I'm struggling to find a solution for this anywhere on Google, maybe i'm searching incorrectly but thought I would come and ask the ever trustworthy members of StackOverflow.
I'm wanting to use an html button to check an html check box. There reason I don't want to use the check box will be purely for accessibility reasons because the application i'm developing will be on a terminal and used as via a touch-screen so an HTML check box is too small.
The only issue is that the list of check box's is dynamic as it is populated using an SQL query. Obviously however I can do the same for creating HTML buttons.
Im guessing it will require JavaScript (which I'm perfectly happy using now as I'm finding a lot of the functionality I need in this application needs JavaScript) to do this functionality.
So to clarify: I want to click on a button, say it has a value of "Fin Rot" and that checks the check box with the value "Fin Rot". And then if I clicked another button, say it has a value of "Ich" then it also checks the check box with the value "Ich"
While you can use a button and JavaScript for this, might I suggest a much simpler approach? Just use a <label> that's designed just for this, and style it like a button, for example:
<input type="checkbox" id="finRot" name="something" value="Fin Rot">
<label for="finRot">Some text here, could be "Fin Rot"</label>
or (if you don't want to use id on checkbox and for on label):
<label>
<input type="checkbox" name="something" value="Fin Rot">
Some text here, could be "Fin Rot"
</label>
....then with CSS you can hide the checkbox if needed, but either are clickable to toggle the checkbox.
You can test out a demo here, also showing some button-ish CSS on the label if needed.
This example uses a button to toggle the checkbox on/off.
http://jsfiddle.net/DnEL3/
<input type="checkbox" id="finRot" name="something" value="Fin Rot">
<button onclick="document.getElementById('finRot').checked=!document.getElementById('finRot').checked;">Fin Rot</button>
How about a HTML solution.
<p><input type="checkbox"
value="Another check box"
name="cboxwithlabel" id="idbox"><label
for="idbox">Another
checkbox</label></p>
<label> Creates label for the checkbox or radio buttons.
If you are looking for bootstrap solution, I just created this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class="col-md-6">
<!-- Here starts the component -->
<label class="input-group">
<span class="input-group-addon">
<input type="checkbox">
</span>
<span class="form-control btn btn-primary">
Click to toggle checkbox
</span>
</label>
<!-- Here ends the component -->
</div>
</div>
</div>