How to click a dropdown menu and select option? - javascript

I have the following code
<select class="needsclick" id="country" name="order[country]">
<option value="USA" selected="selected">USA</option>
<option value="CANADA">CANADA</option>
</select>
I could do the following javascript command to change the option value
document.getElementById("country").value = 'CANADA'
however, this does not change the selected value and does not change the state box to province.
When I physically click this dropdown menu and change to CANADA, the effects of the change take place (the state box changes to province)
I am using Swift iOS to parse HTML and wondering what line of javascript code is needed to click a option value rather than changing the option value?
If I do the following after changing the value
document.getElementById("country").click()
it just clicks the menu but still does not change the state box to province (happens when physically clicking the option value)
How can I achieve this using a javascript command like the two above?
The state/province box is irrelevant to the code just relevant to the fact it changes when the dropdown is physically clicked and not when programmatically changed.
I can do the following code but it still does not change the state box to province (only if physically clicked)
document.getElementById("country")[1].selected = true

To work with the option elements within a select, you must access the options node list and then select one to work with.
Setting the value is separate from setting the selected flag.
var countries = document.getElementById("country");
var states = document.getElementById("provincesUSA");
var territories = document.getElementById("provincesCanada");
countries.addEventListener("change", function(e) { update(e); });
function update(e){
// show the correct sub-list based on the selected option
var country = countries[countries.selectedIndex];
if(country.value === "USA"){
states.classList.remove("hidden");
territories.classList.add("hidden");
} else if(country.value === "CANADA") {
territories.classList.remove("hidden");
states.classList.add("hidden");
} else {
territories.classList.add("hidden");
states.classList.add("hidden");
}
}
// To dynamically choose
document.querySelector("button").addEventListener("click", function(){
countries.options[2].selected = "selected"; // Canada
// Simulate the change event
update(countries);
});
#provincesUSA.hidden, #provincesCanada.hidden { display:none; }
<select class="needsclick" id="country" name="order[country]">
<option value="" selected="selected">Choose A Country</option>
<option value="USA">USA</option>
<option value="CANADA">CANADA</option>
</select>
<select id="provincesUSA" class="hidden" name="states">
<option value="al">Alabama</option>
<option value="ar">Arkansas</option>
</select>
<select id="provincesCanada" class="hidden" name="territories">
<option value="on">Ontario</option>
<option value="qu">Quebec</option>
</select>
<button>Force A Selection (click me whe CANADA is NOT selected)</button>

document.getElementById("country").selectedIndex = 2;

Related

Determine the Selected Index number of a drop down menu?

I'm trying to make sure that the user is not selecting the default of a drop down method by determining the index number selected. It seems to be only returning false even though I believe the code is correct... So far I have the code listed below but its not working, any ideas?
<p id="Gender">
<label for="Gender">Gender: </label>
<select required>
<option disabled selected value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</p>
function validate1() {
valCheck3 = true;
var dropD1 = document.getElementById("Gender");
var resultSelect = dropDown1(dropD1);
var image3 = getImage(Boolean(resultSelect), "gender");
var labelGender = getNotification3(Boolean(resultSelect), "gender");
document.getElementById("Gender").appendChild(image3);
document.getElementById("Gender").appendChild(labelGender);
}
function dropDown1(select){
if(select.selectedIndex > 0){
return true;
}
valCheck3 = false;
return false;
}
EDIT: I added the HTML I used the setting to make the answer required, the problem is I need to have a button that checks whether the answer has been selected to insert an image next to the box. So in this case I figured I could determine the selected index number of the drop down so that I could determin
You can add the required attribute to the select element, then add some value attribute to each option except for the first one (use value without the value itself i.e. value="1")
Then you can just use select.checkValidity(), which returns true or false.
I'm trying to make sure that the user is not selecting the default of a drop down
You can just add disabled attribute to the <option> and also make it default. If the user opens the dropdown, the default option can not be clicked anymore and the user has to choose an onther option.
Example:
<form action="">
<select required>
<option disabled selected value>Default option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="submit">
</form>

How do I disable certain options of 'Dropdown B' depending on an option selected on 'Dropdown A'?

Im new to this so apologies if my question is not presented as it should be.
Basically, my aim is with jQuery is to make it so that when the field called 'Apple' is selected from the first dropdown box, the second dropdown box will only allow the field 'Firm' to be selected and the other two be disabled. However if any of the other fruits other than 'Apple' is selected from the first dropdown box then all of the options in the second dropdown box (texture dropdown) will be available to be chosen.
I have looked all over the internet for jQuery code to help me with this issue but as I am new to jQuery I have difficulty finding the solution I need.
Here is my HTML code:
<div class="ingredients_div">
<select name="ingredients_form" id="ingredients_form_1">
<option value="Apple" selected="">Apple</option>
<option value="Orange">Orange</option>
<option value="Lemon">Lemon</option>
<option value="Mango">Mango</option>
</select>
</div>
<div class="texture_div">
<select name="texture_form" id="texture_form_1">
<option value="Firm" selected="">Firm</option>
<option value="Soft">Soft</option>
<option value="Blended">Blended</option>
</select>
</div>
Many thanks
please check this code , i think it works for you.
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Lemon</option>
</select>
<select name="select2" id="select2">
<option value="1">Firm</option>
<option value="2">Soft</option>
<option value="3">Blended</option>
</select>
To achieve what you mentioned, you need to use jQuery's event binding on the first select box. As soon as the value is changed, you need to write logic to enable/disable options in the second select box as per the value changed in the first box.
Here is how you can achieve it.
$("#ingredients_form_1").change(function() {
if ($(this).val() === "Apple") {
$("#texture_form_1 option").prop("disabled", true);
$("#texture_form_1 option[value='Firm']").prop("disabled", false);
} else {
$("#texture_form_1 option").prop("disabled", false);
}
});
Please go through jQuery's documentation to know more about selectors, event binding, and most importantly, in the next post, include what you've achieved till then.

Select changes selected only twice

I have 2 dropdowns. When you select the Handling unit from the first dropdown $("#HandlingUnit"), it should read the text of the label for the selected option group, then change the second based on on the text of the option....
Example Scenario:
Select 2222 from $("#HandlingUnit"), it reads the optgroup label "Cases" and changes $("#HUType") to "Cases"
Select P00001 from $("#HandlingUnit"), it reads the optgroup label "Pallets" and changes $("#HUType") to "Pallets"
Select 1111 (or 2222) from $("#HandlingUnit"), it does not change to Cases.
This works great for 2 changes, however the third time, the second dropdown does not change.
<label class="label_long" for="HandlingUnit">Handling Unit:</label>
<select id="HandlingUnit" required="" name="HandlingUnit">
<optgroup id="Pallets" label="Pallets">
<option value="P00001">P00001</option>
</optgroup>
<optgroup id="Cases" label="Cases">
<option value="1111">1111</option>
<option value="2222">2222</option>
</optgroup>
</select>
<label class="label_long" for="HuType">Handling Unit Type: </label>
<select id="HUType" name="HUType">
<option value="1" name="Pallets"> Pallets </option>
<option value="0" name="Case" selected="selected"> Cases </option>
<option value="3" name="Items"> Items </option>
</select>
Javascript/jQuery:
$(document).on("change", "select#HandlingUnit", function() {
var selected = $(":selected", this).parent().attr('label');
$("#HUType").find("option:selected").removeAttr("selected");
$("#HUType option").filter(function() {
console.log(this.text.trim() + " >> " + selected);
return this.text.trim() == selected;
}).attr("selected", true)
});
JSFiddle
Edit: JSFiddle is not responding how it does inside my application, so I'm thinking there might be something bigger going on... Looking into it will report back if I find anything.
You can use .val(function)
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
Code
$(document).on("change", "select#HandlingUnit", function() {
var selected = $(":selected", this).parent().attr('label');
//Find option with selected label and set its value
$("#HUType").val(function(){
return $(this).find('option[name="' + selected +'"]').val();
});
});
$("select#HandlingUnit").trigger("change"); //Trigger on page load
DEMO

Jquery for retaining the selected value in select option

i am playing some show/hide function using my select drop down. Here is the html for select,
<select id="sel1" size="1" name="">
<option selected="selected" value="0">Select Here</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Here is my jquery,
$(document).ready(function(){
$("#sel1").change(fun);
});
function fun(){
var selected = $("#sel1 option:selected");
if(selected.val() == 1) {
$("#div1").slideDown("slow");
$('#div2').slideUp("slow");
} else if(selected.val() == 2) {
$("#div1").slideUp("slow");
$('#div2').slideDown("slow");
} else {
$("#div1").slideUp("slow");
$('#div2').slideUp("slow");
}
};
But after the value sent to the server and return back, I want to retain the div1 or div2 based on the value select in the dropdown. But as of now, both the div are not displaying because of display=none at initial level. Any way to retain this?
If your HTML is generated using a server-side language, your best option would be to only add the display: none CSS property to them when appropriate. Alternatively, you could just trigger the change event handler when the DOM is ready, using:
$(document).ready(function(){
$("#sel1").change(fun).trigger('change');
});

select and input copied into one input for posting

First off sorry for a re-post, I voted to delete my old post because I'm asking for help on the code now, not just which way is the better route. Any my code has changed several times
On my page there is a drop down to select a country, dynamically loaded from a db. Once the user selects a country two things can happen. 1) If they select Canada or the US a second drop-down appears and the user can select a region. 2) If the user selects any other country it creates an input box so that the user can type the region instead. This all works fine.
Now there is a third input which takes the province/state value so it can be posted. There are only two of us who will use this form so I'm not worried about JavaScript being turned off in the browser.
My issue is that when the user first selects the Canada/US and a region, nothing is filled into the third input unless they change the country selection. However, if they select a country other than Canada/US and have to type the region, it works as expected.
Here is an example of the issue: http://jsfiddle.net/owalsh/BQXZA/3/
If anyone can tell me why I'd appreciate it, thanks
Working here: http://jsfiddle.net/5A4v4/11/
HTML:
<form id="customer_bill_add_post" name="customer_bill_add_post">
<select id="country" name="country">
<option value="0">Select a country</option>
<option value="CA">Canada</option>
<option value="US">United States</option>
<option value="OT">Other</option>
</select>
<select id="province_select" name="province_select">
<option value="0">Select a Province</option>
<option value="AB">Alberta</option>
<option value="AL">Alabama</option>
</select>
<input type="text" id="province_input" name="province_input">
<input type="text" id="province" name="province" />
</form>
Jquery: code (there was some extra change event binding going on) you can prettify it.
$(function(){
//initially hide the textbox
$("#province_input").hide();
$("#province_select").hide();
$('#country').change(function() {
if($(this).find('option:selected').val() == "CA"){
$("#province_select").show();
$("#province_input").hide();
} else if($(this).find('option:selected').val() == "US"){
$("#province_select").show();
$("#province_input").hide();
} else {
$("#province_input").show();
$("#province_select").hide();
}
});
$('#country, #province_select, #province_input').bind("change", function() {
if($('#country').find('option:selected').val() == "CA"){
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_select.value;
} else if($('#country').find('option:selected').val() == "US"){
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_select.value;
} else {
//alert('foo');
document.customer_bill_add_post.province.value = document.customer_bill_add_post.province_input.value;
}
});
});
Cheers,

Categories

Resources