value from dropdown show/hides div and keeps its state - javascript

im relatively new to ROR, and would like some help with the following code.
I would like to show a div (it's called demographics) when a specific selection ("Customers") is made form a dropdown. If an option other than "Customers" is selected from the dropdown, I would like that the demographicsv div remain hidden.
At present, my code is partially working. It shows and hides the div; however, when I save the page and come back to it, the div is hidden, even if "Customers" is selected in the dropdown. This might be because the default setting is: display:none.
Is there a way to make sure that the field is displayed on page load when the proper selection has been made?? And I suppose a way to make the opposite true too--> a div with display:block; remains hidden if the field from the dropdown does not match the required field.
Any help would be extremely appreciated. Thank you and I sincerely appreciate your time:
my code (HAML):
= f.select :who, WHO, {}, :onChange => "showDemographics(this)", :prompt => true
#demographics{:style => "display:none;"}
%p.information
please fill out the following demographics.
%div{:class => "label_leftalign field"}
= f.label :age, "Age"
= f.select :age, AGES, :prompt => true
%div{:class => "label_leftalign field"}
= f.label :race,
= f.select :race, RACES, :prompt => true
Javascript
function showDemographics(obj)
{
if(obj[obj.selectedIndex].value == 'Customer')
{
document.getElementById('demographics').style.display = 'block';
}
else
{
document.getElementById('demographics').style.display = 'none';
}
}
EDIT::
OK, So the key issue is that on page reload a div remains hidden even if the correct value is in the dropdown box. I suppose that this can be solved by one of two ways 1. running some sort of validation on everytime the page is loaded or 2. cookies.
Unfortunately, I'm not very well versed in Javascript or jQuery... and I've never implemented cookies on a site, and would prefer to avoid using them if possible.
Could anyone help me write a script that validates the presence of Customer in the dropdown and shows/hides a div accordingly? Thank you, and thanks to Carlos Pardilla and M. Cypher for their help thus far.

You have tagged the question with jQuery although you're not using it in the code, but I'll just assume it's fine if I give you some jQuery code:
$(function() {
$('#who').change(function() {
if ($(this).val() == 'Customer') {
$('demographics').show();
} else {
$('demographics').hide();
}
}).change();
}
Note that you need to give the select an id (in this case who) for it to work.

I guess you could use a conditional statement to be checked during page load. You could establish the visibility (or lack thereof) of the div depending on the value ("Customers") of the option:selected element within your select object (the dropdown). Maybe via a script on the head of the document (provided it is a short script). Also, by doing this you wouldn't need to set the display property from the start. It would fire depending on the selected condition during page load.
This could be done to get the opposite result as well, as you said.
Hope it'll help!

The answers above where correct in their own way... the link below shows the actual code that is required for the conditional statement on page load:
show hidden divs on refresh

Related

Setting default option and disabling alert

I've been trying for some time now to get this to work. I don't have much experience with jquery or javascript. I want to set a default option that is selected from the drop down options when the button is pressed. I hope this will also prevent the alert(not sure if that's correct) from appearing. I have add the following code to the "code injection" part of squarespace, which seems to work fine. (Edited, I have removed the code as recommend)
I'm using the Brine template. Here's a link to the website https://www.metastudio35.com/private-photography-services/event-collection the password is "Google360".
<squarespace:script src="plugin.js" combo="true"?>
<squarespace:script src="site.js" combo="true"?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I then added the code below in the page I needed to redirect the button. Which also works, but without the "$("#Additional Photos").val("0");" and "$( ".sqs-widgets-confirmation-content clear" ).dialog( "close" )" lines.
<script>
$(document).ready(function(){
$("#Additional Photos").val("0");
$( ".sqs-widgets-confirmation-content clear" ).dialog( "close" )
$(".sqs-add-to-cart-button").click(function(){
window.location = '/booking/';
});
});
</script>
This is a screenshot of the dialog box I want to remove/disable.
dialog box pop up screenshot
If someone could point me in the right direction or tell me what I'm doing wrong it would be greatly apprenticed.
Thank you for your help.
I checked your website and it seems like jQuery is not used by your template, and instead of including jQuery just for this simple function, I've written the below code in vanilla JS instead.
function setValue() {
var dropdown = document.querySelectorAll('[data-variant-option-name="Additional Photos"]')[0];
dropdown.value = '0';
Y.one('#'+dropdown.id).simulate('change');
}
window.onload = setValue;
If you're interested in figuring out why your code wasn't working, here's the explanation :
$('#Additional Photos').val("0")
This line of code is setting the element that has an ID of "Additional Photos" with a value of "0".
Your "Additional Photos" select box does not have an ID of "Additional Photos", instead - it has a randomly generated ID that re-generates each time the page is refreshed.
So the reason that your code isn't working is because you're simply targeting the wrong element :)
var dropdown = document.querySelectorAll('[data-variant-option-name="Additional Photos"]')[0];
Due to the fact that the ID of the select box is not constant, we are targeting the select box by the 'data-variant-option-name' attribute instead. I figured out this constant attribute simply by inspecting the selectbox on the ChromDev tools.
dropdown.value = '0';
Y.one('#'+dropdown.id).simulate('change');
The other thing to consider is the fact that your template is using YUI to handle the select box. This means that we need to manually trigger the 'change' event in order for the UI to update. As you can see from the code above, the first line is setting the value of the select box, while the second is telling YUI to simulate the 'change' event, and thus - updating the UI.
Hope this helps !

jQuery For Loop Image Check and Display

Good afternoon Stack Overflow,
I'm inexperienced when it comes to coding in general and I've been having a problem that's doing my head in!
If you'll allow me to set the scene...
The section of the project I am currently working on involves a user picking items from a warehouse in order to fulfil a shipment and in some cases they have to pick the same item from various locations, when that needs to be done, the small "!" type icon appears next to the item.
The user then can click on the icon and choose which locations they will be retrieving the stock from, they then press confirm on the modal and when it closes it sets the text back to blue and hides the icon.
The part I am having trouble with is that once all the locations have been established, the order needs to be processed and this requires a button to be clicked on, which I only want to appear once all the "!" icons are hidden.
I know there are alot of questions based on for loops and images checks and believe me when I say I've tried hard to figure this out myself and I've tried different approaches:
ShowProcess = false
for (i = 0; i<Picker; i++) {
if ($('#MultiLocIcon'+i).is(':visible')){
ShowProcess = true
}
if (ShowProcess == true) {
$('#ProcessConfirm').show()
};
};
This obviously wouldn't work because its setting the first variable in the list to "true" and will always read it as true, therefore always showing the image, even if the "!" icon still exists in other rows.
I also tried using .each() to test each rows text color of a specific but also had no luck:
var table = $('#RequestedItemsTable');
table.find('tbody > tr').each(function(){
if $('#Desc').css('color') == '#0000FF'){
//do something
I feel like my experience is letting me down as I still have a lot to learn and have a suspicious feeling that the solution is going to be really easy, but then again, its only easy if you know how.
If anyone could take the time to help me with this problem or offer me any advice, I'd be really grateful.
Here is a section of my code which might be useful:
Modal "Confirm" button:
//CONFIRM Button which will submit final picks.
'Confirm': function() {
//Reset the length loop
length = undefined;
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
//Change text colour back to blue to have visual confirmation that item is ready for picking
$('#Desc'+id).css('color', '#0000FF');
$('#QtyReq'+id).css('color', '#0000FF');
$('#QtyinStock'+id).css('color', '#0000FF');
$(this).dialog('close');
The "!" Icon:
<td id= "MultiLocIcon<?=$i;?>"><?if($row->Count_Location > 1)
{?><img src="<?=base_url();?>public/css/images/error.png" alt="LocPick" title="Multiple Locations" style="cursor: pointer;" id= "icon<?=$i;?>" onClick="$.LocPick(<?=$i;?>);"/><?}?></td>
Basically just need to know how my image can show once the loop checks and knows that the "!" icon is hidden from every possible row.
Thank you for your patience.
You'll need to add a second check in your modal logic, perhaps after your .hide():
//Remove "Multiple Location" icon from the row.
$('#icon'+id).hide();
$('img[id^=icon]:visible').length || $('#ProcessConfirm').show();
What this does is combines the :visible pseudo-selector and a regex selector for all img tags with id starting with "icon". This assumes you won't have any other unrelated image tags with an id like "icon*". If the length is 0, it will go ahead and show the #ProcessConfirm element.
simplest solution I would give is to add a class warning to all the table column which has warning icon & then check for visibility of the same.
if($('.warning:visible').length === 0){
//all warning icons are hidden
}
What I would do is based off your HTML, select all the alert icons, and do a :visible psuedo selector on it. This will return all the visible alert icons, if there are none in the array, you know none of them are visible. You will need to identify them with a class, such as .alert:
if( $(".alert:visible").length === 0 ){
// Do your code in here for no visible alert icons!
}
When user clicks confirm on modal you should run a check on how many icons are still visible, and if the amount is 0 then show the button, like this:
// This searchs for every <td> with an id that contains '#MultiLocIcon'
// Then checks if the amount of those which are visible is 0 and do something
if ( $('td[id*=MultiLocIcon]').not(':visible').length === 0 ) {
$('#ProcessConfirm').show()
}

jQuery: toggling attribute within a toggleClass function

I'm trying to add an attribute to a searchfield only when it is visible, so I have the following code to a) hide the search form initially, b) toggle the visibility and c) add or remove the attribute "autofocus" to the form's input when the form is given the class "focus" (e.g being visible). The code for a) and b) works as it should, c) is my imagined take on how the addAttr() thing should be, but I don't really know Javascript so obviously it's not working. The question is: How do I make it work?
$("#searchwdgt").hide();
$(function() {
$('#show_search').click(function() {
$('#show_search').toggleClass('active');
$('#searchwdgt').toggleClass('focus').slideToggle(400);
if($('#searchwdgt.focus')) {
$('#searchwdgt input').addAttr('autofocus');
} else {
$('#searchwdgt input').removeAttr('autofocus');
}
return false;
});
});
The basic construct is simple. #show_search is an anchor that the user clicks to get the search form (#searchwdgt). To minimize the number of user clicks it would be nice if the attribute "autofocus" could be added to the input (has class "searchfield", is type "search", just for clarification) when the form becomes visible, but for UX purposes it can't be in place always (this messes with tab browsing since the form is hidden initially). So, any constructive pointers that can help solve the issue are most welcome. Thanks.
the function should be
.attr('autofocus','autofocus')
instead of
.addAttr('autofocus');
The reason it isn't working is that each attribute needs to have a value, even if it's null

jQuery styling function in loaded ajax content?

I'm loading some div content using a navigation and i've got most of the content working properly. However I'm now trying to set up:
http://www.bulgaria-web-developers.com/projects/javascript/selectbox/
On a select dropdown, however the styling is called using the following:
$(function () {
$("#select").selectbox();
});
And I can't see how I can I can apply:
$(document).on('mousedown', '.nav-link', function() {
To it for when it first appears? Any advice much appreciated, cheers.
UPDATE
Nevermind, i've done it.
SECOND UPDATE
Ok i've just found 2 problems. Firstly, I made it show by using:
if (href == 'requestedpage.php') {
$(function () {
$("#select").selectbox();
});
};
And when the page loads the first time, the selectbox is styled properly, however if you go to another page and then go back, it doesn't apply the style second time around?
The other problem i've got is that when you click on the options, the dropdown makes your selection, but all of the options in the select list remain in view.
HTML code is:
<select id="selectlist" name="selectlist" onchange="updatevariable(this.value)" tabindex="1">
<option value="">-- Select Quantity --</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
Sorted problem 2 by removing onchange event!
Thanks in advance to anyone who can help me out.
If it's not applying the styling when you navigate back, it might be as simple as setting a flag in your callback.
One way to do this is to send a flag value to a hidden input field which will post to your server on page-submit. This means when you navigate back, you can check if the flag is there, if it is, apply the styling.
Alternatively, if you are building this application for browsers which support HTML5, you can save to the sessionStorage in your AJAX callback.
So, where you're checking the href, add this:
if (href == 'userarea-page1.php') {
$(function() {
$("#select").selectbox();
sessionStorage.selectFlag = "true";
});
};
Then, above your $("a.nav-link").click event (in your document.ready) you can check if this is has been set. If it has, apply the styling.
$(document).ready(function() {
if (sessionStorage.selectFlag == "true") {
$("#select").selectbox();
}
$("a.nav-link").click(
...
);
);
This will take care of maintaining the styling state between pages. Just make sure you clear the flag if you ever want to remove the styling, otherwise it'll be applied forever.
I'm not sure why you're setting the styling via javascript if you want it on page load, but if that is the way you're doing things try this may help:
$(document).ready(function() {
$("#select").selectbox();
);

Javascript, Jquery, Cross browser issues, Frustration

I am a predominantly PHP developer. I realize in this day and age specialization in one scripting language doesn't cut it, but the fact remains that my skills at JavaScript and jQuery are pretty green. I am a novice at best. I can create my own code but Cross Browser compatibility remains a huge issue with my work in JavaScript.
Anyway, I have a script that filters products according to categories/subcategories. This is how it works: you select a category and the javascript in the background does its thing to filter the subcategories so that the options displayed are the ones pertaining to the parent category- a combination of these two filters the product line.
Here is my code:
function scategories(){
//get the category option value from the category drop down bar
var cat = (document.getElementById('categories').value);
//get all the options from the subcategory drop down bar
var subcat = document.getElementsByClassName('subcategories');
var n=0;
//if the category bar option is set to 0 display everything
if(Number(cat)==0){
Show();
}
//filter the subcategories
while(subcat.item(n)){
//if there is no match b/w the subcategories option and the categories id FILTER
if(Number((subcat.item(n).value).split('|')[1]) != Number(cat) && Number(subcat.item(n).value) != 0){
document.getElementsByClassName('subcategories')
.item(n)
.style
.display="none";
}else{
//else display the subcategory
document.getElementsByClassName('subcategories')
.item(n)
.style
.display="list-item";
}
n++;
}
}
This code is pretty self explanatory I would say. I also have a shiftfocus function that shifts the focus from the current option selected in the subcategory to the default one which is 'none' whenever a new category is picked. This basically resets the subcategory.. here's the code:
function shiftfocus(){
document.getElementsByClassName('subcategories')
.item(0)
.removeAttribute("selected");
document.getElementsByClassName('subcategories')
.item(0)
.setAttribute("selected","selected");
}
Shiftfocus is called onChange and scategories is called onClick.
Problem 1:
1) Firefox: Shiftfocus doesn't shift the focus to the default option even though I can see it adds the 'selected' attribute.
2) Safari: Does not work at all.
EDIT: Problem 2 was the product of a careless mistake. I left open an anchor tag which was
creating havoc in IE. Should have double checked before bothering you
guys. Sorry. Problem 1 still persists.
Problem 2:
I understand none of us developers particularly like internet explorer. But I am willing to believe I have made a mistake here. I have some jQuery that fetches data from a script in another file via the native POST function and appends it to a table with the id "content". This works fine on every browser, except IE. If I try going back to IE 7,8 compatibility mode the results are a little better (the data shows up broken in pieces though) and in IE9 compatibility mode nothing is appended at all! Here's the code:
$.post("bagcontents.php", {
"Bid": $(this).attr('bid')
},
function(data){
$("#content").empty().append(data);
roundNumber();
$('#processorder_hidden').attr('value',currentBid);
});
//append here
<div id="contents" style="overflow:auto;height:345px;padding-right:5px;">
<form name="bag_contents" id="bag_contents" method="post" action="<?php _page ;?>">
<table id="content">
</table>
<input type="hidden" id="bag_contents_hidden" name="bag_contents_hidden" value="1" />
</form>
</div>
Any help will be appreciated. I tried outputting the fetched results with alert, alert(data), and the script is fetching everything just fine. Its the just the append part that fails :|
Here are some suggestions and hope you find them somewhat useful.
Problem: 1
Instead of having the shiftfocus() set the to a specific value, have you tried using .val('') just to clear it out. I can imagine that this will default to the first option.
Problem: 2
This will be hard to debug without knowing what data is coming back from the server. Might be bad formatting or some syntax error on the rendered output.

Categories

Resources