Why Isn't My split() Delimiter Acknowledged? - javascript

Just beginning learning JavaScript; writing some calculators with relatively basic functions. I found the need to put multiple variable values in an option tag of a drop-down menu, and after researching I figured it would be easiest to put them in one string, then split them with the split() function, but regardless of the delimiter I specify, it acts as if there is none, and splits each character individually. Why?
<select name="fuel" onChange="document.scalc.fuel.value=document.scalc.fuel.value.split(',')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
</select>

Cᴏʀʏ has made some good points. Additionally, you will find it helpful to have your browser's JavaScript console open while you are testing your JavaScript so that it can show you any errors it encounters.
I could not get your example code to do anything at all - perhaps you have shortened it a little bit too much.
Your page could perhaps look something along the lines of
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Example</title>
<script>
/* TODO: Give this function a meaningful name. */
function x(srcId, targetId) {
// Get reference to the source element
var src = document.getElementById(srcId);
// Make sure it is a select element
if (src.nodeName.toLowerCase() === "select") {
var target = document.getElementById(targetId);
// Put the first part of the source's value in the target
target.value = src.value.split(",")[0];
}
}
</script>
</head>
<body>
<form id="scalc">
<select id="fuel" onChange="x('fuel', 'result')">
<option value="199x1,50">cu/ft Natural Gas(Via Storage Tank Burner, 65% Efficient)</option>
<option value="50x2,60">cu/ft Natural Gas(Via Super Burner, 70% Efficient)</option>
</select>
<input id="result" type="text" readonly="readonly" />
</form>
</body>
</html>
References:
<meta charset='utf-8'> vs <meta http-equiv='Content-Type'>
Best Practice: Access form elements by HTML id or name attribute?
How can javascript determine the type of an html element?
Also useful: W3C Markup Validation Service

Related

Use document.getElementById to retrieve a value

I am tring to retrieve the language value of my page, FR for French or ENG for English.
I am using document.getElementById("contentzone").innerHTML; to retrieve my data
Unfortunatly the html element lang is always=en, that's why I have to find an other way...
that returns
<span style="display: none;">IE BUMPER</span>
<script type="text/javascript" src="/jquery.tools.min.jsdbx?FRv=03-10-2015_0442"></script>
How I can retrieve the src url? (/jquery.tools.min.jsbx?FRv=03-10-2015_0442)
I have to retrieve "FR" which is the current language of my user, after I can parse the data and just get FR.
I've an other element on my page which displays the current language.
The html page structure is:
<html class="ltr chrome" lang="en">
<head> </head>
<body>
<div class="my_site_layout">
<div id="topzone">
<div id ="conn-infos">
<form class="conn-infos">
<div class="login">
FR
How I can access to this data (the string equal to FR) in Javascript? Because I think my first method with document.getElementByID to retrieve the name script is dirty.
Using a combination of the previous answers, I recommend
document.documentElement.getAttribute('lang');
document.documentElement refers to the <html> element of the page. .getAttribute() is used to retrieve an HTML attribute. If the attribute were to be actual text in an element. Your question which I felt wasn't to clear mentioned that there was an element that displayed the language :
document.getElementById('element').innerHTML.trim().toUpperCase()
Possible this could work:
document.getElementsByClassName('login')[0].innerHTML.trim().split(' ')[0].toUpperCase();
getAttribute() Reference
HTML Selectors
There might be better ways to do this, but the quickest approach that comes to mind is to use getElementsByTagName.
var x = document.getElementsByTagName("html")[0].getAttribute("lang");

Call javascript from XForms action

I am experimenting with XForms and trying to dynamically load javascript, but cannot figure it out.
I am presenting a simple example - that is just an input field and button that loads the javascript:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xf="http://www.w3.org/2002/xforms"
xmlns:ev="http://www.w3.org/2001/xml-events" >
<head>
<title>Hello World in XForms</title>
<xf:model>
<xf:instance xmlns="">
<data>
<firstName/>
</data>
</xf:instance>
</xf:model>
<script type="text/javascript">
var myFunction = function(){
var name = document.getElementById("firstName").value;
alert("Hello " + name + "!");
}
</script>
</head>
<body>
<xf:label>Please enter your first name: </xf:label>
<xf:input ref="firstName" id="firstName">
</xf:input>
<br />
<xf:trigger>
<xf:label>Click me!</xf:label>
<xf:action ev:event="DOMActivate">
<xf:load resource="javascript:myFunction()" />
</xf:action>
</xf:trigger>
</body>
</html>
So in my script I am trying to get the value from the input box and then show an alert box with concatenated string. Currently, I get "Hello undefined!"
Do you have an idea how to get the value from the firstName xf:input with Javascript?
I know how to do it with XForms only, but this is sort of a proof of concept.
On a side note - I am using XSLTForms, so the XForms runs on the client.
Another hint might be in the fact that XSLTForms transforms the xf:input into several nested span elements with a <input type="text"> element, but that input element does not have a name or id.
With XSLTForms, there are different possibilities...
If you want to access the value of the corresponding HTML input, I would suggest document.getElementById("firstName").xfElement.input.value.
You could also use the node property to get the value stored in the bound node.
Don't hesitate to browse DOM with a debugger to find how to get things from XSLTForms!
--Alain

JQuery Masked Input plugin doesn't work

I've added a JQuery Masked Input plugin to my Web project but it's not working at all.
The plugin can be found here: http://digitalbush.com/projects/masked-input-plugin
I've included JQuery libray and the Masked Input plugin to my JSP, and called the mask function for my html <input> element:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- JS --->
<script src="js/jquery-1.11.0.js"></script>
<script src="js/masked-input-jquery-1.3.1.js"></script>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
$("#name").mask("99/99/9999");
</script>
<form id="" method="" action="">
<div>
<label for="name">
Name<b style="color: red">*</b>
</label>
<input name="studentName" maxlength="255" autofocus="autofocus" type="text" id="name"/>
......
When I access my JSP, even before typing anything on the text field, the following appears on Chrome console:
Uncaught ReferenceError: iMask is not defined
Can you help me? Is there anything wrong with the code?
This may or may not fix your current problem, but your call to .mask will not work because it runs before the rest of the page (where your input fields are) is parsed.
You need to wrap the call in the jQuery document ready function:
$('document').ready(function() {
$("#name").mask("99/99/9999");
});
This tells the script to wait until the page is loaded enough for the browser to know about the input fields in the document.
As an additional comment best practices say to put all script tags (with some exceptions) just before the closing body tag.
Otherwise you should move the script tag into the head with the rest of the tags.
That's because jQuery is downloaded but not ready yet. Try
$(function(){
// your code goes here
});
You need to wrap your jQuery in document.ready as several folks have already mentioned. You also need to adjust your mask to match your desired input. I assume you only want alpha characters allowed. This JSFiddle shows you an example with that assumption.
If you want alphanumeric just replace 'a' with '*'. Below is the jQuery Code:
$(function() {
//The # of "a"s you enter depends on your max field input
//The "?" makes any character after the first one optional
$("#fname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
$("#lname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
});
It should also be said that using the masked input plugin may not be the best option to validate a name as it is meant for fixed width inputs. If you want to validate alpha characters of varying lenghts consider doing something like this instead.

How to fill <select> with text on <input type="text"> using Javascript?

I want to fill and submit a form like below:
<form action="http://www.test.com/school" method="post">
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="submit" value="submit" id="submitday">
I don't want to select from option so I have to create another form.
<form action="http://www.test.com/school" method="post">
<input type="text" name="days">
<input type="submit" value="submit" id="submitday">
When I want to choose Wednesday, I need to type the value 3 in a text box then click submit. It works.
But I want to know if any method that can make me just type Wednesday in text box and not the value and post it without any problem?
Your question isn't well defined enough and having an explicit goal always helps.
1.) Even though we're pretty much if not outright beyond the point where it's important to use id="same_as" name="same_as" having the same values I still highly recommend this practice (old Internet Explorer bug). You'll want to make good use of the label element (clicky clicky) as it gives users more area to click to give focus (element, checkbox, text, etc).
2.) You'll want to use the in operator to discover what tools you have available...
XHTML
<textarea id="dom_methods"></textarea>
JavaScript
for (i in document.getElementById('select_element_id')
{
document.getElementById('methods').value = document.getElementById('methods').value+'\n'+i;
}
This will let you discover different methods/functions/objects/etc that are associated with in example the select element. Keep in mind that each object may have it's own children. You can do...
for (i in window) {}
for (i in window.document) {}
for (i in document.getElementById('select_element_id')) {}
Good resources including Mozilla Developer Network here...
https://developer.mozilla.org/en/
My absolute biggest piece of advice is do not use frameworks as you will quickly veer off from learning the actual language and immediately inherit some high level issues you will not become aware of. People posting dollar signs ($) in JavaScript posts are usually good give-aways that they have not answered your question unless you have explicitly asked for a framework related answer.
If you revise your question and reply to my answer I'll be happy to append my answer to apply more directly to what you're trying to accomplish.
PART TWO
If you want to create an element you should use the createElement method...
Create the element and give it the value you want...
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
IMPORTANT! JavaScript has QUIET errors that you will battle for days before posting about them and someone casually pointing them out. So be exceptionally wary of using short names for variables (e.g. do not use var in = ''; as "in" is an operator and will cause a silent error) where your code simply won't execute or do odd stuff.
Now you have some VALID choices for putting this new element in to the page...
1.) Using appendChild will put the element at the end of the parent container...
document.getElementById('form_id').appendChild(d);
You should use fieldsets (usually one is fine) as a direct child to a form element...
<form action="" method="post">
<fieldset>
<!--everything form related goes here -->
</fieldset>
</form>
...in which case you could do the following (to help you get comfortable with examples and see them actually work before you)...
document.getElementById('form_id').getElementsByTagName('fieldset')[0].appendChild(d);
Notice the [0], it refers to the first fieldset element, if there were two and you wanted to append the new element in to the second you would use [1] (and [2] for the third and so forth). Also if the page only includes a single form and a single fieldset you could drop the first part (just so you can see how things are constructed)...
document.getElementsByTagName('fieldset')[0].appendChild(d);
2.) You'll usually want to use insertBefore...
var f = document.getElementById('form_id');
var element_parent = f.getElementsByTagName('fieldset')[0];
var element_before = f.getElementsByTagName('select')[0];
parent_element.insertBefore(d,element_before);
A little more information here...
https://developer.mozilla.org/en/insertBefore
NEVER EVER FOR ANY REASON USE INNERHTML!!! Lazy programmers use it all the time and fail to realize that it does NOT correctly register the DOM so elements associated with that proprietary Microsoft JScript method will NOT be seen when you try to work with them. For this reason alone you should avoid using frameworks such as jQuery as they jump to use the easiest things. Easy doesn't get the job done, easy makes the job look done long enough to make a single paycheck and then if you don't one day end up rewriting ALL of your code in that given area (long after you remember working with it and what you were trying to do) you'll be in a world of hurt.
PART THREE
JavaScript is an EVENT driven language, events are DOM based. The DOM and JavaScript are different things very closely tied together.
You can read more about DOM events here...
https://developer.mozilla.org/en/DOM/event
...and there is a good list of DOM events here...
http://en.wikipedia.org/wiki/DOM_events#HTML_events
In order to take advantage of the code you need to determine the event that best fits with your goal. Are you trying to do this when the form is submitted? That would be onsubmit. Are you trying to do this when the page loads? That would be onload.
Generally you can reuse events endlessly though you can only execute the onload event once.
If you visit my site and look at the JavaScript code you'll notice THREE things...
1.) An index.js file that is nothing but functions.
2.) An onload.js file with limited number of global variables (variables defined outside of a function) and the anonymous onload function.
Since you can only execute the onload event once if you want to do multiple things (e.g. execute multiple unrelated functions) you can use an anonymous function which is simply a function without a name...
window.onload = function()
{
my_func1();
my_func2();
my_func3();
}
Keep in mind that you should always keep script elements inside of the <head> element and not the <body> element otherwise it will lead you down a path of poor coding practices.
So if you create a standalone test file it may look something like this...
example.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test Page</title>
<script type="application/javascript">
//<![CDATA[
function form_days()
{
var d = document.getElementById('days');
var input_day = document.createElement('input');
input_day.setAttribute('id','days');
input_day.setAttribute('name','days');
input_day.setAttribute('type','text');
input_day.setAttribute('value',d.options[d.selectedIndex].text);
d.parentNode.insertBefore(input_day,d.nextSibling);
}
function get_methods(o)
{
var m = document.getElementById('dom_methods');
var dom_list = new Array();
for (i in o)
{
dom_list.push(i);
}
dom_list.sort();
for (var i=0; i<dom_list.length; i++)
{
m.value = m.value+dom_list[i]+'\n';
}
}
window.onload = function()
{
form_days();
get_methods(document.getElementById('days').options[document.getElementById('days').selectedIndex]);
}
//]]>
</script>
<style type="text/css">
label {border: #000 dotted 1px; padding: 0px 2px 0px 2px;}
label:hover {border: #000 solid 1px;}
textarea {height: 500px; width: 400px;}
</style>
</head>
<body>
<form action="http://www.test.com/school" method="post">
<fieldset>
<label for="days">Day:</label>
<select id="days" name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<div><textarea id="dom_methods"></textarea></div>
<div><input type="submit" value="submit" id="submitday" /></div>
</fieldset>
</form>
</body>
</html>
You should be able to copy-and-paste this to a file, name it example.xhtml. It's all functional, tested and working at the highest standards. Keep in mind that Internet Explorer 8 and older is not capable of XHTML (application/xhtml+xml) or comprehending the CORRECT media type/mime for JavaScript which is application/javascript so if you require backwards compatibility using text/javascript on script elements is not valid though will work.
well, you could change the values of the options, for example using jquery like this:
$('select[name=days] option').each(function(){
$(this).val($(this).html());
});​
http://jsfiddle.net/RCevC/
I think you're trying to update a text input when a user picks a selection from the dropdown? Try this:
html:
<select name="days">
<option value="2">Monday</option>
<option value="1">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
<input type="text" id="your_input" /> <!-- I added this field to your code -->
<input type="submit" value="submit" id="submitday"> ​
javascript (jquery)
$('select[name=days]').change(function(){
$('#your_input').val($(this).val());
});​
http://jsfiddle.net/z3peu/2/

I need help with DOM in javascript

I am suppose to Create a form that gives the user 3 different options to change the background color of the page. When the user clicks one of the options, the background color changes to match.And also create a div with some basic text to start out. Create a form that has a textarea. Use document.getElementById('yourelementid') to both find the value of the textarea and to change the basic text created in the div. (Hint: user innerHTML) Now I know how to do the form but i dont know how to get it to change the background when the user clicks that button.I am not really understanding how to use the innerHTML at all. If someone could explain or give me some website on how to understand this. Thank you.
OK this is what I have so far and I am not still yet understanding it...
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http:www.w3.org/1999/xhtml">
<head>
<title>background-color</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<script language="javascript" type="text/javascript">
function changeBackgroundColor(objDivID)
{
var backColor = new String();
backColor = document.getElementById(objDivID).style.backgroundColor;
if(backColor.toLowerCase()=='#A20000C')
{
document.getElementById(objDivID).style.backgroundColor = '#DF64BD';
}
else
{
document.getElementById(objDivID).style.backgroundColor = '#FFDD73';
}
}
</script>
</head>
<body>
<h3>Change background color to:</h3>
<div id="div1" style="background-color : #A2000C">
<p><input type="radio" name="color" value="red" />Red<br />
<input type="radio" name="color" value="pink" />Pink<br />
<input type="radio" name="color" value="yellow" />Yellow<br />
</div>
<input type="button" value="click here"onclick="changeBackgroundColor('div1')" />
</body>
</html>
i am still not sure why my box aint that big and is not chaning colors right i still have to have a box on there too. To ask to change the text of the color.
You should add an event handler on the color-change options, like this (assuming it's an select box):
<select id="colorSelect">
<option value="red">red</option>
<option value="green">green></option>
</select>
document.colorSelect.onchange = function(){
document.elementToChangeColor.style.backgroundColor= this.value;
}
here is how you would set the background color of the page to the value of the text area:
document.bgColor=document.getElementById('yourelementid').value;
InnerHTML is basically everything between two tags (hence inner HTML):
<div>
Now to change the background, you would get the value from the form element and then write something like this to change a background color.
document.getElementById('your_element_id').style.backgroundColor = formElementValue
The Mozilla documentation describes innerHTML fairly well. You may want to read through that page.
The innerHTML property of a DOM object provides as text the HTML contents of that object. So if you have the HTML:
<div id="myID"><span>Some text here!</span></div>
And the javascript:
var theHTML = document.getElementById('myID').innerHTML;
alert(theHTML);
Then you will see <span>Some text here!</span>.
If you set the innerHTML property to an HTML string, it will change the contents of the value. Given the HTML above if you have the following javascript:
var myDiv = document.getElementById('myID');
myDiv.innerHTML = '<span>Now this is some other text</span>';
Your div with the ID myID will change to show a span containing "Now this is some other text".
For changing the background color, look into changing the CSS attribute on the body. This question will help you see how this can be done. You will want to investigate document.body.style.
I would use jQuery:
function selectionMade(color) {
var body = $('body');
body.css('background-color', color)
var divWithSomeText = $('<div/>').Text = 'Some Text';
body.Add(divWithSomeText);
}
jQuery makes the things you are trying to do really easy. If I were you I would pick up use of the library now so you can use it again in the future.

Categories

Resources