Loading HTML files with dropdowns using jQuery - javascript

I am using jQuery .load to load different HTML files into my webpage using a dropdown menu. Each dropdown selection calls the corresponding file. My target div is <div id="targetPane"></div> to load the file. That works fine. I am looking to clean up the code so I dont have to write $('#f1').click(function(){$('#targetPane').load( 'includes/inc_1.html' );}); 50 or so times.
The naming convention is that the #f1 will call inc_1.html, #f2 will call inc_2.html and so on. Maybe a solution using a for loop or ('option:selected',this) ? Thanks
$(document).ready(function () {
$('#f1').click(function(){$('#targetPane').load( 'includes/inc_1.html' );});
$('#f2').click(function(){$('#targetPane').load( 'includes/inc_2.html' );});
..
..
..
$('#f50').click(function(){$('#targetPane').load( 'includes/inc_50.html' );});
});
HTML
<form name="courseCalc">
<select name="myCourses"
OnChange="location.href=courseCalc.myCourses.options[selectedIndex].value">
<option selected>Please Select...</option>
<option id="f1" value="#">Item 1</option>
...
<option id="f50" value="#">Item 1</option>
</select>
</form>

Firstly, note that when working with select elements you are best off using the change event of the parent select element instead of listening for click on the option. It's better practice, more widely supported in various browsers, and follows accessibility guidelines.
With regard to your question, the technique you're looking for is called 'Don't Repeat Yourself', or DRY for short. To achieve it in this case you can hook the change event handler and use get a reference to the select from the Event object passed to the handler. You can amend the HTML to store the URL in the value attribute and then provide it as the argument to load(), like this:
<form name="courseCalc">
<select name="myCourses" id="courses">
<option selected>Please Select...
<option value="includes/inc_1.html">Item 1</option>
<option value="includes/inc_2.html">Item 2</option>
<!-- ... -->
<option value="includes/inc_50.html">Item 50</option>
</select>
</form>
jQuery($ => {
$('#courses').on('change', e => {
$('#targetPane').load(e.target.value);
});
});
Note that I added an id to the select element to make it easier to retrieve the element in the example, but any selector would work.

Related

jQuery change selection and trigger change callback

I have a dialog with multiple tabs, the first tab has a list ("SELECT") when a selection is made from the list the number of tabs may change as a result of the callback attached to the list.
In my source I the list callback is attached with:
$("#listID").bind("change", function() {
//Do something
});
In code I want to change the list selection and trigger calling of the change callback. I've tried:
$("#listID").val(3); //3 is one of the valid option values
This didn't result in the change callback being called so I added:
$("#listID").change();
After the setting of the value, this doesn't work either, if I look at the list the high light has not moved.
I've searched online and what I've done should work but it doesn't. What haven't I done?
Here is the HTML:
<select id="listID" size="11">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select>
Should work fine doing $("#listID").val(3).change()
Note that bind() is deprecated and you should use on()
$("#listID").on("change", function() {
console.log(`Changed value to ${this.value}`)
});
$("#listID").val(3).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="listID">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
If it's not working there is something missing in question as to why
$("#listID").val(2).trigger('change'); //to trigger the change event with value 2

Redirecting page based on <select> value

I have a <select> tag on my site that when I change it submits the form and goes to the page in question where I can use the $_POST variable.
<form method='POST' action='myURL'>
<select onchange='this.form.submit();'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</form>
This is fine and works as intended but if someone is on the page and refreshes it I don't want to have to have the warning for resubmitting the form.
So what I was trying to do is remove the form element and have something like this and I can use $_GET instead of $_POST.
<select onchange='window.location.href="myURL?var=this.value";'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
However, this redirects to the page but the $_GET variable is literally this.value.
Is there another way of getting this to work or will I need to write an external piece of JS for this?
Note JS isn't my language, the snippets above are all being rendered via PHP
You've hardcoded the string - just do this instead:
<select onchange='window.location.href=("myURL?var=" + this.value);'>
I would suggest to you to avoid the use of inline-events as onchange and use the addEventListener() method instead to attach the change event.
So first give you select tag an identifier (id or class) then attach the event using this identifier like :
<select id="my-select">
Then in the JS part it could be attached like :
document.querySelector('#my-select').addEventListener('change', function(){
window.location.href = "myURL?var=" + this.value;
})
Or if you could use jQuery it will be :
$('#my-select').change(function(){
window.location.href = "myURL?var=" + $(this).val();
})

Showing alert dialog on dropdown select in jQuery

I'm trying to show an alert dialog on dropdown select in jQuery but it doesn't seem to be working. What am I doing wrong? My code is here: http://jsfiddle.net/AyCFt/6/
HTML
<select>
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>​
JS
$(document).ready(function() {
$("#projectmanager").click(function(){
alert("Hello");
});
$("#projectmanager 2").click(function(){
alert("Hello to you too!");
});
});
​
This way you can show a unique alert box for each projectmanager.
<select id='ddselect'>
<option selected="selected" >Please select your Login</option>
<option>--------------------------</option>
<option id="projectmanager">Project Manager</option>
<option id="projectmanager2">Project Manager 2</option>
</select>
$(document).ready(function() {
$("#ddselect").change(function(){
if($("#ddselect option:selected").attr("id") == "projectmanager"){
alert("Project manager 1 alert");
}
if($("#ddselect option:selected").attr("id") == "projectmanager2"){
alert("Project manager 2 alert");
}
});
});
An elegant and also flexible way of doing this: http://jsfiddle.net/AyCFt/13/
The jsFiddle just tackles the question asked (displaying the alerts). The code below shows that the code is much more flexible, but avoids the if/switch statements of other answers if they are not needed.
HTML: I added an id in the select element and custom attributesnamed data-alert containing the message for each option that needs to display an alert upon being selected. These attributes are valid in HTML5 and forward, but they work fine in earlier HTML versions also:
<select id="selectAlert">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager" data-alert="Hello">Project Manager</option>
<option id="#projectmanager2" data-alert="Hello to you too">Project Manager 2</option>ello
</select>
Javascript (version 1): If you just want the alerts and are a fan of brevity and clean code:
$(function() {
$("#selectAlert").change(function(){
var alertMsg = $(this).find(":selected").attr("data-alert");
if(alertMsg) alert(alertMsg);
});
});
Note that this solution does not force you display the text or the value of options. You are free to choose any alert message exactly as you wanted.
WHY DO THINGS THIS WAY? This kind of solution decouples logic from data. So if you are producing the select using server-side code (either as part of a dynamically generated page or through AJAX) you ideally do not want to have to produce your Javascript in the same way if you can avoid it. Whereas your code and the code in some other solutions puts the alert messages in the Javascript code, this solution puts them inside each option, in the HTML.
Javascript (version 2): If there are more things you need to do:
$(document).ready(function() {
$("#selectAlert").change(function(){
var $selected = $(this).find(":selected"); //faster than $("#selectAlert :selected") as it only searches among the options in the select and not the whole DOM like another answer's solution
//some code: you can do what you want with $selected here get it's value, its id, etc etc
var alertMsg = $selected.attr("data-alert")
if(alertMsg) alert(alertMsg);
//some more code here
});
});
PROBLEM WITH CODE POSTED IN THE QUESTION:
The problem with the code you posted was that you were using click on the options of the select element. As you discovered this event is not defined for the individual options.
A GENERAL POINT ABOUT UI EVENTS: In general, it is best to try to work with device-independent, more "semantic" events wherever possibly. In this case the event we are using is one that tells us that the value of the select has changed. It does not matter if the user did so using the mouse, the keyboard, or touch!!!
Try with the following code. It will work for you.
<select id='ddselect'>
<option selected="selected" >Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>
$(document).ready(function() {
$("#ddselect").change(function(){
alert("Hello");
});
});
Make the below change to html:
<select id="SelectOptions">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>​​​​​​​​​​
Make the below change to the javascript:
$(document).ready(function() {
$("#SelectOptions").change(function(){
alert($("#SelectOptions option:selected")[0].text);
});
});
This will display the selected option.
As stated above you can use onchange on the select element. to respond uniquely to each value you can use a switch statement like so:
http://jsfiddle.net/AyCFt/11/
This is but one way to do it (and depending on your final implementation, there's probably a better way to go about this).
Add value attributes to your markup so that the message is contained in the value:
<select id="changeMe">
<option selected="selected">Please select your Login</option>
<option disabled="disabled">--------------------------</option>
<option id="projectmanager" value="Hello">Project Manager</option>
<option id="projectmanager2" value="Hello to you too">Project Manager 2</option>
</select>​
Since option elements don't [often] receive .click() events, it's much better to add a .change() handler to the select element and go from there:
$(document).ready(function() {
$('select#changeMe').change(function(e) {
var self = $(this), //cache lookup
selected = self.children('option:selected'), //get the selected option
i = selected.index('select#changeMe option'), //grab the index, relative to all options
message = selected.val(); //get the message
if (i > 1) { //ignore "Please select" and "---"
alert(message);
}
});
});​
Updated fiddle: http://jsfiddle.net/AyCFt/12/
To customise the alert message, you would either need to run a 'switch' statement (or a switch-like series of 'if' statements) in the Javascript code, or encode the alert message into the HTML and access that (example here http://jsfiddle.net/AFguq/):
<select id="SelectOptions">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager" alertText="Hello">Project Manager</option>
<option id="#projectmanager2" alertText="Hello to you too">Project Manager 2</option>
</select>​
(javascript:)
$(document).ready(function() {
$("#SelectOptions").change(function(){
alert($("#SelectOptions option:selected").attr('alertText'));
});
});​

Make <select> options "click" automatically

Let's say I've got a drop down like this:
<div class="selector">
<select name="perPage">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="25">25</option>
</select>
</div>
I'm know PHP and Javascript (jQuery) so a solution in either would be just fine. But I've got a submit button underneath it, and instead of that, I was wondering if there's a way to click the drop down, pick your value, then have it send that automatically with OUT having to hit a submit?
You could use the 'onchange' element of the select:
<select name="dropdown" id="dropdown" onchange="this.form.submit()">
This only uses javascript without the need of loading the whole JQuery library - unless you use JQuery for other functions on the site.
You can listen to the change event using jQuery and submit the parent form automatically. Something like this:
$('.selector select[name=perPage]').on('change', function(e) {
$(e.currentTarget).closest('form').submit();
});
Assign an id to to select, e.g. selectID, then add jQuery of the form:
$('#selectID').change(function(){
this.form.submit()
});
$('select[name="perPage"]').on('change', submitForm);
where submitForm is a function that submits the form.

How do I select an option by class?

I tried using $('.className').show(); and $('.className').hide(); but it doesn't seem to work in IE. Is there another way to group options by class in a drop down list? I found this question but the answer is looking for the value "a" or "c".
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
How do I look for the actual class?
EDIT
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
I've never seen anyone try to call hide/show on option elements before, and I imagine IE just doesn't allow you to do that. The selection is probably matching just fine, but IE is not hiding the elements. The selection for removing would be the same as for calling show hide...
$('.className').remove();
or
$('option.className').remove();
or
$('#theSelect option.className').remove();
You can add the disabled attribute to the options you don't want to use:
http://jsfiddle.net/sadmicrowave/Fnvqb/
$('select[class~="cactus"]')
$('option[class~="cactus"]')
javascript:(function(){
var out = "hi\n";
out += $('*[class~="cactus"]').html2string() ;
alert( out );
})()
For future reference, instead of describing in words the html ... show actual html
This demonstration code shows one way of how you can achieve option filtering... it would need modification to determine which candidate items are removed as I just hardcoded for purpose of demonstration, but it shows you what you need to consider - when you remove the items, you need to consider the ordering by which they're added back. The easiest way to bypass this problem is to keep a copy of the original list and then when you unfilter, just remove the remaining items, replacing them with what was originally there - otherwise you have to worry about keeping sort data.
So here's my drop down definition:
<select id="mySelector">
<option class="group1">Item 1</option>
<option class="group2">Item 2</option>
<option class="group1">Item 3</option>
<option class="group2">Item 4</option>
<option class="group1">Item 5</option>
</select>
<input type="button" id="removeItems" value="Remove candidate items" />
<input type="button" id="addItems" value="Add them back" />
And the jquery to filter/restore the items:
$(function () {
var originalOptionData;
$("#removeItems").bind('click', function () {
/* store original copy for rollback */
originalOptionData = $("#mySelector option");
$("#mySelector option.group2").remove();
});
$("#addItems").bind('click', function () {
var selector = $("#mySelector");
selector.children().remove();
selector.append(originalOptionData);
});
});
This could be turned into a select filter jquery plugin relatively simply I suppose, but I didn't go that far...

Categories