Create a function to hide divs - javascript

I want to display tables when a selection is made in a form and a 'Generate Factsheet' button is clicked. I've got a working code where I individually hide other divs when displaying the one I am interested in. Since I have several options in the form (and hence several corresponding divs in which the respective tables are enclosed), the final code appears bulky. I want to write a function to hide other divs whiles displaying the one I am interested in. This is the code I currently have:
var tableDivs = ['tableOPVDiv','tablePneumoDiv','tableRotaDiv'];
var selectedVaccine;
var selectedTableDiv;
function generateFactsheetFunction(){
// Selecting the vaccine chosen from the dropdown
var e = document.getElementById("selectVaccine");
selectedVaccine = e.options[e.selectedIndex].text;
console.log("selectedVaccine: ", selectedVaccine);
if (selectedVaccine=="Rotavirus Vaccine"){
selectedTableDiv='tableRotaDiv';
console.log("rotavirus selected");
hideOtherTables();
} else if (selectedVaccine=="Polio Vaccine"){
console.log("polio selected");
selectedTableDiv='tableOPVDiv';
hideOtherTables();
} else if (selectedVaccine=="Pneumococcal Vaccine"){
console.log("pneumo selected");
selectedTableDiv='tablePneumoDiv';
hideOtherTables();
}
}
function hideOtherTables(){
var testa = tableDivs.indexOf(selectedTableDiv);
console.log("tableDivs[testa]: ", tableDivs[testa]);
console.log("testa: ", testa);
testb = tableDivs[testa];
console.log("testb: ", testb);
document.getElementById(tableDivs[testa]).style.display="block";
/*var newTableDivs=tableDivs.splice(testa);*/
/*for (y=0;y<newTableDivs.length;y++){
document.getElementById(newTableDivs[y]).style.display="none";
}*/
}
The uncommented part works fine. In the commented part, I want to say that for all array elements other than selectedVaccine, I want the display to be:
document.getElementById(tableDivs[testa]).style.display="none";
I cannot splice the data because the selections are repititive (the selections are from a form). What is the way to set the visibility of tableDivs associated with other selections to be none.

Why should you change the display property of each and every division seperately? give a common class name to all the divisions and hide them all at once and then display only the required table.
$(".yourClass").hide();
document.getElementById(tableDivs[testa]).style.display="block";
You will have to use the jQuery Library too.
If you are not familiar with jQuery then use the for loop to hide all the tables first and then display only the required table.
for (y=0;y<TableDivs.length;y++){//you need not create newTableDivs
document.getElementById(TableDivs[y]).style.display="none";
}
document.getElementById(tableDivs[testa]).style.display="block";
i.e you just have to interchange the order of execution. ;)

Cannot read property 'style' of null this means that document.getElementById(tableDivs[y]) return null and can not find this element
try to write
document.getElementById("ElementId")

Related

How to get path of button located in table cells

I am working on one table, where I have created one button which I am using in different rows and tables based on some condition.
I have one scenario where I need to show the button to some specific users, I have implemented the condition however I am not able get the path of the button, I can hide the cell but in that case complete cell is removed from the table which is not looking good, please help me to get the path of the button, so that I can hide it, here is the code I am using:
totalrows = document.getElementById("DEVmyTable").rows.length;
for(i = 0;i<totalrows; i++){
if(actualusernamevalue == currentusernamevalue){
table.rows[i].cells[6].style.display = "";
}
if(actualusernamevalue != currentusernamevalue){
table.rows[i].cells[6].style.display = "none";
}
}
Here in Cells[6] my button is present which I am created dynamically like this:
row = document.getElementById("DEVFirstrow");
var w = row.insertCell(6);
w.innerHTML = '<button onclick="Releaseentry(this)"type="button"
id="release" class="btn btn-primary release">Release</button>';
I have not added the complete code here, but based on the ids I am using this code in different table and rows.
in this code I have hidden the cell, for hiding the button I am not able to get the path, and that is what I am looking for.
You actually style the cell based on table.rows[i].cells[6].style.display and not its content. You choose the 6th cell and style it.Another mistake you make is that you use id in the button while the button is used in multiple rows which makes the id useless as it should be unique.
What I would do is simply use the class of the buttons and then based on the checks you have decide what the button should do using jquery, so:
if(actualusernamevalue == currentusernamevalue){
$('.release').show();
}
if(actualusernamevalue != currentusernamevalue){
$('.release').hide();
}
If I understand well what you are trying to do at least. The simpler solution, the better solution!
EDIT: By the way, you should keep in mind that if someone wants to find the button when you play with the display property in both ways, they can always find it through the source code. If someone inspects the element and changes the CSS manually they will be able to see the button, so it's always important to have back end validation too for cases like this.
I think I have got my solution finally, Thanks #natan for your help.
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "none";
table.rows[i].cells[6].getElementsByTagName('button')[0].style.display = "";
I should have used this code.

Show div when click on a different div, and show a different div when clicked again

I currently have made a way so the user can add another text field to the form by pressing on a 'add_another' div, this uses basic JS so when the user presses on the div 'add_another' the div 'author_2' is toggled.
I would like to make it so that when the user presses on the 'add_another' div for a second time it shows 'author_3' div, and when they press 'add_another' again, it then shows 'author_4'. I have put all the CSS and HTML divs in place to support this, I am just trying to adapt my code so it shows one div after another, rather then toggling a single div.
Here is my JS:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('.author_2').toggle();
});
});
</script>
I have tried altering this code, however with no luck.
I haven't added my HTML as it is just 4 divs, 'author_1' 'author_2' ... 3...4
Thankyou for your help
There are two solutions to Your problem.
First one - use static code
It means the max author count is 4 and if user gets to 4, this is it.
If so - You need to store the number of authors already shown.
var authors_shown = 1;
$(document).ready(function() {
$('.add_another').on('click', function(){
authors_shown++;
if (!$('.author_'+authors_shown).is(":visible")) {
$('.author_'+authors_shown).toggle();
}
});
});
But there is also a second - more dynamic option.
What if user wants to input 10 or 20 authors? You don't want to pre render all that html code and hide it. You should clone the div and change its id or if the (HTML) code (for another author) is not too long, you can render it within JS code.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
If it's a form, then change names of input fields to array as author_firstname[]
Also You can store number of added authors in another hidden field (so you know how long to loop the form fields on the server side.
The second option is a bit more complex and longer, but way more dynamic.
You should make another div when clicked on add_another:
something like this:
<script>
$(document).ready(function() {
$('.add_another').on('click', function(){
$('<div><input type="text" name="name[]" /></div>').appendTo('.your_container');
});
});
</script>
as you see, input's name has [] which means you should treat with the inputs as an array.
let me know if you got any further questions
good luck.

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

cross browser issues jquery dropdown menu

Ok I made a site a while back and always had issues with the menu system is needed. Basically you click a location on a map, then it displays the list of sub locations in the dropdown menu to the right. These are always their they just chance to display based on the options class.
I have put the site at shiftera.co.uk so you can see it their.
The issue first.
1) IE - The list never filters out, it displays all results all the time regardless of class.
2) Chrome - The dropdown is sometimes squashed showing 1 result and hiding the others you need to use up/down arrows to change, sometimes it shows 3, sometimes 4.
3) Firefox - The list displays in 1 long row, not like a usual dropdown.
I think the issue is more of a css problem or multitude of css problems.
An example of the map link is
Scotland
The dropdown list although not seperated is generated from the database and appears as below
<option value='AB25 1UH' class="Scotland">Aberdeen</option><option value=' WA14 4DW' class="Northwest">Altrincham</option>
As you can see, some have the space before some don't. The dropdown has the id of apick and Im using css below to hide it on load.
#apick { display: none; }
Here is the javascript to display the correct items based on map click.
//<![CDATA[
$(document).ready(function(){
$('.areaselect').on('click', function(event){
$('#apick').css('display','inline');
var id = $(this).attr('id')
$('#apick option').not('.'+id).css('display','none');
$('.'+id).css('display','inline').first().attr('selected','selected');
event.preventDefault();
});
}); //]]>
This has been driving me mad for a long time now, it seem's if i fix 1 issue another 2-3 get created. So I figured i'd try here and see if any brightspark can narrow down my issue.
Updated removing windows load as per change to main website.
The simple answer is that you are setting the style to inline. An <option> tag should not be inline, or have any style like that. The inline style i causing the problems.
Instead add the <option> tags when you need them. Store all the values in a object to add/remove them.
By the way. Remove that window load thing.
Here is the javascript fix:
$(document).ready(function()
{
var options = $('#apick option');
var values = $.map(options, function(option)
{
return option;
});
$('.areaselect')
.on('click', function()
{
var apick = $('#apick').empty();
var id = $(this).attr('id');
var newValues = $.grep(values, function(n, i)
{
return $(n).hasClass(id);
});
apick.append(newValues).show().find('option:first').attr('selected','selected');
return false;
});
});

switching selections between two select menus

I'm trying to build some kind of currency converter and I have two select menus with the list of currencies.
I want to create a button that when clicked, it will switch the selection between the "from" select menu and the "to" select menu.
how do I implement it using the select menus I already have?
I believe you'r looking for a swap behavior.
http://jsfiddle.net/brentmn/D55Dm/
$(function(){
var $sel1 = $('#currency1');
var $sel2 = $('#currency2');
$('input[type=button]').click(function(){
var val1 = $sel1.val();
var val2 = $sel2.val();
$sel2.val(val1);
$sel1.val(val2);
//jqueryui
//$sel2.val(val1).trigger('change');
//$sel1.val(val2).trigger('change');
});
});
Something like this?
$("#button").on("click", function() {
var from = $("#from").val();
var to = $("#to").val();
$("#from").val(to);
$("#to").val(from);
});
I'd really do it with less code than that, but have done it like that for readability.
Assuming I've understood you correctly, you want a button that will swap the values of two select elements. If that's right, try something along these lines:
$("#someButton").click(function() {
var elemTo = $("#to"),
elemFrom = $("#from"),
toVal = elemTo.val();
elemTo.val(elemFrom.val());
elemFrom.val(toVal);
});
It simply gets references to the two select elements (assumed here to be #to and #from), gets the value of one of them, replaces the value of that one with the value of the other, and then replaces the value of the second with the stored value from the first.
Note that this assumes both select elements have the same option values. If an option is present in one select but not the other, it would not work.
Here's a working example.
If you dbl click on one item in 'From' section , it will get selected be appended to the 'To' section.
$("#selectFrom").dblclick(function(){
$selectTo.append($selectFrom.children(":selected"));
});
Which all functionalities you want??

Categories

Resources