first of all i am a beginner in javascript, a really big beginer
Can someone give me a hint on this?
I have a form, on the form i have a radio button.
And i would like to that if the radio is set yes , it would show the value of it on another page.
And i would like to get the value by the input name
is it possible?
I'm not asking to write my code, but just an example for a start.
i was tried with this just for a test
<input type="hidden" name="the_name" value="yes">
if(the_name.element == 'yes') {
alert('cool');
}
the_name.value, not the_name.element
You can use getElementsByName() for accessing the elements value via the input name. But as a standard and since it helps load off the DOM we use getElementById() instead of the name. Also you can start from here -> http://eloquentjavascript.net/
You can reference the form using:
document.forms[formName or formId].elements[element-name];
However, name is not necessarily unique in the document. If there is only one element with the name, then only one is returned. If more than one have the same name, then you will get a collection (a bit like an array) and you will have to iterate over them to find the one you want.
You can also use document.getElementsByName, which always returns a collection. So you can do:
var elements = document.getElementsByName('the_name');
// get the one with value 'yes'
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (elements[i].value == 'yes') {
return elements[i];
}
}
You will also need to be careful of case sensitivity, you might want to use toLowerCase() on the value first, or use a case insensitive regular expression:
e.g.
var re = /yes/i;
...
if (re.test(elements[i].value)) {
// value is Yes or YES or yeS or ...
<input type="hidden" name="the_name" id="the_name" value="yes"> <!-- id added -->
if(formName.the_name.value == 'yes')
{
alert('cool');
}
OR better (since you are not accessing the elements by global names)
var element = document.getElementById("the_name");
if(element.value === 'yes')
{
alert("yes, it is");
}
Related
i want to check the first element of multiple radiobutton groups.
I'm using Firebug, which is why i do not want, yes i know there is firequery, but there must be a way like they did it in the old days :)
Any help yould be great, thx in advance.
Loop backwards over document.getElementsByTagName('input') and set checked to true if type is equal to "radio".
If you try to check multiple buttons in the same group, the last one will hold.
Thus, looping backwards will end up checking the first option in each group.
Update
Feeling a bit silly here, you said you were using Firebug, and thus Firefox, and so we have querySelector available. Thus checking the first radio button in any given group is a one-liner:
document.querySelector('input[type="radio"][name="theGroupName"]').checked = true;
Live example
querySelector returns the first matching element, and so the above will return the first input element with type="radio" and name="theGroupName". Then we just set its checked to true.
Granted that doesn't do the first of all groups, but it gives you more control and is (again) a one-liner — handy for Firebug.
Original answer
You can use getElementsByTagName to get all input elements in document order. Then loop through them, only processing the ones with type="radio" and remembering the last name you encoutered; mark checked = true for the first of each name.
E.g.:
var inputs = document.getElementsByTagName('input');
var lastName, index, input;
for (index = 0; index < inputs.length; ++index) {
input = inputs.item(index);
if (input.type.toLowerCase() === "radio") {
if (input.name !== lastName) {
lastName = input.name;
input.checked = true;
}
}
}
Live example
If you want to limit that to some container, you can use the element version of getElementsByTagName.
I am a javascript novice. I'm trying to build a complex form whilst simultaneously learning JS and JQ... not an easy task. This code works, but I don't know what two lines do, so I thought I'd ask here.
What this code does is loop through an array to see if a radio button checkbox has been checked as yes or no. It runs at initialization when a user revisits the form he/she is filling out. The code is attached to a textfield element which unhides if myRadioButton is yes, stays hidden if no.
I do not know what lines 5 and 6 do (beginning with the second if statement). Would some knowledgable person please be so kind as to transcribe those lines into a couple of sentences, kind of like they do in tutorials? I would really appreciate it!
var rbVal = "";
var rbBtn = JQuery("[name=\"myRadioButton[]\"]");
for (var i = 0; i < rbBtn.length; i++)
if (rbBtn[i].checked) {
if (rbVal != "") rbVal += ",";
rbVal += rbBtn[i].value;
}
if( rbVal != "yes" ){
doSomething;
}
else {
doSomethingElse;
}
That code is checking all radio buttons with a shared name myRadioButton[], to make sure that if one is checked its value is added to rbVal string seperated by a comma.
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); <- gets an array of radio buttons
for (var i = 0; i < rbBtn.length; i++) <- loops through every button in that array.
if (rbBtn[i].checked) { <- if the button is selected it then checks to see if rbVAl is already set. <-- Either you are missing something here or it is faulty program
Line 5 compares the value of rbVal to an empty string (""). If rbVal is not equal (!=) to an empty string, a string containing a comma character is appended to rbVal. So for example, if rbVal contains the string "hello", after the execution of that line, it will contain "hello,".
Line 6 then appends the value of rbBtn[i].value to rbVal. rbBtn is an array-like object (in fact, it appears to be an instance of jQuery containing whatever was matched by the selector), and when you access a jQuery object with array syntax like that, you get the actual DOM element rather than another jQuery object, so the value property is the actual value property of the DOM element (by the look of it, that will be a radio button).
So, if you have a radio button like this:
<input type="radio" value="someVal">
then your loop would result in rbVal == "someVal".
If you have two radio buttons:
<input type="radio" value="someVal">
<input type="radio" value="anotherVal">
then you would end up with rbVal == "someVal,anotherVal". You can see from that what the overall purpose of that loop is - to build up a comma-separated string of the values of all the radio buttons matched by the jQuery selector.
Curiously, this is using jQuery to grab radio buttons and some vanilla JavaScript to see if the returned radio buttons are checked or not.
var rbVal = ""; initalises a new variable with an empty string "".
var rbBtn = JQuery("[name=\"myRadioButton[]\"]"); fetches all elements from the document that are called myRadioButton[].
for (var i = 0; i < rbBtn.length; i++) loops through each of the returned elements (there might be more than one as myRadioButton[] is an array of radio buttons hence the [] at the end). i is the current index in the array of returned elements.
if (rbBtn[i].checked) sees whether the radio button is "checked" ("on", if you like).
rbVal += rbBtn[i].value;: If the current radio button is checked (remember, for() loops through them all), fetch it's value attribute and append it (add it onto) whatever is currently in rbVal.
For example, if rbVal contains Hello and the radio button's value is world then rbVal would end up containing Hello world.
if( rbVal != "yes" ) If the value in rbVal doesn't equal (!=) yes, then we call the doSomething function.
If rbVal does contain yes, then we want to call the doSomethingElse function:
else {
doSomethingElse;
}
Other than the fact that my brief research tells me the latter will return a collection rather than a a single element with the ID passed.
Consider the following code:
function validateAllFields()
{
var clientid = document.getElementById("clientid");
var programs = document.getElementById("programs");
var startmonth = document.getElementById("startmonth");
var startday = document.getElementById("startday");
var startyear = document.getElementById("startyear");
var completed = document.getElementsByName("completed");
var goals = document.getElementsByName("goals");
var errors = document.getElementById("errorMsg");
errors.innerHTML = "";
if(isNumeric(clientid, errors, "Please enter a valid client ID")){
if(madeSelection(programs, errors, "Please select a program from the drop-down list")){
if(madeSelection(startmonth, errors, "Please enter a month for the start date")){
if(madeSelection(startday, errors, "Please enter a day for the start date")){
if(madeSelection(startyear, errors, "Please enter a year for the start date")){
if(checked(completed, errors, "Please choose an option that indicate whether the client has completed the program")){
if(checked(goals, errors, "Please choose an option that indicate whether the client has met his/her goals.")){
window.alert("GOT IN TO RETURN TRUE");
return true;
}
}
}
}
}
}
}
return false;
}
</script>
The above code works perfectly after placing it in the onsubmit handler of the form. However, earlier, for the elements (programs, startmonth, startday, startyear) I was using getElementsByName(), the following happened:
The code seems to get to the second line of the if blocks "if(madeSelection(programs...." and it displayed the error msg via innerHTML for a brief second and
Proceeded to submit the form AS IF the JS had indeed returned true. As you can tell, there is a popup alert right before returning true and the popup DID NOT show up at all.
Bad data was submitted to my test database because the form had not been validated. (yet to write server-side validation with this form, but I will).
please assume the elements programs, startmonth, startday, and startyear are drop-down lists with the same id and name attributes.
Also, the madeSelection function is given as:
function madeSelection(element, error, msg) {
if (element[0].value == "none" || element[0].valueOf == "none" || element[0].value == "") {
error.innerHTML = msg;
element.focus();
return false;
} else {
return true;
}
}
My code does work right now after I changed those elements to be using getElementById(), I was just wondering why getElementsByName presented such behavior.
<input type="text" name="foo" id="bar">
^^^^ ^^
getElementsByName gets elements by their name, getElementById gets the element by its id. There may be many elements on a page with the same name (hence getElementsByName always returns a list of elements), but there is (must) only be one element with a given id (therefore getElementById only returns a single element).
The GetElementsByName method returns an array, and when you tried to call element.focus() you got an error because there is no focus method on an array. When you get an error in the event handler it won't prevent the form from posting.
If you use GetElementById you should use element to access the element, and if you use GetElementsByName you should use element[0].
To expand a little on the answers already provided, the name attribute was provided early in the days of the browser DOM, to allow the contents of elements in forms to be submitted with reference to that name attribute, so that parameters could be passed to a CGI script at the server side. This dates from before the more modern ability to reference DOM elements for manipulation of such things as styles by JavaScript.
When the DOM was expanded to allow said modern manipulations, the id attribute was added, so that individual elements could be manipulated at will. When you want to perform DOM manipulations, you select elements to be manipulated either via the id attribute, if you're only interested in manipulating a single DOM element, or via the class attribute (suitably set by yourself), if you want to manipulate several elements together in the same manner. In this latter case, you can set the class attribute to multiple values (name strings separated by spaces), so that you can, for example, designate elements to belong to more than one class, and perform manipulations accordingly. You can mix and match id and class attributes practically at will, provided you exercise some care to avoid name clashes.
So, for example, you could have five buttons on your web page, all set to:
class="Set1"
and change the style of all those buttons, first by using a statement such as:
myButtons = document.getElementsByClassName("Set1");
to obtain an array of Element objects corresponding to your buttons, then running the following loop:
for (i=0; i<myButtons.length; i++)
myButtons[i].style.color="#FF0000";
to change the colour of the text to red. One of those buttons could additionally have an id attribute set to "Special", and you could then do something such as:
ref = document.getElementById("Special");
ref.style.backgroundColor = "#FFFF00";
to set the background colour of that one button in the set to yellow, to signal that it's intended for a special function within the set.
In short, use the name attribute for form submissions, and the id and class attributes for referring to elements you intend to perform DOM manipulations upon, or attach event handlers to, etc.
The name attribute is not designed to be unique, while the id attribute is.
<div name="nonUnique" />
<div id="unique" />
In order for the form to not be submitted, return false needs to be returned (you said you used the onsubmit handler)
in the second line of your code, because a selection is indeed returned by getElementsByName (it would work with .getElementsByName("test")[0] ) a js error is thrown. The rest of the code is not executed, therefore nothing is returned and the form by-passes the rest of the validation completely.
The getElementById method can access only one element at a time, and that is the element with the ID that you specified. The getElementsByName method is different. It collects an array of elements that have the name that you specified. You access the individual elements using an index which starts at 0.
getElementById
It will get only one element for you.
That element bears the ID that you specified inside the parentheses of getElementById().
getElementsByName
It will get a collection of elements whose names are all the same.
Each element is indexed with a number starting from 0 just like an array
You specify which element you wish to access by putting its index number into the square brackets in getElementsByName's syntax below.
function test() {
var str = document.getElementById("a").value;
console.log(str);
var str1 = document.getElementsByName("a")[0].value;
console.log(str1);
var str2 = document.getElementsByName("a")[1].value;
console.log(str2);
}
<input type="text" id="a" value="aValue" />
<br>
<br>
<input type="text" name="a" value="bValue" />
<br>
<br>
<input type="text" name="a" value="cValue" />
<br>
<br>
<button onclick="test()">Click Here</button>
I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}
Update: clarified question (I hope)
Hi.
I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.
In case of A, I ouput element "Foo".
In case of B, I output element "Bar".
Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).
I've looked at using the typeof() function:
if(typeof(element) == 'undefined') {
//do something...
}
I'm also using jQuery. So one solution could be using this:
if ($("#mydiv").length > 0){
// do something here
}
Using the above methods, makes me having to check each element before trying to retrieve any values.
The "ideal" solution would be to get values based on user privileges. E.g:
if (userPriv == A) {
//get values from element 'Foo'
}
This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.
<input type="hidden" id="userPriv" value="A" />
The other solution would be adding a value to the cookie.
setcookie("userPriv", "A");
Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.
I'm looking for opinions on which method is "the best way" to accomplis this.
Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.
var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
//...
} else if (elementB) {
//...
}
The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.
Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)
<input type="hidden" id="userPriv" value="A" />
...
var priv = $('#userPriv').val();
if (priv == 'A') {
//...
}
I'd still recommend checking for individual elements over checking a hidden input. It seems cleaner to me, more along the unobtrusive lines
You can use object as associative array:
var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();
In that case is much simpler to check and you will avoid "spaghetti code".