Select an option of select box using the value - javascript

I have a dropdown box and I want to select the option based on value. Somehow I am getting handle to value say 3. Now I want to manually select the option which has got value 3.
I have tried something like this
selectBoxElement.options[selectedValues].selected = true;
where selectedValue = 3, but it is not working.

If using jquery (as per your tag), you can do:
$(document).ready(function() {
$("#yourSelectId option[value='3']").attr("selected", "selected");
});

Something like that should work (assuming $ is not overwritten and is alias for jQuery):
$(selectBoxElement).find('option[value="selectedValue"]').prop('selected', true);
or rather:
$(selectBoxElement).val(selectedValue);
which is simpler and achieves similar result :)

If you're using plain JS (except for the jQuery tag, you didn't explicitly say whether you want plain JS or jQuery), this should do what you want:
for (i=0; i<selectBoxElement.options.length; i++) {
if (selectBoxElement.options[i].value == selectedValues) {
selectBoxElement.options[i].selected=true;
break;
}
}

This is simple please try the following
When using the index position of the option tag within the select box
selectBoxElement.selectedIndex = index; // Where the index starts from 0
When using the value
selectBoxElement.value = value;// Where the value is the attribute defined within option tag
Hope this solves your problem.

Related

Update some fields on change and on load

We have the following script which runs on a change to a drop-down - updates the price based on the currency code chosen. This basically gets the value of the drop-down and updates the priceamm and preicecurr fields within the text on the page.
<script>
function run() {
var f = document.getElementById("dropPrice");
priceamm.innerHTML = f.options[f.selectedIndex].value;
var e = document.getElementById("dropPrice");
pricecurr.innerHTML = e.options[e.selectedIndex].text;
}
HTML
<select id="dropPrice" onchange="run()" class="fa-select">
<option value = "a">aaa</option>
<option value = "b">bbb</option>
Question
Now, we would also like to load the drop-down to one of the options (selected) when loading the page (onload). We are able to populate the variables in the text but not the drop-down to show option bbb. In php this is quite easy but we are a bit lost with javascript. We tried something on these lines onload but does not work:
document.getElementById("dropPrice").value = "<?php echo $geo_price ;?>";
With jQuery this is probably easier but once again no luck:
window.onload = function() {
jQuery(document).ready(function($){
document.getElementById('dropPrice').find('option[value=<?php echo $geo_price ;?>]').attr('selected','selected');
});
}
Any help is appreciated. Thanks
The jQuery selector part is incorrect. You are mixing plain JS with jQuery. When you call document.getElementById('dropPrice') a regular DOM element is returned, but then you call find which is a jQuery method to be used on a jQuery element. So, you either need to wrap the first part to return a jQuery element like so:
$(document.getElementById('dropPrice'))
.find('option[value="b"]').attr('selected', true);
Or, select it via jQuery in the first place like:
$('#dropPrice [value="b"]');
However, your first example:
document.getElementById("dropPrice").value = "b";
should work. That makes me wonder if the value that is being echoed by PHP is correct and/or if there are other JS errors being thrown that would cause that code not to run.

Alternative method to display content

The selected radio button will show its corresponding dropdown box.
For example, upon the selected radio button ‘Ontario’, a dropdown box with matching cities will show up.
I have the following working code for the above example:
<script type="text/javascript">
$(document).ready(function(){
$("#searchForm input:radio").change(function() {
var buttonPressed = $('[name="Region"]:radio:checked').val();
var cityElmntBox = document.getElementById("dispalyCityBox");
if(buttonPressed == 'Ontario'){
cityElmntBox.style.display='block';
} else {
cityElmntBox.style.display='none';
}
});
});
</script>
Instead of the sudden effect (display='block'), I wanted to use for the selected elements the slideDown() method.
So I replaced:
cityElmntBox.style.display='block';
with:
cityElmntBox.slideDown(500);
But this doesn’t work…, please can someone help me get it working?
Wrap it in jQuery:
$(cityElmntBox).slideDown(500);
Also you can simplify the var statement like this and you wont have to put it in a wrapper:
var cityElmntBox = $("#dispalyCityBox");
Use $('#dispalyCityBox') instead of document.getElementById("dispalyCityBox").
Try $('#dispalyCityBox').slideDown(500) instead.
By using cityElmntBox.slideDown(500); you're trying to use a jQuery method on a non-jQuery object.

How to enable/disable text field on radio button interaction?

Cannot get this to work. First time using variables passed into functions. Unchecking radio button should disable form field and vice versa. lineid variable distinguishes this radio/text input pair from 10 others.
My code:
<script type="text/javascript">
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid.disabled = false;
} else {
document.dupedit.lineid.disabled = true;
}
}
</script>
Subset of my HTML.
You need to pass a string into your disablefield function, so put the value in quotes when you pass it in. Something like:
<input onclick="disablefield('2671997')" />
This is because document.getElementById expects a string, not an integer.
Secondly, to enable/disable the field, you need to use disabled = true; rather than = 'disabled'.
document.dupedit.lineid is looking a for a field with name "lineid", which doesn't exist in your form. I would suggest giving the field an id and using document.getElementById again instead.
If you want to continue using the name attribute, you will have to use document.getElementsByName instead. This returns an array of matching elements (since multiple elements can share the same name), but if in your code you know that the element in question is the only one with that name, you can do this:
document.getElementsByName(lineid)[0].disabled = true;
You can see a working version (I think this is how you wanted it anyway) here. And here is a version using getElementsByName.
You are missing a closing brace on the function:
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
} //<-- here
Also, can I suggest you pass this to the function. Then you don't have to call getElementById
<input onclick='disablefield(this)' type.....
function disablefield(obj){
if (obj.checked == true){
document.dupedit.lineid='enabled';
}else{
document.dupedit.lineid='disabled';
}
}
I think what you need is to re-think the code.
Don't use ID on the checkbox. Better move that ID to the text field you want to disable/enable and check whether that field is disabled/enabled, not the checkbox itself
use cleaner JS.
Please, take a look at the jsFiddle, I have compiled for you. Does it do what you expect, Dan?

jQuery selector for option tag value attribute returns null

I am trying to change the selected option in a select dropdown box with jQuery. I have it set so that it finds the hash tag at the end of the URL and based on that hash tag it changes the selected option in the select box.
Most of my code is functional, it successfully finds the hash tag and executes the if statement that corresponds with it. However, when it goes to execute the "then" section of the statement when it goes to the selector for the option (which uses an attribute selector based on the value attribute of the option tag) it returns null. If figured this out with firebug, in the console it says that the selector is null.
Here is my code:
$(document).ready(function() {
var $hash = window.location.hash
if($hash == "#htmlcss") {
$('option[value="HTML/CSS Coding"]').attr("selected","selected")
}
if($hash == "#php") {
$('option[value="PHP Coding"]').attr("selected","selected")
}
if($hash == "#jscript") {
$('option[value="Javascript and jQuery Coding"]').attr("selected","selected")
}
if($hash == "#improv") {
$('option[value="General Website Improvements"]').attr("selected","selected")
}
if($hash == "#towp") {
$('option[value="Website Conversion to Wordpress"]').attr("selected","selected")
}
if($hash == "#wptheme") {
$('option[value="Wordpress Theme Design"]').attr("selected","selected")
}
if($hash == "#complete") {
$('option[value="Complete Website Creation"]').attr("selected","selected")
}
if($hash == "#server") {
$('option[value="Web Server Configuration"]').attr("selected","selected")
}
});
So to clarify, when I enter in a url that ends in the #php hash tag, for example, the desired action does not occur which would change the "PHP Coding" option to the selected one by using the "selected" html attribute however the selector for the particular option tag returns null. Is there a problem with my syntax or is my code not functioning in the way that I think it should? Thanks very much.
You can slim it down and resolve your selector issue at the same time, just use .val() like this:
var hashmap = {
htmlcss: "HTML/CSS Coding",
php: "PHP Coding",
jscript: "Javascript and jQuery Coding",
improv: "General Website Improvements",
towp: "Website Conversion to Wordpress",
wptheme: "Wordpress Theme Design",
complete: "Complete Website Creation",
server: "Web Server Configuration"
};
$(function() {
var $hash = window.location.hash.replace('#','');
$("#IDOfSelectElement").val(hashmap[$hash]);
});
This approach sets the value on the <select> (finding it by it's ID) using .val(), which selects the <option> with the value matching what you passed in, this resolves escaping issues as well. However, I'm not certain the values you have are the actual value="" portion, they seem like the text of the <option>...make sure you're using the value="" portion. The other optimization is that this uses an object map to make this much easier to maintain :)
You shouldn't use quotes in the value selector, also I think you might need to escape the slash, i.e.:
$('option[value=HTML\\/CSS Coding]').attr("selected","selected")
For more info, see http://api.jquery.com/category/selectors/
Probably just add this code before your if statements:
$('option').removeAttr('selected');
Though know that if you have more then one select on the page, then that affects all of them.
Why not to assign id for each select option? It would make your code more tidy
$(document).ready(function() {
$(window.location.hash).attr("selected","selected");
});

JQuery/Javascript Clear/Reset Drop down List to original values

Ok dokey, got a bit of jquery up and running, lovely stuff.
$(document).ready(function() {
$inputs = $("#tbxProdAC, #ddlBuyer, #txtbxHowMany, radTopx");
$.each($inputs, function() {
$(this).focus(function() {
$.each($inputs, function() {
$(this).val('');
$(this).attr('checked', false);
})
});
})
});
However, in my drop down list, I wish to retain the orignal value rather than clear it altogether.
Is there a way I can specify the individual values i.e. tbxProdAC ='', ddlBuyer = Original Value, txtbxHowMany='', radTopx =unchecked, etc?
have you tryed:
document.getElementById('formId').reset();
try it this way:
$(document).ready(function() {
$("#tbxProdAC, #ddlBuyer, #txtbxHowMany, radTopx").focus(function() {
document.getElementById('formId').reset();
});
});
You'll have to go through each one separately to do that.
i.e.
$('#tbxProcAC').val('');
$('#ddlBuyer').val($('#ddlBuyer')[0].defaultValue);
$('#txtbxHowMany').val('');
$('#radTopx').attr('checked',false);
Perhaps the second line there may be of most intrest to you - it shows how to access the original 'default' value.
Comment if you've any questions, good luck!
You can use the data function in JQuery - you can store all the existing values and call them again when you need them
in JQuery can select First Option <option value="0" > </option> first option value is zero and text is empty.
now
$('#DropDown').find('option:first').attr('selected', 'selected');
$('#DropDown')[0].selectedIndex = 0;
$('#DropDown') -> select dropdown
find('option:first') -> find first option
attr('selected', 'selected') -> set attribute selected.
Try this simple way
document.getElementById(‘drpFruits’).options.length=0;

Categories

Resources