Two select boxes with one function in Jquery - javascript

I have here two select boxes. The process is like this http://www.w3schools.com/ajax/ajax_database.asp. What I need to display only the value between the two select boxes. How I can do that in one function? Any help will appreciate.
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str=="") {
$txtHint.html('');
return;
}
$txtHint.load('ajax.php?q='+str)
}
</script>
<select name="customers" id="customers" onchange="showUser(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>

First, take the function that you're calling inside change(), and declare it separately. Then, call .change() on that function twice.
E.g.
$(document).ready(function() {
var myChangeFunction = function() {
var city = $(".city").val();
var customer = $("#customer").val();
if (city && customer) {
// do something only if both are set
}
};
$(".city").change(myChangeFunction);
$("#customer").change(myChangeFunction);
});

I think I understood what you need.
You need both selects to call the same function onchange.
That function will get some info, and load it. You need it to load it in different places regarding which was the select that changed.
If that's what you need, check this fiddle:
http://jsfiddle.net/hige/4878B/
Remember to uncomment the .load() line, and delete the console.log() one.
Hope it helps!

Related

How to always trigger function of <select> tag

I wrote a select tag (have default selected) and take the option value to trigger another js function:
var selectElement = document.getElementById("sel");
function somefunction() {
console.log(selectElement.value);
};
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>
However, if I keep the onchange event, it only triggers the function when I change the selection. I also want to trigger the function when page is loaded with the default selection that i have set (which is Yes in the above example).
Thanks.
Add an onload function to your body tag:
<body onLoad='somefunction()'>
What I would recommend is to build an independent function for calculating the selected index. Then I would manually map a variable to the <select> element, and attach an onchange() handler than calls this function, passing itself in as a parameter.
With this setup, you have both a function to calculate the selected value of any <select> element, and the target <select> element already mapped to a variable for easy access. You can then simply pass that variable into the function on page load:
/* Function to grab the selection, which takes a `<select>` element as a parameter */
function getSelectedIndexes(select) {
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
return i;
}
}
}
var select = document.getElementsByTagName("select")[0];
select.onchange = function(e) {
console.log(getSelectedIndexes(this)); // Selection on change
}
console.log(getSelectedIndexes(select)); // Default selection
<select>
<option disabled selected> Select
</option>
<option selected="selected" value='yes'> Yes
</option>
<option value='no'> No
</option>
<option value='all'> All
</option>
</select>
Hope this helps! :)
Why don't you call the function when the window is loaded? I guess that will solve
your problem.
window.onload = function() {
if (selectEl.value) // or use (selectEl.value == "yes)
somefunction()
};
var selectEl = document.getElementById("sel");
function somefunction() {
console.log(selectEl.value);
}
<select id="sel" onchange='somefunction()'>
<option selected="selected" value='yes'>Yes</option>
<option value='no'>No</option>
<option value='all'>All</option>
</select>

How do I attach an event to an array of select boxes?

I have an array of select boxes, with a class "taskcompleted". I want to be able to do something when a box is changed.
<select class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
I have used this javascript code
function initselects() {
var myselects = $('.taskcompleted');
myselects.each( function(){ // any select that changes.
console.log( $(this).val() );
}).change();
}
When the page loads, it is logging a change for each select box. I do not want this to happen. I want to only log a change after the page as has loaded.
You can use change() to attach the event to each select, like this:
function initselects() {
$('.taskcompleted').change(function() {
console.log($(this).val());
});
}
Something like this you mean? This will add change handlers to all selects with class taskcompleted
The problem you have it that you're adding .change() to the end which actually triggers the change you don't want to happen - so instead, just listen for it
function initselects() {
$('select.taskcompleted').on('change', function() {
// do something
});
}
If you don't want the logging at page load, then simply remove change() from the end.
In general you can use it like that
JavaScript:
var myselects = $('.taskcompleted');
myselects.change( function(){
console.log($(this).attr('name') + ': ' + $(this).val() );
});
HTML:
<select name="1stselectbox" class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<select name="2ndselectbox" class = "taskcompleted" >
<option value="Maybe">Maybe</option>
<option value="dontknow">I don't know</option>
</select>
So you set the change listener directly on the jQuery objects, no need to use a loop (each). The example above will even print which select box was selected (might be useful). E.g. the output will be when changing the first box to Yes: 1stselectbox: Yes
JSFiddle: https://jsfiddle.net/x8jwy92h/

javascript onchange running by itself [duplicate]

This question already has answers here:
onclick function runs automatically
(4 answers)
Closed 7 years ago.
I have a problem with a javascript function.
It runs by itself when the page loads even if it`s set to run .onchange
I have a select that looks like this:
<select name="make_brand" id="make_brand" class="form_tag dispB width_full">
<option value="" selected disabled>Please select</option>
<option value="1">Audi</option>
<option value="2">BMW</option>
<option value="3">Mercedes-Benz</option>
</select>
And my js looks like this:
// defining select fields
var brand = document.getElementById("make_brand");
// get values
function getSelectedValue(element, show_mark){
return element.options[element.selectedIndex].value;
}
// on select change
brand.onchange = getSelectedValue(brand, true);
When I refresh the page, the function runs automatically and I don`t know why. Can anyone help me with this?
I want the function to run on select change.
Your code is running your getSelectedValue function and then setting setting brand.onchange to it's return value. You can only set event handlers in that way if you do not need parameters.
You have two options for passing parameters to dom element events:
You can make an anonymous function like so:
brand.onchange = function(event){
return getSelectedValue(event.target, true);
}
Or you can add your event to your html element directly:
<select name="make_brand" onchange="getSelectedValue(this,true)" ...
this should do...
<html>
<head>
<script>
function init(){
var brand = document.getElementById("make_brand");
// on select change
brand.addEventListener("change", function(){getSelectedValue(brand, true)});
}
// get values
function getSelectedValue(element, show_mark){
return element.options[element.selectedIndex].value;
}
</script>
</head>
<body onLoad = "init()">
<select name="make_brand" id="make_brand" class="form_tag dispB width_full">
<option value="" selected disabled>Please select</option>
<option value="1">Audi</option>
<option value="2">BMW</option>
<option value="3">Mercedes-Benz</option>
</select>
</body>
</html>
you have to let the document load before adding a listener to an element in the document. Notice the body tag, I called my init() function within onLoad.
brand.onchange should be a function like this :
brand.onchange = function(event){
getSelectedValue(brand, true);
}

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

jquery not getting value from select statement on change

This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.
onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.
my html is:
<select onChange= "getDrop2()" id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
My Javascript is:
function getDrop2(){
var choice = $("#drop1").val()
alert(choice);
}
The output of the alert statement is just blank.
In jQuery, you're better off doing something like:
<select id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
With the following JavaScript:
$(function(){
$('#drop1').change(function() {
var choice = $(this).val();
alert(choice);
}
});
The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.
Although what others have selected is a better approach. My answer is just to tell you why your code is not working
Try this
var choice = $('#drop1 option:selected').val()
Instead of
var choice = $("#drop1").val()

Categories

Resources