CSS with JavaScript - Cannot read property 'undefined' error - javascript

I tried to change the colors of the select lists header, title and text. I added the functions changehead(), changetitle() and changebody() to do this. And bind elements through unique id.
But I'm getting the following error
Uncaught TypeError: Cannot read property 'undefined' of undefined
in the function changehead(), after
header = document.form1.heading.options[i].value;
and in the function changetitle() after
header = document.form1.heading.options[i].value;
I'm not sure whether I should be using two different functions or if it can be done with one.
Code:
<script>
function changehead() {
i = document.form1.heading.selectedIndex;
header = document.form1.heading.options[i].value;
document.getElementById("head1").style.color = header;
}
function changetitle() {
i = document.form1.heading.selectedIndex;
header = document.form1.heading.options[i].value;
document.getElementById("head2").style.color = header;
}
function changebody() {
i = document.form1.body.selectedIndex;
doccolor = document.form1.body.options[i].value;
document.getElementById("p1").style.color = doccolor;
}
</script>
</head>
<body>
<h1 id="head1">Controlling Styles with JavaScript</h1>
<hr>
<h2 id="head2">Subtitles at this screen. And cery important subtitles!</h2>
<hr>
<p id="p1">Select the color for paragraphs and headings using the form below. The colors you specified will be dynamically changed in this document. The change occurs as soon as you change the value of either of the drop-down lists in the form.</p>
<form name="form1"> <b>Heading color:</b>
<select name="heading" onChange="changehead();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br>
<B>Body text color:</B>
<select name="body" onChange="changebody();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br> <b>Heading second color:</b>
<select name="heading" onChange="changetitle();">
<option value="black">Black</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
</form>
</body>
Questions:
How to circumvent situation with errors?
Do need two different functions for changing head & title, or is one enough (if yes - how)?

You have two selects named "heading". Give them different names and your javascript will stop throwing errors.
Here is a working example: http://jsbin.com/uritid/1/edit

Related

How to use JavaScript to make an option selected in a dropdown? [duplicate]

This question already has answers here:
How do I programatically select an HTML option using JavaScript?
(11 answers)
Closed 1 year ago.
The code below is for a dropdown in html:
<html>
<body>
<select id="demo1" name="demo2" type="text">
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
</body>
</html>
How to make the option with value "paris" selected?
Please consider it is not possible to change anything in the code above.
The code was edited to give more details because unfortunately the answers did not work on this question.
The below code did not work as well:
<script>
var selectedtext = "paris";
document.getElementById("demo1").selected = selectedtext;
</script>
If you know what position the option you want selected will always be in, you can use either of the following approaches:
To modify the DOM object property of the option, set the .selectedIndex property (which starts counting from 0) on the element.
document.querySelector("select").selectedIndex = 1;
<html>
<body>
<!-- A select element can't have a type attribute -->
<select id="demo1" name="demo2" type="text">
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
</body>
</html>
If you do want to alter the HTML state of the element, you can use the setAttribute() method on the element:
document.querySelector("select").options[1].setAttribute("selected", "selected");
// Just for demo purposes:
console.log(document.querySelector("select").outerHTML);
<html>
<body>
<!-- A select element can't have a type attribute -->
<select id="demo1" name="demo2" type="text">
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
</body>
</html>
But, if you only know the text of the option that should be selected and not its position, then you can use the following CSS selector with .querySelector to isolate the right option and select it:
let input = "paris";
// Either one of these will work:
// To affect the HTML state:
document.querySelector("option[value='" + input + "']").setAttribute("selected", "selected");
// To affect the DOM Object property:
document.querySelector("option[value='" + input + "']").selected = true;
// Just for demo purposes:
console.log(document.querySelector("select").outerHTML);
<html>
<body>
<!-- A select element can't have a type attribute -->
<select id="demo1" name="demo2" type="text">
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
</body>
</html>
You can do this in multiple ways:
if the options might change order you select the value itself
document.querySelector('[value=paris]').selected = true
<select>
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
Otherwise you can use selectIndex:
document.querySelector('select').selectedIndex = 1
<select>
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
this way....
document.querySelector('select').value = 'paris';
<select>
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
Or, with full use in a form:
const myForm = document.forms['my-form']
myForm.city.value = 'paris'
<form name="my-form">
<select name="city">
<option value="london">London</option>
<option value="paris">Paris</option>
<option value="tokyo">Tokyo</option>
</select>
</form>

Change 2 DIVS Using JS

I'm still very new to writing JS.
I want to be able to change 2 divs based on on option from a tag.
i.e if some one selects the color red it will show 2 different divs with content about red.
Please see the code below.
Thankyou in advance!
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</Select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
</script>
Consider adding a div as a container for your divs and create them
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</Select>
<div id="content"></div>
$('#colorselector').change(function(){
$('.colors').hide();
$('#content').html('');
$('#content').append('<div>Div 1'+ $(this).val()+'</div>');
$('#content').append('<div>Div 2'+ $(this).val() +'</div>');
});
The modern day frontend is heavily dependant on templating and rendering. To get into React/Vue/Angular, start with any simple templating library. Eg handlebars:
Your solution in handlebars:
<Select id="colorselector">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</Select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Include Handlebars from a CDN -->
<script src="https://cdn.jsdelivr.net/npm/handlebars#latest/dist/handlebars.js"></script>
<script>
// compile the template
var template = Handlebars.compile("<div> 'This can be anything eg <b>bold</b> text or selected value: {{content}}</div>");
$(function() {
$('#colorselector').change(function(){
$('body').append(template({ content: $(this).val() }))
});
});
</script>

check required field in Javascript on different button

i am not too good with java Script but trying to learn few things in different ways and this community always help me to learn such stuff.
i need some help from you guys again. below is my code and what i want is.
i have different dropdowns on a single page, with different buttons to run different queries in php. but i want to make sure that drop should have some selected value before proceeding to php query on button click. i am not able to perform this task, below is the sample which is definitely wrong. i want on button click "fun" Myfunction should run which should check that proper value is selected from drop down s1 and here s2 value is not required. and same is with 2nd button vice verse. kindly help and any idea would be appreciated.
function myFunction() {
document.getElementById("s1").value = "required"
}
function myFunction1() {
document.getElementById("s2").value = "required"
}
dd1:
<select id="s1">
<option>Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br>
<br>dd2:
<select id="s2">
<option>Select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="b">b</option>
</select>
<br>
<br>
<button onclick="myFunction()">fun</button>
<button onclick="myFunction1()">fun1</button>
You have to check value of document.getElementById("s1").selectedIndex and ...(s2) as following:
function myFunction() {
var s1 = document.getElementById("s1").selectedIndex;
var s2 = document.getElementById("s2").selectedIndex;
if (s1<1 && s2<1) {
alert("Please select atleast one item from dropdowns!");
return false;
};
}
<html>
<body>
dd1:<select id="s1">
<option >Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br> <br>
dd2:<select id="s2">
<option >Select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="b">b</option>
</select>
<br><br>
<button onclick="myFunction()">fun</button>
<button onclick="myFunction()">fun1</button>
</body>
</html>
Using jQuery will do the trick. You just need to check the value of your select component. To achieve this, you should first add a value for when nothing is selected:
dd1:<select id="s1">
<option value="0">Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br> <br>
dd2:<select id="s2">
<option value="0">Select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="b">b</option>
</select>
<br><br>
Now, when nothing is selected, the value of your component will be 0. To check this values, you have to do something like this:
function myFunction() {
var selectedValue1 = $('#s1').val();
var selectedValue2 = $('#s2').val();
// check both values and do whatever
}
function myFunction1() {
var selectedValue1 = $('#s1').val();
var selectedValue2 = $('#s2').val();
// check both values and do whatever
}
Using vanilla
If you don't want to use jQuery for whatever the reason, you just have to change var selectedValue1 = $('#s1').val(); for var selectedValue1 = document.getElementById('s1').value;.
I hope this helps :)

Multiple options from one drop down giving alternate results - Javascript/html

I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}

Show specific content based on 4 drop-down selections

I've managed to source some code to achieve the above, however, despite several attempts, I cannot get it to work. Could anyone please assist me on this?
JS in HEAD of HTML file:
<script type="text/javascript">
jQuery(function($){
selects = $('#select-container select'),
results = $('#results-container > div');
selects.change(function(){
var values = '';
selects.each(function(){
values += '.' + $(this).val();
});
results.filter(values).show().siblings().hide();
});
});
</script>
HTML in BODY of HTML file:
<div class="margins1"><h2>Goal</h2>
<div id='select-container'>
<select>
<option value='none'>Select Option</option>
<option value='Fat Loss'>Fat Loss</option>
<option value='Lean Muscle'>Lean Muscle</option>
<option value='Size & Mass'>Size & Mass</option>
</select>
<h2>Dietary Requirements</h2>
<select>
<option value='none'>Select Option</option>
<option value='No Requirements'>No Requirements</option>
<option value='Vegetarian'>Vegetarian</option>
<option value='Vegan'>Vegan</option>
<option value='Gluten Free'>Gluten Free</option>
<option value='Gluten Free (vegetarian)'>Gluten Free (vegetarian)</option>
<option value='Gluten Free'>Gluten Free (vegan)</option>
<option value='Dairy Free'>Dairy Free</option>
<option value='Dairy Free (vegetarian)'>Dairy Free (vegetarian)</option>
<option value='Dairy Free (vegan)'>Dairy Free (vegan)</option>
<option value='Nut Free'>Nut Free</option>
<option value='Nut Free (vegetarian)'>Nut Free (vegetarian)</option>
<option value='Nut Free (vegan)'>Nut Free (vegan)</option>
<option value='Supplement Free'>Supplement Free</option>
<option value='Supplement Free (vegetarian)'>Supplement Free (vegetarian)</option>
<option value='Supplment Free (vegan)'>Supplement Free (vegan)</option>
</select>
<h2>Type of Day</h2>
<select>
<option value='none'>Select Option</option>
<option value='Non-Back-Load Day (10-Day Prep/CNS)'>Non-Back-Load Day (10-Day Prep/CNS)</option>
<option value='Back-Load Day (10-Day Prep/CNS)'>Back-Load Day (10-Day Prep/CNS)</option>
<option value='Non-Back-Load Day (CBL)'>Non-Back-Load Day (CBL)</option>
<option value='Back-Load Day (CBL)'>Back-Load Day (CBL)</option>
</select>
<h2>Cooking Level</h2>
<select>
<option value='none'>Select Option</option>
<option value='Minimal Cooking'>Minimal Cooking</option>
<option value='Moderate Cooking'>Moderate Cooking</option>
<option value='Maximum Cooking'>Maximum Cooking</option>
</select></br>
</div>
Here is the rest of the HTML code that assigns combinations of drop-down selections to a piece of text. I have only done one example:
<div class="margins2"><h1>Meal Plan...</h1>
<div id='results-container'>
<div class='Fat Loss No Requirements Back-Load Day (CBL) Moderate Cooking'> IT WORKS</div>
</div>
The second div class has 4 inputs. It looks strange without commas or separate '' marks but the tutorial doesn't include these and it works. Finally, here is some code from my EXTERNAL CSS file:
#results-container > div { display: none; }
Can anyone please assist me in fixing the issue of no text displaying or identify why this is happening? The JSFiddle link of the tutorial of what I want to achieve can be found here: http://jsfiddle.net/chnZP/
Many thanks
The problem seems to be in how the values in the drop-down lists are written. Because values are directly used as class names you are restricted in your choice of special characters.
Following the tutorial example, if you select alpha, blue and dog the script will turn this into a string ".alpha.blue.dog" and then select the elements containing those 3 class names using the .filter() method.
Because the string is sent to jQuery to manage it has to follow a strict syntax. This means you cannot using spaces, backslashes, parentheses (...and so on) in your class names because they will be parsed differently.
Editing the code slightly will fix it. http://jsfiddle.net/AjdHa/7/
<div id='select-container'>
<select>
<option value='none'>Select Option</option>
<option value='Fat_Loss'>Fat Loss</option>
</select>
<h2>Dietary Requirements</h2>
<select>
<option value='none'>Select Option</option>
<option value='No_Requirements'>No Requirements</option>
</select>
<h2>Type_of_Day</h2>
<select>
<option value='none'>Select Option</option>
<option value='Non-Back-Load_Day_CBL'>Non-Back-Load Day (CBL)</option>
</select>
<h2>Cooking Level</h2>
<select>
<option value='none'>Select Option</option>
<option value='Minimal_Cooking'>Minimal Cooking</option>
<option value='Moderate_Cooking'>Moderate Cooking</option>
<option value='Maximum_Cooking'>Maximum Cooking</option>
</select>
</div>
<div class="margins2">
<h1>Meal Plan...</h1>
<div id='results-container'>
<div class='Fat_Loss No_Requirements Non-Back-Load_Day_CBL Moderate_Cooking'>
IT WORKS
</div>
</div>
</div>

Categories