How to get second combobox value after first one changed (jquery) - javascript

I have 2 comboboxes, first for Province and second for city/town.
I just wanna get the value of my second combobox (city/town) after first combobox changed and second combobox will change with ajax after user chose first the combobox.
Here is my code, but the problem is that the alert shows up twice!
jQuery('#billing_state').on('change', function() {
jQuery('#billing_city').on('change', function() {
var state = jQuery(this).val();
alert(state);
});
});

Why you made an imbrication of event ? just use change on the first combo .
Here is an example :
state = {"1":["Rome","Milan","Parma"],"2":["Paris","Lile","Nice"],"3":["Algiers","Jijel","Bejaia"],"4":["London","Manchester"]}
$(document).ready(function(){
//this if you want that changing province this alert country value
$("#billing_state").on("change",function(e){
$("#billing_town").children().remove();
var city =state[$(this).val()];
if(!city) return;
$("#billing_town").append('<option value="">- Select -</option>')
for(i=0; i< city.length;i++) {
//console.log(city[i]);
$("#billing_town").append('<option value="'+city[i]+'">'+city[i]+'</option>');
}
});
// when changing country this alert country value itself
$("#billing_town").on("change",function(e){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Province :
<select id="billing_state">
<option value="">- select -</option>
<option value="1">Italy</option>
<option value="2">France</option>
<option value="3">Algeria</option>
<option value="4">UK</option>
</select>
<br><br>
Country :
<select id="billing_town">
</select>

is this what you want. try with demo below
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
<label>Province</label>
<select id="province">
<option>california</option>
<option>austin</option>
<option>texas</option>
<option>colombo</option>
</select>
<hr>
<label>city</label>
<select id="city">
<option>colombo</option>
<option>canberra</option>
<option>silicon valley</option>
<option>ottawa</option>
</select>
</body>
<script type="text/javascript">
$("#province").on('change',function(){// in this line identify if there is any changes to first select box
var thevalue = $("#city").val(); // if there is any changes to first selection box, then at that time get the value of second selection box.
alert(thevalue); // to check the value of secod check box at the time chage put an alert.
});
</script>
</html>
or else if your want to show values according to user selection of first select box value, you can do it like this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
<label>Province</label>
<select id="province">
<option>california</option>
<option>austin</option>
<option>ottawa</option>
<option>western</option>
</select>
<hr>
<label>City</label>
<select id="city">
<option>--select--</option>
</select>
</body>
<script type="text/javascript">
$("#province").on('change',function(){// in this line identify if there is any changes to first select box
var thevalue = $(this).val(); // if there is any changes to first selection box, then at that time get the
$("#city").text("");
//display values according to the first value
if (thevalue == "california")
{
var cities = ["sillicon valley","st pauls","new york"];
for(var i=0;i<cities.length;i++)
{
var createoption = $('<option>'+cities[i]+'</option>');
$("#city").append(createoption);
}
}
else if(thevalue="austin")
{
var cities = ["mirage","manhatten","las vegas"];
for(var i=0;i<cities.length;i++)
{
var createoption = $('<option>'+cities[i]+'</option>');
$("#city").append(createoption);
}
}
else
{
//like above you can add relevent values.
}
});
</script>
</html>

Related

onchange event show all text values of target element, why?

Consider this:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
$("select").change(function(){
var val = $(this).val();
var text = $(this).text();
// That's fine
alert(val);
// But it's not. It alerts both Value 1 and Value 2
alert(text);
});
});
</script>
</head>
<body>
<select>
<option value="val_1">Value 1</option>
<option value="val_2">Value 2</option>
</select>
</body>
</html>
When onchange event occurs, then it alerts the right value of target option element (val_1 or val_2). That's fine.
But the problem with options's text. That should alert either Value 1 or Value 2, but not both! So what's the problem? Why it alerts both values, when only one target option element is processed?
$(function(){
$("select").change(function(){
var val = $(this).val();
var text = $(this).text();
// That's fine
alert(val);
// But it's not. It alerts both Value 1 and Value 2
alert(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select>
<option value="val_1">Value 1</option>
<option value="val_2">Value 2</option>
</select>
</body>
</html>
In your change event, this refers to the <select> element, not the selected <option>, therefore calling .text() on a select, will show all options.
To get the selected option text:
var text = $(this).find("option:selected").text();
$(function(){
$("select").change(function(){
var val = $(this).val();
var text = $(this).find("option:selected").text();
// That's fine
alert(val);
// But it's not. It alerts both Value 1 and Value 2
alert(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select>
<option value="val_1">Value 1</option>
<option value="val_2">Value 2</option>
</select>
</body>
</html>

How can I have multiple condition in 1 if statement

I'm trying to hide a button until both select boxes have an item select.
<select id="comType">
<option>-- Select --</option>
<option>Call</option>
<option>Fax</option>
<option>Email</option>
</select>
<select id="comDirection">
<option>-- Select --</option>
<option>Incoming</option>
<option>Outgoing</option>
</select>
Next
What I'm currently using, but I know is not right.
<script>
$(document).ajaxSuccess(function () {
if ($("#comType").change()) || ($("#comDirection").change()))
{ $("#button_that_displays_only_when_both_selects_have_input").show()}
});
</script>
It would be an added bonus if this could ensure actual selection, as in, not allow the first select option to count as they are just placeholders....
Thanks,
Mark
// take both inputs and bind this function to the change event of both
$("#comType, #comDirection").on('change', function () {
// show the button if they both have a value
if ($("#comType").val().length > 0 && $("#comDirection").val().length > 0) {
$("#button_that_displays_only_when_both_selects_have_input").show();
}
});
As the condition is checking the value lengths, once you correctly set up your options it will only show the button when the selects have actual values selected.
i.e.
value's length is 0, button will not show:
<option value="">Placeholder</option>
value's length is 3, so the button will show (if the other side of the condition is also satisfied):
<option value="fax">Fax</option>
This solution interprets the first option ("-- Select --") as invalid, independent of it's and the other options textual content.
Tested with jQuery 1.8.1 and 2.0.3, with browsers Firefox 24.0/Linux, Opera 12.16/Linux, Chrome 29.0.1547.76/Linux.
<!DOCTYPE html>
<html>
<head>
<title>Option select</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="PATH_TO_jQuery"></script>
<script type="text/javascript">
function bothSelectsAreValid() {
return $("#comType")[0].selectedIndex > 0 && $("#comDirection")[0].selectedIndex > 0;
}
function setButtonVisibility() {
if (bothSelectsAreValid())
$("#button_that_displays_only_when_both_selects_have_input").show();
else
$("#button_that_displays_only_when_both_selects_have_input").hide();
}
$(document).ready(function() {
$("#comType, #comDirection").on('change', function() {
setButtonVisibility();
});
setButtonVisibility(); // needed if browser presets the selected values on reload
});
</script>
<style type="text/css">
#button_that_displays_only_when_both_selects_have_input { display : none; }
</style>
</head>
<body>
<select id="comType">
<option selected="selected">-- Select --</option>
<option>Call</option>
<option>Fax</option>
<option>Email</option>
</select>
<select id="comDirection">
<option selected="selected">-- Select --</option>
<option>Incoming</option>
<option>Outgoing</option>
</select>
Next
</body>
</html>

Bind / Unbind or On / Off with select and jQuery datepicker

I want to remove the click event from select list and from jQuery date picker.
Say if a select box contains 3 values
(Select, Yes, No) No is selected when the form is loaded then the user must not be able to change it until a satisfying condition is met.
Once the condition is met also I want to restore the selection of any option.
<html>
<head>
<title> Javascript Test </title>
<script src="jquery.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#b1").data("isOn","Remove");
});
$(document).ready(function(){
$("#b1").click(function(){
var i=0;
//alert("hi");
if($(this).data("isOn")=="Add"){
alert($(this).data("isOn"));
$(this).data("isOn",'Remove');
$("#car").on('click');
//return false;
}
else if($(this).data("isOn")=="Remove"){
alert($(this).data("isOn"));
$("#car").off("click");
$(this).data("isOn",'Add');
//return false;
}
alert(i);
i++;
});
});
</script>
</head>
<body>
<select name="carlist" form="carform" id="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type = "button" value="Add/Remove" id="b1"/>
</body>
</html>

More Properties of Dropdown options

I've got a dropdown setup going on in which the user enters an input value, chooses a calculation to perform on that number from a dropdown, then a function displays the result.
What I would like is to add more 'values' to the dropdown, so when an option is selected from the list, it can also, say, display some text stored in the list, or some other information. Right now I can return the selected option's value (.value) and use the option's name (.text) to perform functions, but is there any more data I can add to each selection to be used later?
<html>
<head>
<script language="JavaScript">
function myfunction(form)
{
var i = parseFloat(form.Input.value, 10);
var e = document.getElementById("calculationList");
var strUser = e.options[e.selectedIndex].value;
form.Output.value = strUser*i;
}
</script>
</head>
<body>
<form>
Input Number:
<INPUT NAME="Input" SIZE=15>
Make a selection:
<select id="calculationList" onchange="myfunction(form)">
<option></option>
<option value="2">Double It</option>
<option value="3">Triple It</option>
<option value="10">Multiply It By ten</option>
</select>
Output Number:
<INPUT NAME="Output" SIZE=15>
</FORM>
</body>
</html>
Basically you may attach data attribute to your options like that:
<select id="calculationList">
<option></option>
<option value="2" data-aaa="10">Double It</option>
<option value="3" data-aaa="20">Triple It</option>
<option value="10" data-aaa="30">Multiply It By ten</option>
</select>
And later get the content of the attribute:
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
jsfiddle -> http://jsfiddle.net/pzKrr/
Edit:
If you want to implement my solution remove onchange="myfunction(form)" from the select tag. After that add the following code just after that myfunction
window.onload = function() {
var dropdown = document.getElementById("calculationList");
dropdown.addEventListener("change", function() {
console.log(dropdown.options[dropdown.selectedIndex].getAttribute("data-aaa"));
});
};

Update Textbox with Combobox value on ValueChange event

My ultimate goal with this is to make a dropdown that allows user input also. The best I can seem to do is an textbox next a dropdown that makes it look like they are similar, the issue I am running into is that I need the textbox to update whenever my dropdown value is changed. I have some code I've been playing with (below), but it doesn't seem to be getting me anywhere! Any pointers on how I can get this to work, or am I messing up the syntax? (fairly new to both jscript and html)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<style type="text/css">
select
{
width:200px;
}
</style>
<head>
<title>Test</title>
<script type="text/JavaScript">
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
</script>
</head>
<body>
<form action="" method="">
<input name="stroke"/>
<select name="theItems" onchange="otherSelect()">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
You should execute your script in the window.onload event. The elements are not available to your script when it is being executed. Change your script to this
<script type="text/JavaScript">
window.onload = function(){
var select = document.getElementById('theItems');
var input = document.getElementById('stroke');
function otherSelect()
{
input.value = select.value;
}
}
</script>
This way the script will be executed after the HTML elements have been rendered by the browser.
Here's a simple pure JavaScript implementation of what you want. http://jsfiddle.net/24Xhn/
We're going to setup the markup so the select box and the other input box have similar name and id attributes. We'll use classes to setup/initialize the onchange events and make sure the inputs start off hidden and disabled. By toggling the "disabled" attribute, true or false we are making it so the input or select don't show up when the form is submitted, submit the form in the JSFiddle with different combinations and you'll see the output in the query string of the URL.
HTML
<select id="items1" name="items1" class="select-other">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<input id="items1-other" name="items1-other" class="input-other" />
JS
// setup
var inps = document.getElementsByClassName("input-other");
for(var i=0; i<inps.length; i++) {
var inp = inps[i];
// hide & disable the "other" input
inp.style.display = "none";
inp.disabled = true;
// set onchange, if input is empty go back to select
inp.onchange = function() {
var val = this.value;
if(val == "") {
this.style.display = "none";
this.disabled = true;
// get its associated select box
var sel = document.getElementById(this.id.replace(/-other$/i, ""));
sel.style.display = "";
sel.disabled = false;
}
};
}
var sels = document.getElementsByClassName("select-other");
for(var i=0; i<sels.length; i++) {
var sel = sels[i];
// set onchange if value is other switch to input
sel.onchange = function() {
var val = this.value;
if(val == "other") {
this.style.display = "none";
this.disabled = true;
// get associated input box
var inp = document.getElementById(this.id + "-other");
inp.style.display = "";
inp.disabled = false;
}
};
}
I just realized what was wrong. I didn't truly look at the html until I copied and pasted it into a test application and I figured out the issue.
You need to set the id tag to the stroke and theItems not the name tag. That's why it's not doing anything. There was, I'm guessing, a copy/paste issue as well because you didn't have a closing html tag, but I assumed you just missed copying that. Also, you don't really need global variables in order to retrieve the input and select you just need them inside the actual function, and you can actually pass the select into the function like so.
Your code corrected:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
<style type="text/css">
select
{
width:200px;
}
</style>
<script type="text/javascript">
function otherSelect(obj)
{
var input = document.getElementById('stroke');
input.value = obj.value;
}
</script>
</head>
<body>
<form action="" method="">
<input id="stroke" name="stroke"/>
<select id="theItems" name="theItems" onchange="otherSelect(this)">
<option value="item1">Item One</option>
<option value="item2">Item Two</option>
<option value="item3">Item Three</option>
<option value="item3">Item Four</option>
<option value="other">Other</option>
</select>
<div id="otherBox" style="visibility: hidden;">
If other: <input name="otherField" type="text" />
</div>
</form>
</body>
</html>
I also wanted to create a combobox with an auto-updating text field next to it for new entries, and came up with this in less than an hour, based on simple html and javascript examples from w3schools.com. It works perfectly on my IE browser.
<!DOCTYPE html>
<html>
<head>
<script>
function updateField(name, value)
{
document.getElementById(name).value = value;
}
</script>
</head>
<body>
<select name='10' onchange='updateField(this.name, this.value)'>
<option value='volvo'>Volvo</option>
<option value='saab'>Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" id="10" value="volvo">
</body>
</html>

Categories