Code to detect option value does not work as expected - javascript

I was attempting to do some string comparisons in javascript. I have seen several tutorials and examples but they do not seem to work. I am missing something fundamental?
Attempt 1
function addAspect(aspect) {
var print = document.createElement('p');
var ptext;
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
Then I found this example to which all readers said it worked fine
function addAspect() {
var print = document.createElement('p');
var ptext;
var aspect = String(document.getElementById("aspectResult").value);
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
I also tried .toString() as well as the '===' exact match comparison.
Full code
<html>
<head>
<script type="text/javascript">
function addAspect()
{
var print = document.createElement('p');
var ptext;
var aspect = document.getElementById("aspectResult").value;
if (aspect == "Option1"){
ptext = document.createTextNode("This is option1");
}
print.appendChild(ptext);
document.getElementById("mainBlock").appendChild(print);
}
</script>
</head>
<body>
<form>
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
<input type="button" value="Check" onclick="addAspect()"/>
</form>
<span id="mainBlock">&nbsp</span>
</body>
</html>
Any suggestions?

First, a small introduction to how dropdowns work:
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
To read the selected value from the dropdown, you should do this:
var dropdown = document.getElementById('aspectResult'),
selectedValue = dropdown.options[dropdown.selectedIndex].value;
Then, you create the <p> element with a text node inside:
var p = document.createElement('p'),
txt;
if (selectedValue == 'Option1') {
txt = document.createTextNode('This is option 1');
}
Afterwards, you can append the newly created paragraph to the container of your choice:
var container = document.getElementById('mainBlock');
if (txt) {
p.appendChild(txt);
container.appendChild(p);
}
All together now!

If you are trying to add the ptext to the paragraph, you need to add two lines to the end:
function addAspect(aspect) {
var prnt = document.createElement('p');
var ptext;
if( aspect == "Option1" ) {
ptext = document.createTextNode("This is option1");
prnt.appendChild(ptext); // Add the text to the paragraph
document.body.appendChild(prnt); // Add the paragraph to the document
}
}

Your function creates a text node but then does nothing with it, so you code appears to do nothing at all. You need to append the text node to an element somewhere in the DOM:
document.body.appendChild(ptext);
Your full code appears to be working fine in IE9, Firefox 4 and Chrome 11. See http://jsbin.com/ekura5/.

Related

Vanilla JS - function to hide and show a div by clicking a button

I am having an issue; where when I click a button that takes the value from a drop-down list, it is supposed to show the div assigned to his matching value.
So far, my code do as intended, it shows the corresponding div, but then it reverts and hides it back 3 seconds after. It could be a simple mistake, your help is appreciated.
At the head:
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
function getGraphReq(){
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
My button:
<button onclick="getGraphReq()"></button>
The hidden div:
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
function getGraphReq(){
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
<select id="graph_req_ID">
<option value="Default">Default</option>
<option value="Default">foo</option>
</select>
<button onclick="getGraphReq()">Click me</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
I moved those variables into the function. Then when you execute the function it will assign correct values to the variables. Is this the expected output you need.
Not sure what the issue with your code, but is that the intended behaviour?
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
function getGraphReq() {
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
getGraphReq();
<select id='graph_req_ID'>
<option value='Default'>Default</option>
<option value='Other' selected>Other</option>
</select>
<button onclick="getGraphReq()">getGraphReq</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
If the element should not be visible onload and only by the click event then:
<div id="graph3" style="display:none">
Your code worked for me. Possibly something else in the file causing your issue. Hard to tell with what you posted.

Removing items from a to do list using Javascript

Attempting my first Javascript project, playing around with DOM to make a To-Do List.
After adding an item, how do i get the 'Remove' button to function and remove the item + the remove button.
Furthermore, after a new entry is made, the list item still stays in the input field after being added. How can it be made to be blank after each list item.
And yes i know my code is kinda messy and there is most likely an easier way to create it but I understand it like this for now.
Any help is greatly appreciated. Thanks
JSFiddle Link : http://jsfiddle.net/Renay/g79ssyqv/3/
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
node.appendChild(removeTask);
}
You can simply assign event:
removeTask.addEventListener('click', function(e) {
node.parentNode.removeChild(node);
});
http://jsfiddle.net/g79ssyqv/6/
Edited the Fiddle... just try this
FiddleLink (Should work now, button and p-tag will be removed)
HTML
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
JS
var row = 0;
function addText(){
var input = document.getElementById('inputTask').value;
if(input != "")
{
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
node.setAttribute("id","contentP"+row);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.setAttribute("onClick", "deleterow("+ row +");");
node.appendChild(removeTask);
row++;
}
else
{
alert("Please insert a value!");
}
}
function deleterow(ID)
{
document.getElementById('contentP'+ID).remove();
}
Greetings from Vienna
Use this
// +your code
.....
node.appendChild(removeTask);
// + modify
removeTask.onclick = function(e){
var dom = this;
var p_dom = this.parentNode;
console.log(p_dom);
var parent_node = p_dom.parentNode;
parent_node.removeChild(p_dom);
}

removeChild only works once

I have a test input form where a child select box is created depending on the value of one of the choices in the parent select box. Selecting any of the other choices in the parent select box should remove the child. It works, but only once. If the child select box is created a second time, then it is not removed by selecting one of the other choices.
Here is the code:
<html>
<SCRIPT LANGUAGE="JavaScript">
function createtext(){
var var1 = document.getElementById('s');
var var2=var1.value;
if (var2 == "American Express")
{
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
}
else
{
myform.removeChild(gift);
}
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="myform">
<SELECT id = "s" name="s" size=3 onChange="createtext()" ><OPTION>Visa Card<OPTION>Mastercard<OPTION>American Express</SELECT>
</form>
</html>
And here it is in action... http://www.crazyforstamps.com/test-form-6.htm
Try
var gel = document.getElementById('gift');
if(gel){
myform.removeChild(gel);
}
Update:
<!DOCTYPE html>
<html>
<head>
<script>
function createtext() {
var var1 = document.getElementById('s');
var var2 = var1.value;
if (var2 == "American Express") {
var selector = document.createElement('select');
selector.id = 'gift';
selector.name = 'gift';
selector.size = '2';
myform.appendChild(selector);
var option = document.createElement('option');
option.value = '0';
option.appendChild(document.createTextNode('Gift card'));
selector.appendChild(option);
option = document.createElement('option');
option.value = '1';
option.appendChild(document.createTextNode('Fully owned card'));
selector.appendChild(option);
} else {
<!--myform.removeChild(gift);
var gel = document.getElementById('gift');
if (gel) {
myform.removeChild(gel);
}
}
}
</script>
</head>
<body>
<form action="" method="get" name="myform">
<SELECT id="s" name="s" size=3 onChange="createtext()">
<OPTION>Visa Card</OPTION>
<OPTION>Mastercard</OPTION>
<OPTION>American Express</OPTION>
</SELECT>
</form>
</body>
</html>
Demo: Plunker
Assuming you have defined gift somewhere which I don't see it in the question.
Removing all child elements
var gift = document.getElementById("gift");
while (gift.firstChild) {
gift.removeChild(gift.firstChild);
}
Or another alternative is to simply assign innerHTML to an empty string
var gift = document.getElementById("gift");
gift.innerHTML = '';
First of all you have to keep in mind, that each browser has it's own js compiler. Some can use properties without getting browsers dom element via JS, by just referencing their name. But in order to write all browsers supported code, you have to keep in mind JS specifications.
In your current example on JSFiddle you have to always get your elements before you try to perform any actions on them.
var myform = document.getElementById('myform');
var gift = document.getElementById('gift');

how to make button insert tag in a textfield?

I'm trying to make multiple buttons that when clicked they add tags like <p></p> and <b></b> to a text-field. I have already figured out how to make it work like this:
<script>
function addtxt(input) {
var obj=document.getElementById(input)
obj.value+="<p></p>"
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body')">
but instead of having multiple scripts for every different button, I'd like to know if there is a way of the JS use the element value as obj.value. Is it possible?
EDIT: i found this other code online that's even better, how can i make this new code use the element value, is there any way?
function boldText(textAreaId, link)
{
var browser=navigator.appName
var b_version=navigator.appVersion
if (browser=="Microsoft Internet Explorer" && b_version>='4')
{
var str = document.selection.createRange().text;
document.getElementById(textAreaId).focus();
var sel = document.selection.createRange();
sel.text = "<b>" + str + "</b>";
return;
}
field = document.getElementById(textAreaId);
startPos = field.selectionStart;
endPos = field.selectionEnd;
before = field.value.substr(0, startPos);
selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
field.value = before + "<b>" + selected + "</b>" + after;
}
You may pass this to your onclick handler, and then access it's value within your function:
<script>
function addtxt(input, button) {
var obj=document.getElementById(input);
obj.value+=button.value;
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body', this)">
<input type="button" value="<b></b>" onclick="addtxt('body', this)">
Here is an example with a specific div that receives the code javascript produces.
I don't recomend adding it to a div with id body, because that word is reserved for html structural elements, so I called the destination div "addHere".
Javascript
function addtxt(e) {
console.log(e)
var dest = document.getElementById("addHere");
dest.innerHTML = e.value;
}
HTML
<input type="button" value="<p>Text</p>" onclick="addtxt(this)">
<div id="addHere"></div>
fiddle here

Removing a div as user removes input in javascript

I'm trying to take user input, match result, display result in drop-down, and then click on a name from drop down to display it. I've been able to display result in drop-down using innerHTML but it wasn't clickable so now I'm dynamically creating Div elements. However, I'm not sure how to clear the list when user presses backspace. I was previously doing that with document.getElementById('placeholder').innerHTML="" statement. Here's what I've done so far. The code in comments is for when I was displaying the drop down menu using innerHTML:
HTML code:
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.."
onkeyup="test()"/>
<div id="lc">
<!--- <p id='placeholder'> </p> -->
</div>
<script type="text/javascript" src="js/filter.js"></script>
</body>
JS code:
// JavaScript Document
s1 = new String()
var myArray = new Array();
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
function test() {
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex) {
var flag=0;
//document.getElementById('placeholder').innerHTML="";
for(i=0; i<myArray.length; i++) {
//if(myArray[i].charAt(0).indexOf(s1) != -1) {
if(myArray[i].match(myRegex)) {
flag = 1;
//document.getElementById('lc').style.visibility = 'visible';
//document.getElementById('placeholder').innerHTML += myArray[i]+"<br/>";
var element = document.createElement("div");
element.appendChild(document.createTextNode(myArray[i]));
document.getElementById('lc').appendChild(element);
}
//}
if (flag == 0) {
document.getElementById('lc').style.visibility='hidden';
}
}

Categories