Show hide select list depending on other select list value - javascript

The following code show one (of many hidden) child select list depending on the value of the parent select list. The script check if any value is selected (in the parent select list) and if so show the corresponding child select list. But if the user select a value for the parent select list, post the form, get a message that the child select list miss input and (most likely) presses back button in the browser the parent select list still has a value (I guess browser default) and the child select list is hidden which will most likely confuse the user.
How can this be solved?
Javascript:
$('#parent-list').live("change",function() {
var value = $(this).find('option:selected').val();
$("#child-list-"+value).slideDown(200).siblings().hide();
return false;
});
HTML:
<select id="parent-list" name="parent">
<option value="1">1</option>
...
</select>
<select id="child-list-1 style="display:hidden">
<option value="a">a</option>
</select>
<select id="child-list-2 style...

I typically select an appropriate option on every page load, either through the code generating the HTML or in the JavaScript when the document is ready.

I think this is a common problem, and as far as I know there is no perfect solution.
You need to find some way to check whether the page is in an invalid state, such as a refresh timer (setInterval) that can check any dependencies and re-render if necessary.
If the user presses the back button after a POST he will get a warning (at least in some browsers). Though you can not trust users to realize the issue...
EDIT: Also, why is the user redirected to another page for the error messages? Can you instead redirect him back to the form if an error occurs, or preferably perform the validations client side before form submission?

Related

onchange() event of dropdownlist missing after disabled

I have an ASP.NET MVC project at work. Browser: Internet Explorer (forget what version), but my work machine is 32bit Windows 7.
In one of the view page, I have a dropdownlist. If there is any change, it will populate a text box with certain value. Here is the code (translated to HTML): Please note the drop down list is in a form
<form>
<select id="searchType" name="searchType" onchange="FillMyTextBox()">
<option value="1" selected>A</option>
<option value="2">B</option>
...
</select>
</form>
At the top of page, I have a button called 'Commit'. Once this button is clicked, all fields are disabled and form is submitted. $('input, select').attr('disabled', 'true') The 'Commit' button will be gone, and another button 'Back' appears. This 'Back' button, if clicked, will set all fields editable and form is submitted. $('input, select').removeAttr('disabled') (I guess you are aware of, these two sections of code use jQuery.)
However, once the 'Commit' button is pressed, select has attribute disabled and form is submitted. Once the form / page comes back, I find out the onchange() function is missing in the dropdownlist. Why? I use document.getElementById('searchType).hasAttribute('onchange') and it returns false (when I am in Console tab of Internet Explorer developer tool).
Why the disabled attribute remove the onchange() event of a dropdownlist? Is this a design flaw? I mean if I have many controls on the page, if I disable these controls, but somehow later on enable them back (say user review what has entered, but find out need to re-enter some fields), then I have to re-associate each with its own event, it seems rather inefficient.
[Edit] Stress that drop down list is inside a form and each button will cause the form to be submitted [/Edit]
Try using $('input, select').prop('disabled', false) to see if it works.
Or in other way this page may help. According to the answer assigning attribute uses $("input").attr('disabled','disabled') and removing by $("input").removeAttr('disabled');

What event to handle choose option from <select>?

I have an select with options which are loaded by ajax. After that user chooses option and additional data is pulled from ajax.
Of course at least one these options is selected as soon as select is filled with options so when I listen for change of this option:
$('article select.fetchedPosts').on('change', function () {
//do stuff and things
})
and user wants to fetch data for first (by default already selected) option the event is not firing because nothing has changed...
So is there any event in JS which would fire everytime user chose something from select, using keyboard or mouse?
You can do default instead of Option 1 Which option as "Select Option", and the user will have to replace the selection.
<select>
<option>select option...</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
change should be the correct event. According to MDN docs:
When the user commits the change explicitly (e.g. by selecting a value from a 's dropdown with a mouse click, by selecting a date from a date picker for [...]
There's actually an example select at the end of the page, where you can experiment clicking options or selecting with your keyboard, and each time it fires the event.
It may also change depending on your browser:
Different browsers do not always agree whether a change event should be fired for certain types of interaction. For example, keyboard navigation in elements never fires a change event in Gecko until the user hits Enter or switches the focus away from the

How to change selected attribute via javascript

I have an issue that I'm trying to solve. Need some advice to the right direction:
With Prestashop when creating combinations, you have a dropdwon-list on product page where customer can choose the combination from. Here within the product.tpl file I have created some extra button to get customers attention for a certain combination. Now I would like this combination beeing automatically selected and activated when user clicks on that button. I have inputted some javascript code within the product.tpl file which is also hiding some other elements when button is clicked. I just dont get it to work that a certain attribute option is selected on mouseclick. Someone may have some clue to solve this??
This is the select option list of the attributes within product page. For example I want on button click choose option "Large" and beeing activated within product page via onclick function with help of jquery/javascript within the template. How to achieve this?
<select id="group_4" class="attribute_select selectBox" onchange="findCombination();getProductAttribute();$('#wrapResetImages').show('slow');;" name="group_4" style="display: none;">
<option title="Small" selected="selected" value="21">Small</option>
<option title="Medium" value="41">Medium</option>
<option title="Large" value="40">Large</option>
<option title="Extralarge" value="25">Extralarge</option>
I have tried with this but it doesn't work:
$('#group_4 option[value='58']').attr('selected', 'selected').change();
Your quotes are wrong, looking at the console you would get the error Uncaught SyntaxError: Unexpected number
$('#group_4 option[value='58']').attr('selected', 'selected').change();
^ ^
should be
$('#group_4 option[value="58"]').attr('selected', 'selected').change();
To change the selected option, you can simply change the value of the select element using plain JS:
document.getElementById('group_4').value = 58;
You'd still need to trigger the change event after that, though.
See a simple example here: http://jsfiddle.net/BgBGL/1/ (uses alert as onchange callback)

Variable values on event tracking on a dynamic button with dropdown form

I am wanting to track the option chosen in 2 dropdown lists within a form. Below I have placed an example of the HTML that controls the form. The page the form is on is a dynamic secure page. After filling out one form, it changes to another without the URL changing.
I read on stackoverflow you can't use onClick on option fields. So I am wondering how I would set up event tracking in my scenario.
List 1
<div>
<p>What is your favorite fruit?</p>
<select id="list1">
<option value="a">apple</option>
<option value="b">banana</option>
<option value="c">cherry</option>
</select>
</div>
<a href="#"> <!-- Click here first to see the next dropdown menu, URL won't change -->
List 2
<div>
<p>What is your 2nd favorite fruit?</p>
<select id="list2">
<option value="a">apple</option>
<option value="b">banana</option>
<option value="c">cherry</option>
</select>
</div>
<a href="#"> <!-- This is the second time the same button is clicked. -->
If I could I would add each option tag with an onClick, but can't. Learned that on stackoverflow. So the disguised as a button is all I have. I just don't know how to post the dynamic selections to Google.
<a onClick="_gaq.push(['_trackEvent', 'listId', 'optionValue']);"
Since I click twice on the dynamic tag that is a button, how can I grab the value and the select ID each time? How do I post to google a variable based on ID for the list and the value for the option.
Is setting up in the dynamically used a tag, a smart way of doing the event tracking. Is there a cleaner way of setting up event tracking on my site for this form?
Presumably (since the form changes after selection) there is a javascript callback that does the changing. So you would place you analytics tracking call into that callback and read the selected value before the form changes. This requires control over the js code.
If the form is changed via an ajax call you might want to look if the setup of your page allows you to hook into the ajax success event. Jquery has global ajax event handlers, in prototype.js the same thing is called ajax responders and I'm sure other frameworks have something similar.
Another, and possibly the easiest way is to attach the onclick event to the link that changes the form and write a function that selects the value for the selected option.
Using jquery it could look like this:
$('#list1').find(":selected").value();
In plain javascript it should look like this (untested):
var list = document.getElementById("list1");
var selection = list.options[list.selectedIndex].value;
So your complete callback would look something like:
function getSelection(element) {
var list = document.getElementById(element);
var selection = list.options[list.selectedIndex].value;
_gaq.push(['_trackEvent', element , selection);
}
You'd need to attach this to the onclick event of the link and pass the id of the combobox as parameter.

Multiple groups of dropdowns

In jQuery, how to get multiple dropdowns for each group of handset, for example:
Customer can select more than 1 handset to make an order. Firstly customer will need to select a number of handset from a dropdown (1 to 15).
If they have selected number 5 from a dropdown then 5 groups of dropdrowns should appear like this:
Group One:
Select Phone [Dropdown / load entries via ajax]
Select Contract Length [Dropdown / load entries via ajax]
Select Contract Plan [Dropdown / load entries via ajax]
Select Additional Addon [Dropdown / load entries via ajax]
Group Two:
Same dropdowns as above
Other question is, if there an error (validation from PHP) for not filling the form properly - it will redirect back same page but the dropdowns will need to be reselected again. How to make that to work also?
Pretty sure you will have to bring some variable indicating the failure of form completion like into a session or some hidden element in html and then on document load - check for that variable and manually invoke those drop downs.
OR
Do not allow to click the submit button and check the validation in javascript. However it won't be that secure but it would save hassle for both you and the user. I myself would prefer form being checked before clicking submit just to wait a few seconds until the page is reloaded and I face the fact I chose/wrote something wrong.
OR
Validate automatically with xmlhttprequest or something similarly working so on submit click, js accesses php file, validates, returns the result and allows submission of data. Won't be super secure but... You can recheck that with the same php file again (will be caught if someone tried illegitimately pass some data not through form and xmlhttprequest failed to catch it). Would be safest and nicest way for the user.
Assuming this markup:
<select id="qty">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="placeholder"></div>
Use this JavaScript:
$('#qty').change(function() {
var qty = $('#qty').val() * 1;
$('#placeholder').html(''); //Clear existing.
for (var i = 0; i < qty; i++)
{
$('#placeholder').append(
'<select id="phone_' + i + '"></select>');
}
});
In your PHP script you'll need to check each possible field name - potentially taxing, probably better to composite these into a hidden field before submitting.
And it looks like #AndriusNaruševičius has answered the other half of your question.

Categories