jquery show hide form fileds using next and previous button - javascript

i have a form with 100s question in it..and checkbox or radio button as a option to answer the questions..
<b style="font-weight:bold">1.How long have you been working in field of Programming?</b><br/>
<input type="radio" name="1" value="Less than 2 years" style="cursor:pointer">
<span style="display: inline-block;font-size: 13px;position: relative;top: -2.5px;">Less than 2 years</span>
<input type="radio" name="1" value="3-5 years" style="cursor:pointer">
<span style="display: inline-block;font-size: 13px;position: relative;top: -2.5px;">3-5 years</span>
<input type="radio" name="1" value="6-10 years" style="cursor:pointer">
<span style="display: inline-block;font-size: 13px;position: relative;top: -2.5px;">6-10 years</span>
<input type="radio" name="1" value="11-15 years" style="cursor:pointer">
<span style="display: inline-block;font-size: 13px;position: relative;top: -2.5px;">11-15 years</span>
the above html is my first question out of 100 questions....so for this i have decided..to create a next and previous button for 10 questions at a time on a screen?
any suggestion or help would be a great help?.. thanks in advance..

Here is the most simple approach I could get.
HTML:
Add div's for pages (1st page has an extra active class)
<div class="page active">
<!-- A set of questions go here -->
</div>
<div class="page">
<!-- Another set of questions go here -->
</div>
...
CSS:
.page { display: none; }
.active { display: inherit; }
jQuery:
$("#prev").on("click", function(){
if($(".page.active").index() > 0)
$(".page.active").removeClass("active").prev().addClass("active");
});
$("#next").on("click", function(){
if($(".page.active").index() < $(".page").length-1)
$(".page.active").removeClass("active").next().addClass("active");
});
And its done!
Fiddle with this example here: http://jsfiddle.net/V8LCL/

I'll try my best given your small sample, but it seems to me you are very far away from being able to generalize the code to a page approach. I'll explain why
Brute approach
If you don't want to change anything I would say for you to write your 100 questions on the DOM like you have in your sample and create a section for each block of 10:
<section class="section-1" ... > </section>
Then in your javascript code you can have the current active page, let's say you start with 1:
var visiblePageIndex = 1
A next button would increment the page by 1 and a back button would decrement the visible page by 1, obviously taking into account the limits, 1 <= page <= 10.
Now for the show and hide, you need to make the display setting of the section to be lets say inline-block for the visible page index, and none for the all the others. You can do this in two ways:
In the same event where you process the next and back you can use jQuery to query all sections that contain the number of the visible index (http://james.padolsey.com/javascript/regex-selector-for-jquery/).
Having a css selector with the same functionality (http://css-tricks.com/attribute-selectors/)
I would prefer the second. This should do the trick but obviously this is maintenance heavy, and it doesn't adjust automatically.
A more dynamic approach
I will try to illustrate the key points of this approach, the code will have to written by you, or if you get me a sample, I can help you get there.
You will need to store your questions and possible answers in a data structure, hopefully in a JSON or XML (bah) file, or if you can't be bothered simply inline in your JS block.
This will allow you to iterate over that structure with javascript and append to the DOM the number of questions you want to see each time. A click on next or prev will just change the index from where you start and draw the respective group.
You can save the answers in the same structure so when the user navigates back he will see his/her selections.
The pros of this option are:
Dynamically adjusts for the size of questions
You can customise how many questions are shown with a simple variable change
it's more lightweight, since you don't have to load a massive DOM.
You practice your JS a bit.
I hope this helps, there are a ton of possible solutions for this. This is just a couple of them, but I would definitely try to go number 2 or anything similar instead of hacking it (option 1).

Related

How can I restore proper function of the tab key and traverse all form inputs?

I'm building an interactive speed calculator and I want desktop browser users to be able to navigate and provide inputs using the keyboard alone if they wish.
Codepen here: https://codepen.io/mannadu/pen/EBNmzz
I tried to accomplish this using the tabindex="0" property on all form inputs, as well as on list items which allow the user to choose from among a few popular running event distances.
Tabbing across the form works fine If I tab through the elements without making a selection, but the tab key stops working as soon as I choose a value from among the popup options for the "Distance" input.
Any suggestions as to what is wrong with the code, and what needs to change to restore expected behavior of the tab-key after entering the first input value?
Relevant portion of the html:
<?xml version="1.0" encoding="UTF-8"?>
<div class="form-group center-content distance-input">
<label class="col-form-label" for="race-distance">
<input size="10" type="text" tabindex="0" id="race-distance" v-model:value="input_distance" class="btn btn-outline-light form-control-lg-border border-light" on:blur="modalTrackEvent" v-on:focus="modalTrackEvent" rows="1" v-on:change="modalTrackEvent" v-on:keyup="modalTrackEvent" placeholder="Distance" />
</label>
<!--CHANGE DISTANCE UNITS -->
<!--COMMON RACE LENGTHS -->
<div class="event-modal track-evt-list" v-bind:class="[ismodalvisible ? 'observable' : 'invis']" tabindex="0">
<ul>
<li class="btn btn-outline-light" v-bind:class="[ismodalvisible ? 'observable' : 'invis']" v-on:keyup.enter="setInputDist" v-on:mousedown="setInputDist" v-for="(trackevt, idx) in trackevent" v-bind:key="idx" v-bind:raceid="idx" tabindex="0">{{ trackevt.id }} {{ trackevt.label }}</li>
</ul>
</div>
</div>
The tab keys are still working. It's just that because you used CSS opacity to hide the elements by using opacity: 0 in your invis class (and opacity: 1 in the observed class), the tab key will cycle through all those "hidden" buttons (they are still there, just transparent) as well. Just keep hitting the tab key and you will see the cursors appearing eventually.
If you use the visibility property and replace opacity: 1 with visibility: visible, opacity: 0 with visibility: hidden in your CSS it should work as expected. (Elements with visibility: hidden will not be part of the tab key cycle.)
A working CodePen example can be seen here.

A way to access all my form elements without creating different functions for different ids

I'm working on a project for my web design class. We have to make a website for a fake company, not really important info. This is combined HTML, CSS, and JavaScript. Anyway, so I'm making an order page with a form and everything, and I have a ton of fieldsets all with different ids, since they all ask different questions. I want to display one fieldset at a time, and have a "Next" button that will hide the current fieldset and display the next one. So each fieldset will be set to
display: none;
until you press the button. I was going to use javascript
document.getElementById("").style.display = "block";
to do this. But I just started learning javascript a couple days ago and I'm not sure how to do this with so many different ids. I don't want to have create a different function for each fieldset. I have a total of 24. I don't think an array would work, nor incrementing a numeric id, cause these don't function as numbers right? Sorry, I'm very new to JavaScript. Any help would be greatly appreciated.
Here is something simple to get you going.
<html>
<head>
<script>
function NextClicked(incomingStepID)
{
document.getElementById("question" + incomingStepID).style.display = "none";
document.getElementById("question" + (incomingStepID + 1)).style.display = "block";
document.getElementById("buttonToClick").setAttribute("onclick", "NextClicked(" + (incomingStepID + 1) + ")");
}
</script>
</head>
<body>
<div id="NextHolder"><button type="submit" id="buttonToClick" onclick="NextClicked(1);">next</button></div>
<div id="question1" style="display: block">q1</div>
<div id="question2" style="display: none">q2</div>
<div id="question3" style="display: none">q3</div>
<div id="question4" style="display: none">q4</div>
</div>
</body>
</html>
I would start off by setting up all visibility stuff in CSS using classes. Something like:
.hidden {
display: none;
}
Put your fieldsets in order of display, with all set to hidden except the first:
<fieldset>
...
<button onclick='next(event)'>Next</button>
</fieldset>
<fieldset class='hidden'>
...
</fieldset>
Now, ideally you'd associate the click handler in JS rather than on the HTML page, but keeping things simple, you'd do it like above. The next function then just needs to get the next fieldset and clear the classname while setting its own fieldset's classname to 'hidden'.
function next(event) {
var self = event.target;
var parent = self.parentNode;
var nextFieldset = self.nextSibling;
parent.className = 'hidden';
nextFieldset.className = '';
}
Didn't get a chance to test it, but that should get you in the ballpark.

Populate a hidden form field using the div of a drop menu (drop down menu is created using divs not select, option etc)

I have a form.
Please note I must use divs for creating the form drop down and not the select option method etc. It just has to be done that way. The code is below.
<form action="url.asp" method="get">
<div class="search-button"><i class="fa fa-search"></i><input type="submit" /></div>
<div class="search-drop-down">
<div class="title"><span>Choose Category</span><i class="fa fa-angle-down"></i></div>
<div class="list">
<div class="overflow">
<div class="category-entry" id="Category1">Category One</div>
<div class="category-entry" id="Category2">Category Two</div>
</div>
</div>
</div>
<div class="search-field"><input type="text" name="search-for" id="search-for" value="" placeholder="Search for a product" /></div>
<input type="hidden" id="ChosenCategory" name="ChosenCategory" value="CATEGORY1 OR CATEGORY2 (WHICHEVER SELECTED)" />
</form>
As shown in the code above I need to populate the hidden field value as per the chosen option which the user selects in the drop down.
I have used about 20 different variations of getElementById or onFocus functions but cannot get it to work.
The only thing I can get to work is the following JavaScript and it just populates the hidden field value with the first id ignoring completely which one has actually been selected(clicked) by the user;
var div = document.getElementById('DivID');
var hidden = document.getElementById('ChosenCategory');
hidden.value = div.innerHTML;
I'm running classic asp so if there is a vbscript way then great, otherwise if I have to use JavaScript to do it then as long as it does the job I'll be happy still.
A click handler on the options could be used to update the value.
No jQuery or any other external library is needed. Below is a working example. Of course, in your case the input element could be of type hidden, but I made it text here for the sake of demonstration.
//Add the click handlers
var options = document.getElementsByClassName('option');
var i = 0;
for (i = 0; i < options.length; i++) {
options[i].addEventListener('click', selectOption);
}
function selectOption(e) {
console.log(e.target);
document.getElementById('output').value = e.target.id;
}
div {
padding: 10px;
}
div.option {
background-color: #CCC;
margin: 5px;
cursor: pointer;
}
<div>
<div class="option" id="Category1">Category One</div>
<div class="option" id="Category2">Category Two</div>
</div>
<input type="text" id="output" />
You should be able to achieve what you're after with a fairly simple setup involving listening for clicks on two separate <div> elements, and then updating an <input> based on those clicks.
TL;DR:
I've put together a jsfiddle here of what it sounds like you're trying to make work: https://jsfiddle.net/e479pcew/5/
Long version:
Imagine we have 2 basic elements:
A dropdown, containing two options
An input
Here's what it might look like in HTML:
<div class="dropdown">
<div id="option-one">Option 1</div>
<div id="option-two">Option 2</div>
</div>
<input type="text" id="hidden-input">
The JavaScript needed to wire these elements up should be fairly easy, but let me know if it doesn't make sense! I've renamed things throughout to make things as explicit as possible, but hopefully that doesn't throw you off.
One quick thing - this is an incredibly 'naive' implementation of this idea which has a lot of potential for refactoring! However I just wanted to show in the most basic terms how to use JavaScript to make this stuff happen.
So here we go - first things first, let's find all those elements we need. We need to assign variables for the two different dropdown options, and the hidden input:
var optionOne = document.getElementById("option-one");
var optionTwo = document.getElementById("option-two");
var hiddenInput = document.getElementById("hidden-input");
Cool. Next we need to make a function that will come in handy later. This function expects a click event as an argument. From that click event, it looks at the id of the element that was clicked, and assigns that id as a value to our hiddenInput:
function valueToInput(event) {
hiddenInput.value = event.target.id;
}
Great - last thing, let's start listening for the clicks on specific elements, and if we hear any, we'll fire the above valueToInput function:
optionOne.addEventListener("click", valueToInput, false);
optionTwo.addEventListener("click", valueToInput, false);
That should get you going! Have a look at the jsfiddle I already linked to and see if it makes sense - get in touch if not.
Are you allowed to use JQuery in this project? It would make your life a lot easier. You can detect when a div is clicked and populate the hidden field.
This could do it:
$(document).ready(function() {
$('.category-entry').click(function() {
$('#ChosenCategory').val($(this).text()); }); });

Javascript simple script for changing input value by <a> name element

I need this script to work real badly. been trying to fix it all day.
Basicly, whenever you click on an example from the list it needs to update either the Normal background, or the Hovered background (as user select).
but it requires IDs so i can add links as new examples, so whenever i add a new with a value in it's 'name' it needs to be a new example.
its like having the same script , but twice. one for normal bg, and one for hovered.
theres also a list show/hide script that i haven't figured out how to make work,
i'm not much of a javascript scripter but i managed to get that in a few hours.
i really need some help here, and i will appreciate if you help me.
thank you.
/Edward
jsfiddle.net/5tq2Y this is the fiddle. but it won't work on it for some reason
the js:
<script type="text/javascript">
function change_bg(){
document.getElementById('button_bg').value = 'BY THE DIFFRERENT <A> NAMES';
}
function change_bg_hover(){
document.getElementById('button_bg_hover').value = 'BY THE DIFFRERENT <A> NAMES';
}
</script>
the input that needs the updates:
<input type="text" id="button_bg" name="button_bg" value="">
<input type="text" id="button_bg_hover" name="button_bg" value="">
the html:
<b>Show/Hide Background examples list</b><br />
<a id="changer" name="images/examples/1.jpg" onclick="change_bg()"><u>Example 1 Red</u></a><br />
<a id="changer" name="images/examples/2.jpg" onclick="change_bg()"><u>Example 2 Blue</u></a><br />
<b>Show/Hide HOVERED Background examples list</b><br />
<a id="changer" name="images/examples/1_hovered.jpg" onclick="change_bg_hover()"><u>Example 1 Blue Hover</u></a><br />
<a id="changer" name="images/examples/2_hovered.jpg" onclick="change_bg_hover()"><u>Example 2 Red Hover</u></a><br />
For starters, you can't have multiple elements with the same id value, so your id="changer" will have to change. I would propose class="changer".
Edit: I actually gave them unique ID's so you could look them up for the complicated means of retrieving their attributes in the fixed code. If you want them to share a common rule for css or javascript targeting, I still recommend class="changer".
I think what you want to have is this:
User clicks a link.
Background of a different element changes
What it changes to depends on what was in the name attribute of the clicked link.
If that's accurate, well, I don't even know how to do it cleanly without jquery. Try this for the html:
<u>Example 1 Red</u><br />
<u>Example 2 Blue</u><br />
and this for the javascript
function change_bg(elem){
document.getElementById('button_bg').value = elem.name;
}
function change_bg_hover(elem){
document.getElementById('button_bg').value = elem.name;
}
Fiddle: http://jsfiddle.net/aGCNn/
Ask how to do it with jQuery, you'll like the answer. I promise!
I made a fiddle that work http://jsfiddle.net/juzVG/2/
Please check if this what you want.
I also made a few modifications to the code.
Example 1 Red<br />
Example 2 Blue<br />
<b>Show/Hide HOVERED Background examples list</b><br />
Example 1 Blue Hover<br />
Example 2 Red Hover<br />

jQuery update form element

I have a form that I create a checkbox on a click of a button. I am using https://github.com/pixelmatrix/uniform which provides an update function to style dynamically create elements which does not work. I got a work around but my problem is that it also reset the already created elements so they double, triple etc.
They are wrapped in a div with a class of checker. Is there a way to check if the div is around it first before applying my $('.table').find('input:checkbox').uniform(). I have tried different examples but they dont seem to work with my code and my jQuery is still limit.
Thanks
<div class="checker" id="uniform-160">
<span>
<input type="checkbox" name="chbox" id="160" style="opacity: 0;">
</span>
</div>
jQuery:
$(".fg-button").live("click", function(){
$('.table').find('input:checkbox').uniform()
});
Try this:
$('.table input:checkbox').not('div.checker input').uniform()

Categories