Javascript selectedindex not working - javascript

I have a code that should allow me to show div id='yestext' when 'Yes' is selected in the dropdown box. Yet this is not working. I don't know what isn't working, but something clearly isn't.
JS
function text() {
if (document.getElementById("text").selectedIndex == "0") {
document.getElementById("yestext").style.display = "block";
}
else {
document.getElementById("yestext").style.display = "none";
}
}
HTML
<select id='text' onchange='text()'>
<option value="0">Yes</option>
<option value="1">No</option>
</select>
<div style='display:none;' id='yestext'>
What text would you like displayed?
<input type='text' class='text' name='type' value size='20'/>
</div>
Here is the JSFiddle containing my code: http://jsfiddle.net/4w9fh/

Your code is fine. The You had the JSFiddle set to run your code in OnLoad and it wrapped the text() function so it did not add it to global namespace. I fixed it by moving the js to the head and now it works.
I also called the text() function when the html finishes loading to take in account the browser remembering the last choice.
Here is the updated code.
http://jsfiddle.net/4w9fh/2/

Related

How to access the javascript variable inside html tags

I wanted to added javascript variable inside html code.
Here is my code:
<select id="currentrun" name="currentrun" >
<option value=""><script>selectedrun</script></option>
</select>
and my js function
var currentrun="";
var selectedrun="";
function setCurrentRun()
{
currentrun = document.getElementById("runlist");
selectedrun = currentrun.options[currentrun.selectedIndex].value;
}
But this doesn't work.
Can anyone help me to do this.
Thanks in advance.
You don't have to run the script like that.
The value of the currentrun can be retrieved as:
document.getElementById('currentrun').value
And for completeness, if you want to trigger a JavaScript function call each time the selection is modified, do this:
<select onchange="my_function();">
<option>...</option>
</select>
It seems like you are trying to set the text of the option element with javascript. Here is one way you can do it using the id of the element to get it and then set the text property of the element to your javascript variable:
<select id="currentrun" name="currentrun" >
<option id="currentoption" value=""></option>
</select>
<script>
document.getElementById("currentoption").text = selectedrun;
</script>
Be sure to put any necessary javascript that declares and sets the selectedrun variable before the above script.

Javascript only works when assigning variable to function?

I'm working on a project that uses bootstrap. In the project, some additional functionality was needed so that when a user selects a certain option from the drop down it hid/showed certain content. It look as follows:
<select class="form-control" id="state-text" onChange="test()" name="selected-state" >
<!-- Select options here -->
</select>
Then I had the JS as follows:
function test()
{
// Code here
}
Now this didn't work, and would throw an error that function test was not defined. However, when I repalced it with:
test = function test()
{
//Code here
}
it worked as intended. I don't understand why one worked and the other didn't? Does it maybe have something to do with the other JS files that the bootstrap file is importing?
As you tagged the question as jQuery here's a fiddle I made quickly
http://jsfiddle.net/nYmF8/
markup
<select class="form-control" id="state-text" name="selected-state" >
<option value="a">A</option>
<option value="b">B</option>
<option value="b">C</option>
</select>
jquery
$(function(){$('#state-text').on('change', function () {
alert('changed value to to '+$(this).val());
});});
maybe you forgot to put your jQuery in the document ready function?
try to avoid adding JS in the middle of your HTML. Try doing that instead:
$(document).ready(function() {
$('#state-text').on('change', function () {
//Code Here
});
});
I am assuming here that you are using jQuery since it's a requirement for bootstrap. If not, let me know.

append() text value to div onclick()

I am creating an instant messenger using jquery and am having trouble taking the message typed into the message field after clicking the "send" button
I have the html
<body>
<div class="main-window">
<div class="chat-screen"></div>
<div class="bottom-wrapper">
<input class="text-bar"></input>
<input type="button" value="Send"class="send-btn">Send</input>
</div>
</div>
<body>
and I have tried to append it using this jquery
$('.send-btn').click(function() {
$(".text-bar").text().appendTo(".chat-screen");
});
But it doesn't seem to work. Can someone please point me in the right direction?
JSFiddle
you need .val()
change
$(".text-bar").text()
to
$(".text-bar").val()
you code becomes
Fiddle DEMO
use .append()
$('.send-btn').click(function () {
$(".chat-screen").append($(".text-bar").val());
});
Clear Textbox and new chat in new line.
$(document).ready(function () {
var chat_screen = $(".chat-screen");
var text_bar = $(".text-bar")
$('.send-btn').click(function () {
chat_screen.append(text_bar.val() + '<br/>');
text_bar.val('');
});
});
Updated Fiddle DEMO
The .text() (and correct .val()) functions return strings, not jQuery objects, and therefore don't have the appendTo() function available on them. You'll need to do this instead:
$('.chat-screen').append($('.text-bar').val());
Also make sure that, if the script is in the <head> of your HTML page, or comes before the actual HTML of the elements, you wrap it in a DOM ready handler:
$(document).ready(function() {
$('.send-btn').click(function(){
$('.chat-screen').append($('.text-bar').val());
});
});
And, of course, check that jQuery is being loaded correctly (it wasn't in your jsFiddle at all).
Since this is going to (probably) be running a lot of times, you'd want to cache the selectors for the chat screen and the text input, like so:
$(document).ready(function() {
var $chatscreen = $('.chat-screen'),
$textbar = $('.text-bar');
$('.send-btn').click(function(){
$chatscreen.append($textbar.val());
$textbar.val('');
});
});
Updated jsFiddle
Here is you fiddle updates: jsfiddle
Use val() instead text()
$('.send-btn').click(function(){
//$(".text-bar").val().appendTo(".chat-screen");
$(".chat-screen").append($(".text-bar").val())
$(".chat-screen").append('<br />')
});
please see http://jsfiddle.net/K95P3/15/
Several issues:
Add space between value and class attributes in input
Change .text() to .val() - inputs don't have text nodes, just values
Use $('.chat-screen').append($(".text-bar").val());
Make sure you have jQuery included
See updated fiddle http://jsfiddle.net/K95P3/11/
Try this.
$('.send-btn').click(function(){
$('.chat-screen').append($(".text-bar").val());
});
Actually, you really should append an html tag, not just text. I mean, you could, but shouldn't.
What i would recommend is this:
Create a base container for a message like:
<div class="message-container" style="display:none;">
<span class="message"> </span>
</div>
You then clone this container, stuff it the value of the input in the chat and append it to the chat screen.
The code could be something like:
$('.send-btn').click(function(){
var container = $('.message-container:hidden').clone(true).show();
container.find('.message').text($(".text-bar").val());
container.appendTo($('.chat-screen'));
});
Append text and dropdown value sametime
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
//var x=$("#cars option:selected").text();
//var y=$("#bus").val();
//alert(''+x+' '+y+'');
$(".chat-screen2").append($("#cars").val()+'<br/>');
$(".chat-screen").append($("#bus").val()+'<br/>');
$("#bus").val('');
});
});
</script>
</head>
<body>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<input id="bus" type="text">
<button type="submit">submit</button>
<br><br>
<div class="chat-screen2" style="float:left;"></div>
<div class="chat-screen" style="float:left;margin-left:10px;"></div>
</body>
</html>

jQuery variable issues

My attempt to find the name of the div holding a select box, then put this div into a variable which is used elsewhere in my jQuery code, does not seem to be working. Another piece of code is appending extra divs to the page, these have select boxes of class .parent within them. However many extra divs I append, the code below always appends to the first div added, even though checking through a browser the div structure works as expected. I'm new to jQuery so don't know if I'm missing something obvious, but I'm pretty sure the variable div below should be redefined each time .parent element is changed as it is part of the variable's definition. When I've run an alert just to check the variable name it is always defined as sub_cat_1. This is correct for the first appended div class of show_sub_categories but thereafter it should be sub_cat_2, sub_cat_3 etc incrementing. As said the select boxes are definitely in the correct divs on the page, so I can only asssume I'm missing something simple with this bit of the code below. (basic html at bottom for reference)
$('.parent').livequery('change', function () {
var div = $(".parent").closest("div").attr("id");
$(this).nextAll('.parent').remove();
$(this).nextAll('input').remove();
alert(div);
$('#' + div).append('<img src="images/system/loader2323.gif" style="float:left" id="loader" alt="" />');
$.post("get_chid_categories.php", {
parent_id: $(this).val(),
}, function (response) {
setTimeout(function () {
finishAjax(div, response);
}, 400);
});
return false;
});
This is just to show you the basic structure of the divs being appended.
<p id="add_field"> … </p>
<div class="show_sub_categories">
<div id="sub_cat_1">
<select class="parent" name="search_category"> … </select>
<select class="parent" name="sub_category"> … </select>
</div>
</div>
<div class="show_sub_categories">
<div id="sub_cat_2">
<select class="parent" name="search_category"> … </select>
<select class="parent" name="sub_category"> … </select>
</div>
</div>
I've put a very simplified version of this at http://www.0urs.com/fiddle/experience1.php just to illustrate the physical location of the appended select boxes.

Selection from dropdown list that loads a div into another div (IE8, Chrome)

I'm just starting out to learn javascript and it seems like I have ran into a wall regarding drop down list and loading a div into another div upon selection. I'm setting up a drop down box that is nothing more then a list of different divs with embedded videos. When selected I want the div to be loaded into the main div
Now the code I have below works on Firefox, but not on Chrome or IE8. I've searched and read that IE8 and Chrome doesn't like having onclick within the option tag. If true, how do I go about making the code below useful on IE8 and Chrome?
What I've tried so far:
Using onsubmit and adding a submit button - couldn't get it to work
Using onchange - Couldn't get it to work!
At this point I wouldn't be surprised if I'm just misusing the event handlers and possibly my function not going far enough, but I've been stuck for hours trying different things to no avail.
Any Suggestions?
<div id="videodiv" style='display: none'> Some embedded video code</div>
<div id="videodiv2" style='display: none'> Different Embedded video code</div>
<div id="videoPlayback"> The div where all the embedded videos will end up loading</div>
<script type="text/javascript">
function playVideo(sourceId, targetId) {
if (typeof(sourceId)=='string') {sourceId=document.getElementById(sourceId);}
if (typeof(targetId)=='string') {targetId=document.getElementById(targetId);}
targetId.innerHTML=sourceId.innerHTML;
return false;
}
</script>
<select><option selected>Please Select...
<option onclick='return playVideo("videodiv2","videoPlayback")'>Video Div2>
Here is a version that works; it uses jQuery just for convenience, but you can use standard javascript (pass me the term) without problems.
http://jsfiddle.net/MisterJack/qw6DL/
The main issue was that the HTML was wrong, especially the select tag wasn't closed, as well as the option tag.
What I did is simply bind the onChange event of the select (not the option!) to a function that updates the content.
This function searches the option which is currently selected, reads its value attribute (which is the id of the div to load content from) and updates the content accordingly.
$('select').change(function() {
var domElement = $('select option:selected').attr('value');
$('#videoPlayback').html($('#' + domElement.toString()).html());
});
try this with jquery:
<div id="videodiv" style='display: none'> Some embedded video code</div>
<div id="videodiv2" style='display: none'> Different Embedded video code</div>
<div id="videoPlayback"> The div where all the embedded videos will end up loading</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var sourceDiv;
var targetDiv;
function playVideo(sourceId, targetId) {
sourceDiv=$("#"+sourceId);
targetDiv=$("#"+targetId);
targetDiv.html(sourceDiv.html());
}
</script>
<select id="videos"><option selected="selected" >Please Select...</option>
<option value="videodiv">Video Div1</option>
<option value="videodiv2">Video Div2</option>
</select>
<script type="text/javascript">
function videoChanged() {
//var videoSelectList = $('select#videos');
var selectedValue = $('#videos').val();
//alert(selectedValue);
if (selectedValue != 'Please Select...') {
playVideo(selectedValue,'videoPlayback');
}
}
$(function() {
//alert('my alert');
$('select#videos').change(videoChanged);
});
</script>

Categories