Set select element option on page load - javascript

I want the page to auto-select some value ('hot', 'new', etc.) depending on the
$r->category value which is loaded from database. The $r->category value contains some string that could be 'hot', 'new', etc.
Input element:
<input type="text" id="cex" value="<?php echo $r->category?>">
The select option:
<select name="ktgr" onChange="cek();">
<option id='n' value="normal">normal</option>
<option id='h' value="hot">hot</option>
<option id='nw' value="new">new</option>
<option id='u' value="upcoming">upcoming</option>
</select>
The javascript function
function cek()
{
var j = document.getElementById("cex").value;
if(j=='normal')
document.getElementById('n').selected=true;
else if(j=='hot')
document.getElementById('h').selected=true;
else if(j=='new')
document.getElementById('nw').selected=true;
else if(j=='upcomming')
document.getElementById('u').selected=true;
}

Currently, your code will set the value of the select element to the initial value every time any option is selected. For example, if 'hot' is the value from the server, and a user selects 'new', the cek function will execute in the change event and change the value back to 'hot'.
Instead, only set the select element's value to the initial value from the server once. A working example is below.
function cek() {
var j = document.getElementById("cex").value;
if (j == 'normal')
document.getElementById('n').selected = true;
else if (j == 'hot')
document.getElementById('h').selected = true;
else if (j == 'new')
document.getElementById('nw').selected = true;
else if (j == 'upcoming')
document.getElementById('u').selected = true;
}
<body onload="cek()">
<input id="cex" value="new" />
<select name="ktgr">
<option id='n' value="normal">normal</option>
<option id='h' value="hot">hot</option>
<option id='nw' value="new">new</option>
<option id='u' value="upcoming">upcoming</option>
</select>
</body>

Related

Simplify setOptionByValue(selectElement, value) function for <select> element. How?

When data is received from a JSON api, one of the data properties is used to set the selected option value of a select html element.
The following code sets the option to be selected based on the select html element and the corresponding select option value passed in.
Is there a shorter version of this nowadays?
Take a look:
// Custom function to set select option by value
const setOptionByValue = (selectElement, value) => {
let options = selectElement.getElementsByTagName('option');
for (let i = 0, optionsLength = options.length; i < optionsLength; i++) {
// console.log(options[i].value);
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
// The select element
const selectStatus = document.getElementById('selectStatus');
// Initially set status to Draft.
setOptionByValue(selectStatus, 'Draft');
<label for="selectStatus">Status:</label>
<select id="selectStatus">
<option value="0" selected>Select...</option>
<option value="Draft">Draft</option>
<option value="Pending">Pending</option>
<option value="Complete">Complete</option>
</select>
Just assign the value to the select element's value
// Custom function to set select option by value
const setOptionByValue = (selectElement, value) => {
selectElement.value = value;
}
// The select element
const selectStatus = document.getElementById('selectStatus');
// Initially set status to Draft.
setOptionByValue(selectStatus, 'Draft');
<label for="selectStatus">Status:</label>
<select id="selectStatus">
<option value="0" selected>Select...</option>
<option value="Draft">Draft</option>
<option value="Pending">Pending</option>
<option value="Complete">Complete</option>
</select>
Should the value of the option differ from its content and you wish to select by content:
// Custom function to set select option by value
const setOptionByValue = (selectElement, value) => {
selectElement.querySelectorAll('option').forEach((e) => {
if (e.innerHTML == value) {
selectElement.value = e.value;
}
})
}
// The select element
const selectStatus = document.getElementById('selectStatus');
// Initially set status to Draft.
setOptionByValue(selectStatus, 'Draft');
<label for="selectStatus">Status:</label>
<select id="selectStatus">
<option value="0" selected>Select...</option>
<option value="Draft">Draft</option>
<option value="Pending">Pending</option>
<option value="Complete">Complete</option>
</select>

How to establish relationship between option tag of different select tags in html

I have three select tags in HTML with option tag.I want to establish relationship between option tags of different select tag.
EDIT-1
When I choose Reference-1 from select name="reference" then 2014-10-10 07:17:00 and 2014-10-10 08:46:00 from select name="from" and select name="to" should only be present in the dropdown list.When I choose Reference-2 then 2014-09-01 10:00:00 and 2014-09-01 11:00:00 should only be present in dropdown list of from and to select tag. My html code for is-
<form method="post">
Select Reference:
<select name="reference">
<option value="Select">Select</option>
<option value="Reference-1">Reference-1;</option>
<option value="Reference-2">Reference-2</option>
<option value="Reference-3">Reference-3</option>
<option value="Reference-4">Reference-4</option>
</select>
From Date:
<select name="from">
<option value="Select">Select</option>
<option value="2014-10-10 07:17:00">2014-10-10 07:17:00</option>
<option value="2014-09-01 10:00:00">2014-09-01 10:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 10:00:00</option>
</select>
To Date:
<select name="to">
<option value="Select">Select</option>
<option value="2014-10-10 08:46:00">2014-10-10 08:46:00</option>
<option value="2014-09-01 11:00:00">2014-09-01 11:00:00</option>
<option value="2014-09-08 10:00:00">2014-09-08 11:00:00</option>
</select><br>
<b>Select Date to be compared</b>
<p>Date: <input type="text" id="datepicker"></p>
<input type="submit" value="Submit"><br>
</form>
Get the index of the selected option from reference select element and then disable all the options of from and to select elements except the option with index of the previous index you got from reference select option.
javaScript Solution :
var reference = document.getElementsByName("reference")[0];
var fromSelect = document.getElementsByName("from")[0];
var toSelect = document.getElementsByName("to")[0];
reference.onchange = function(){
var selectedIndex = this.selectedIndex;
for(var i = 1; i <= fromSelect.length; i++){
if(i != selectedIndex){
fromSelect.getElementsByTagName("option")[i].disabled = true;
toSelect.getElementsByTagName("option")[i].disabled = true;
} else{
fromSelect.getElementsByTagName("option")[i].disabled = false;
toSelect.getElementsByTagName("option")[i].disabled = false;
}
}
};
jsFiddle
jQuery Solution :
$("select[name='reference']").on("change", function(){
var $fromSelect = $("select[name='from']");
var $toSelect = $("select[name='to']");
var selectedIndex = $(this).children("option:selected").index();
$fromSelect.children("option").removeAttr("disabled");
$toSelect.children("option").removeAttr("disabled");
$fromSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
$toSelect.children("option").not(":eq(" + selectedIndex +")").prop("disabled", "disabled");
});
jsFiddle
If second selection values are dependent on the first selection option, then you should disable the whole second selection until the first one is selected.
When the first one is selected then disable all the unrelated options in second selection and make it enabled to the user. Let me know if it helped.
$("select[name='reference']").on('change', function() {
var value = $(this).val(); // first selection value
if ("Reference-1" == value ) {
var $selection2 = $("select[name='from']");
$selection2.find("option[value*='2014-09-01 10:00:00']").prop('disabled',true);
$selection2.find("option[value*='2014-09-08 10:00:00']").prop('disabled',true);
}
...
});
Here is DEMO

Dropdown 1 value automatically selects dropdown 2 value

I am trying to write a JavaScript function where if value 1 from the first dropdown(pcount) automatically selects value 1 for drop down 2(listedname), But then if anything besides value 1 (2,3,4) is chosen I do not want drop down 2 to do anything except default back to please select if value 1 was selected and then changed to another value. I am very new to JavaScript and programming in general and have not been able to find any examples similar to this. So any help will help!
JavaScript Funtion:
<script type="text/javascript">
function leaveChange() {
if (document.getElementById("pcount").value = 1){
document.getElementById("listedname").value = 1;
}else
document.getElementById("listedname").value = 2;
}
}
</script>
Dropdown 1 and 2:
<select id="pcount" onchange="leaveChange()">
<option value="" selected="selected">Please Select</option>
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
<option value="4">3</option>
</select>
<select id="listedname">
<option value="" selected="selected">Please Select</option>
<option value="1">Business Name</option>
<option value="2">Individual Owner</option>
</select>
If you are doing your if clause with one equals sign, Javascript will check if your element is set to the new value successfully.
Instead, when you do a comparison, use double equal signs (in your case)
if (document.getElementById("pcount").value == 1){
If anyone is looking for the JavaScript function here you go!
<script type="text/javascript">
function leaveChange() {
if (document.getElementById("pcount").value == 1){
document.getElementById("listedname").value = 1;
}
else if (document.getElementById("pcount").value != 1){
document.getElementById("listedname").value = "";
}
}
</script>

How to run a piece of javascript when you select a dropdown option?

I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};

javascript validation in a form

I am having trouble getting this validation to work. I am validating that a selectbox has been chosen and not left on the default option within my form.
Form:
<label for="reason">How can we help?</label>
<select name="reas">
<option value="Please Select">Please Select</option>
<option value="Web Design">Web Design</option>
<option value="branding">Branding</option>
<option value="rwd">Responsive Web Design</option><span id="dropdown_error"></span>
</select>
Onclick event:
$(document).ready(function(){
$('#contactForm').submit(function(){
return checkSelect();
});
});
Function:
function checkSelect() {
var chosen = "";
var len = document.conform.reas.length;
var i;
for (i = 0; i < len; i++){
if (document.conform.reas[i].selected){
chosen = document.conform.reas[i].value;
}
}
if (chosen == "Please Select") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}
I also get this error in the console:
Uncaught TypeError: Cannot set property 'innerHTML' of null
I am really new to javascript, so, I am learning and trying some simple examples at the moment, but I cannot see what is causing this not to validate.
Any help appreciated
First, you can't have your error span inside the <select>. Move it outside of the <select> HTML, and that will make the JS error go away.
<label for="reason">How can we help?</label>
<select name="reas">
<option value="select">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option>
</select>
<span id="dropdown_error"></span>
Then, since you are already using jQuery, you could shorten your whole validation function to just this:
function checkSelect() {
var chosen = $('select[name="reas"]').val();
if (chosen == "select") {
$("dropdown_error").text("No Option Chosen");
return false;
} else {
$("dropdown_error").text("");
return true;
}
}
Change your default selection to an optgroup:
<optgroup>Please Select</optgroup>
Then it won't be selectable
https://developer.mozilla.org/en-US/docs/HTML/Element/optgroup
Your default value is "select" and you are checking "Please Select". Use the same value.
Change this
<option value="select">Please Select</option>
to
<option value="Please Select">Please Select</option>
EDIT: I would use the following code. To fix javascript issue, make sure you put the script just before closing body tag. Your script is executing before the document is parsed
<label for="reason">How can we help?</label>
<select id="reas" name="reas">
<option value="">Please Select</option>
<option vlaue="Web Design">Web Design</option>
<option vlaue="branding">Branding</option>
<option vlaue="rwd">Responsive Web Design</option><span id="dropdown_error"> </span> </option>
function checkSelect() {
var chosen = document.getElementById["reas"].value;
if (chosen == "") {
document.getElementById("dropdown_error").innerHTML = "No Option Chosen";
return false;
}
else{
document.getElementById("dropdown_error").innerHTML = "";
return true;
}
}

Categories